From daab14bd058de198c80b71d63e108fd788b7f5ee Mon Sep 17 00:00:00 2001 From: Jozsef Csongvai Date: Mon, 26 Jul 2021 12:00:59 -0400 Subject: Revert "Renaming Files having BluePrint to have Blueprint" The renaming in CCSDK-3098 caused breaking changes to the grpc api and compile issues for kotlin scripts. Issue-ID: CCSDK-3385 Change-Id: I0d745cb858371678eabcb2284671c1fd76a1ab6d Signed-off-by: Jozsef Csongvai --- .../designer/api/BluePrintManagementGRPCHandler.kt | 320 ++++++++++ .../designer/api/BlueprintManagementGRPCHandler.kt | 320 ---------- .../designer/api/BlueprintModelController.kt | 36 +- .../designer/api/DesignerApiData.kt | 6 +- .../designer/api/ModelTypeController.kt | 4 +- .../designer/api/ResourceDictionaryController.kt | 8 +- .../BluePrintArtifactDefinitionEnhancerImpl.kt | 92 +++ .../BluePrintAttributeDefinitionEnhancerImpl.kt | 55 ++ .../api/enhancer/BluePrintEnhancerServiceImpl.kt | 103 ++++ .../enhancer/BluePrintNodeTemplateEnhancerImpl.kt | 68 +++ .../api/enhancer/BluePrintNodeTypeEnhancerImpl.kt | 157 +++++ .../enhancer/BluePrintPolicyTypeEnhancerImpl.kt | 44 ++ .../BluePrintPropertyDefinitionEnhancerImpl.kt | 64 ++ .../BluePrintRelationshipTemplateEnhancerImpl.kt | 69 +++ .../BluePrintRelationshipTypeEnhancerImpl.kt | 87 +++ .../BluePrintServiceTemplateEnhancerImpl.kt | 67 +++ .../BluePrintTopologyTemplateEnhancerImpl.kt | 74 +++ .../enhancer/BluePrintTypeEnhancerServiceImpl.kt | 84 +++ .../api/enhancer/BluePrintWorkflowEnhancerImpl.kt | 233 ++++++++ .../BlueprintArtifactDefinitionEnhancerImpl.kt | 92 --- .../BlueprintAttributeDefinitionEnhancerImpl.kt | 55 -- .../api/enhancer/BlueprintEnhancerServiceImpl.kt | 103 ---- .../enhancer/BlueprintNodeTemplateEnhancerImpl.kt | 68 --- .../api/enhancer/BlueprintNodeTypeEnhancerImpl.kt | 157 ----- .../enhancer/BlueprintPolicyTypeEnhancerImpl.kt | 44 -- .../BlueprintPropertyDefinitionEnhancerImpl.kt | 64 -- .../BlueprintRelationshipTemplateEnhancerImpl.kt | 69 --- .../BlueprintRelationshipTypeEnhancerImpl.kt | 87 --- .../BlueprintServiceTemplateEnhancerImpl.kt | 67 --- .../BlueprintTopologyTemplateEnhancerImpl.kt | 74 --- .../enhancer/BlueprintTypeEnhancerServiceImpl.kt | 84 --- .../api/enhancer/BlueprintWorkflowEnhancerImpl.kt | 233 -------- .../enhancer/ResourceAssignmentEnhancerService.kt | 26 +- .../enhancer/ResourceDefinitionEnhancerService.kt | 28 +- .../designer/api/handler/BluePrintModelHandler.kt | 643 +++++++++++++++++++++ .../designer/api/handler/BlueprintModelHandler.kt | 643 --------------------- .../designer/api/handler/ModelTypeHandler.kt | 6 +- .../api/handler/ResourceDictionaryHandler.kt | 10 +- .../api/load/BluePrintCatalogLoadService.kt | 69 +++ .../api/load/BluePrintDatabaseLoadService.kt | 67 +++ .../api/load/BlueprintCatalogLoadService.kt | 69 --- .../api/load/BlueprintDatabaseLoadService.kt | 67 --- .../designer/api/load/ModelTypeLoadService.kt | 14 +- .../api/load/ResourceDictionaryLoadService.kt | 4 +- .../api/service/BluePrintRepoServiceImpl.kt | 115 ++++ .../api/service/BlueprintRepoServiceImpl.kt | 115 ---- .../designer/api/utils/BluePrintEnhancerUtils.kt | 191 ++++++ .../designer/api/utils/BlueprintEnhancerUtils.kt | 191 ------ .../designer/api/utils/ModelTypeValidator.kt | 28 +- .../api/BluePrintManagementGRPCHandlerTest.kt | 252 ++++++++ .../api/BlueprintManagementGRPCHandlerTest.kt | 252 -------- .../designer/api/BlueprintModelControllerTest.kt | 14 +- .../designer/api/ModelTypeControllerTest.kt | 12 +- .../designer/api/TestDatabaseConfiguration.kt | 4 +- .../enhancer/BluePrintEnhancerServiceImplTest.kt | 114 ++++ .../enhancer/BlueprintEnhancerServiceImplTest.kt | 114 ---- .../designer/api/handler/ModelTypeServiceTest.kt | 14 +- .../api/repository/ModelTypeReactRepositoryTest.kt | 18 +- .../api/utils/BluePrintEnhancerUtilsTest.kt | 68 +++ .../api/utils/BlueprintEnhancerUtilsTest.kt | 68 --- 60 files changed, 3152 insertions(+), 3152 deletions(-) create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandler.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTemplateEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTypeEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintArtifactDefinitionEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintAttributeDefinitionEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTemplateEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTypeEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPolicyTypeEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPropertyDefinitionEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTemplateEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTypeEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintServiceTemplateEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTopologyTemplateEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTypeEnhancerServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintWorkflowEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BlueprintModelHandler.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintCatalogLoadService.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintDatabaseLoadService.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BlueprintRepoServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtils.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandlerTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImplTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtilsTest.kt (limited to 'ms/blueprintsprocessor/modules/inbounds/designer-api/src') diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt new file mode 100644 index 000000000..54f8dbc9d --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt @@ -0,0 +1,320 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api + +import com.google.protobuf.ByteString +import com.google.protobuf.util.JsonFormat +import io.grpc.stub.StreamObserver +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.BluePrintModelHandler +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.common.api.Status +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString +import org.onap.ccsdk.cds.controllerblueprints.core.emptyTONull +import org.onap.ccsdk.cds.controllerblueprints.core.utils.currentTimestamp +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintBootstrapInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintDownloadInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementOutput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintRemoveInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction +import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk +import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction +import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction +import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes +import org.onap.ccsdk.cds.error.catalog.core.GrpcErrorCodes +import org.onap.ccsdk.cds.error.catalog.core.utils.errorMessageOrDefault +import org.onap.ccsdk.cds.error.catalog.services.ErrorCatalogService +import org.slf4j.LoggerFactory +import org.springframework.security.access.prepost.PreAuthorize +import org.springframework.stereotype.Service + +// TODO("Convert to coroutines handler") +@Service +open class BluePrintManagementGRPCHandler( + private val bluePrintModelHandler: BluePrintModelHandler, + private val errorCatalogService: ErrorCatalogService +) : + BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() { + + private val log = LoggerFactory.getLogger(BluePrintManagementGRPCHandler::class.java) + + @PreAuthorize("hasRole('USER')") + override fun uploadBlueprint( + request: BluePrintUploadInput, + responseObserver: StreamObserver + ) { + + runBlocking { + // TODO("catch if request id is missing") + log.info("request(${request.commonHeader.requestId})") + try { + /** Get the file byte array */ + val byteArray = request.fileChunk.chunk.toByteArray() + + /** Get the Upload Action */ + val uploadAction = request.actionIdentifiers?.actionName.emptyTONull() + ?: UploadAction.DRAFT.toString() + + when (uploadAction) { + UploadAction.DRAFT.toString() -> { + val blueprintModel = bluePrintModelHandler.upload(byteArray, false) + responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString())) + } + UploadAction.PUBLISH.toString() -> { + val blueprintModel = bluePrintModelHandler.upload(byteArray, true) + responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString())) + } + UploadAction.VALIDATE.toString() -> { + // TODO("Not Implemented") + responseObserver.onNext( + failStatus( + request.commonHeader, + "Upload action($uploadAction) not implemented", + BluePrintProcessorException("Not Implemented") + ) + ) + } + UploadAction.ENRICH.toString() -> { + val enrichedByteArray = bluePrintModelHandler.enrichBlueprintFileSource(byteArray) + responseObserver.onNext(outputWithFileBytes(request.commonHeader, enrichedByteArray)) + } + else -> { + responseObserver.onNext( + failStatus( + request.commonHeader, + "Upload action($uploadAction) not implemented", + BluePrintProcessorException("Not implemented") + ) + ) + } + } + } catch (e: Exception) { + responseObserver.onNext( + failStatus( + request.commonHeader, + "request(${request.commonHeader.requestId}): Failed to upload CBA", e + ) + ) + } finally { + responseObserver.onCompleted() + } + } + } + + @PreAuthorize("hasRole('USER')") + override fun downloadBlueprint( + request: BluePrintDownloadInput, + responseObserver: StreamObserver + ) { + runBlocking { + val blueprintName = request.actionIdentifiers.blueprintName + val blueprintVersion = request.actionIdentifiers.blueprintVersion + val blueprint = "blueprint $blueprintName:$blueprintVersion" + + /** Get the Search Action */ + val searchAction = request.actionIdentifiers?.actionName.emptyTONull() + ?: DownloadAction.SEARCH.toString() + + log.info("request(${request.commonHeader.requestId}): Received download $blueprint") + try { + when (searchAction) { + DownloadAction.SEARCH.toString() -> { + val downloadByteArray = bluePrintModelHandler.download(blueprintName, blueprintVersion) + responseObserver.onNext(outputWithFileBytes(request.commonHeader, downloadByteArray)) + } + else -> { + responseObserver.onNext( + failStatus( + request.commonHeader, + "Search action($searchAction) not implemented", + BluePrintProcessorException("Not implemented") + ) + ) + } + } + } catch (e: Exception) { + responseObserver.onNext( + failStatus( + request.commonHeader, + "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e + ) + ) + } finally { + responseObserver.onCompleted() + } + } + } + + @PreAuthorize("hasRole('USER')") + override fun removeBlueprint( + request: BluePrintRemoveInput, + responseObserver: + StreamObserver + ) { + + runBlocking { + val blueprintName = request.actionIdentifiers.blueprintName + val blueprintVersion = request.actionIdentifiers.blueprintVersion + val blueprint = "blueprint $blueprintName:$blueprintVersion" + + log.info("request(${request.commonHeader.requestId}): Received delete $blueprint") + + /** Get the Remove Action */ + val removeAction = request.actionIdentifiers?.actionName.emptyTONull() + ?: RemoveAction.DEFAULT.toString() + + try { + when (removeAction) { + RemoveAction.DEFAULT.toString() -> { + bluePrintModelHandler.deleteBlueprintModel(blueprintName, blueprintVersion) + responseObserver.onNext(successStatus(request.commonHeader)) + } + else -> { + responseObserver.onNext( + failStatus( + request.commonHeader, + "Remove action($removeAction) not implemented", + BluePrintProcessorException("Not implemented") + ) + ) + } + } + } catch (e: Exception) { + responseObserver.onNext( + failStatus( + request.commonHeader, + "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e + ) + ) + } finally { + responseObserver.onCompleted() + } + } + } + + override fun bootstrapBlueprint( + request: BluePrintBootstrapInput, + responseObserver: StreamObserver + ) { + runBlocking { + try { + log.info("request(${request.commonHeader.requestId}): Received bootstrap request") + val bootstrapRequest = BootstrapRequest().apply { + loadModelType = request.loadModelType + loadResourceDictionary = request.loadResourceDictionary + loadCBA = request.loadCBA + } + /** Perform bootstrap of Model Types, Resource Definitions and CBA */ + bluePrintModelHandler.bootstrapBlueprint(bootstrapRequest) + responseObserver.onNext(successStatus(request.commonHeader)) + } catch (e: Exception) { + responseObserver.onNext( + failStatus( + request.commonHeader, + "request(${request.commonHeader.requestId}): Failed to bootstrap", e + ) + ) + } finally { + responseObserver.onCompleted() + } + } + } + + private fun outputWithFileBytes(header: CommonHeader, byteArray: ByteArray): BluePrintManagementOutput = + BluePrintManagementOutput.newBuilder() + .setCommonHeader(header) + .setFileChunk(FileChunk.newBuilder().setChunk(ByteString.copyFrom(byteArray))) + .setStatus( + Status.newBuilder() + .setTimestamp(currentTimestamp()) + .setEventType(EventType.EVENT_COMPONENT_EXECUTED) + .setMessage(BluePrintConstants.STATUS_SUCCESS) + .setCode(200) + .build() + ) + .build() + + private fun successStatus(header: CommonHeader, propertyContent: String? = null): BluePrintManagementOutput { + // Populate Response Payload + val propertiesBuilder = BluePrintManagementOutput.newBuilder().propertiesBuilder + propertyContent?.let { + JsonFormat.parser().merge(propertyContent, propertiesBuilder) + } + return BluePrintManagementOutput.newBuilder() + .setCommonHeader(header) + .setProperties(propertiesBuilder.build()) + .setStatus( + Status.newBuilder() + .setTimestamp(currentTimestamp()) + .setMessage(BluePrintConstants.STATUS_SUCCESS) + .setEventType(EventType.EVENT_COMPONENT_EXECUTED) + .setCode(200) + .build() + ) + .build() + } + + private fun failStatus(header: CommonHeader, message: String, e: Exception): BluePrintManagementOutput { + log.error(message, e) + return if (e is BluePrintProcessorException) onErrorCatalog(header, message, e) else onError(header, message, e) + } + + private fun onError(header: CommonHeader, message: String, error: Exception): BluePrintManagementOutput { + val code = GrpcErrorCodes.code(ErrorCatalogCodes.GENERIC_FAILURE) + return BluePrintManagementOutput.newBuilder() + .setCommonHeader(header) + .setStatus( + Status.newBuilder() + .setTimestamp(currentTimestamp()) + .setMessage(BluePrintConstants.STATUS_FAILURE) + .setEventType(EventType.EVENT_COMPONENT_FAILURE) + .setErrorMessage("Error : $message \n Details: ${error.errorMessageOrDefault()}") + .setCode(code) + .build() + ) + .build() + } + + private fun onErrorCatalog(header: CommonHeader, message: String, error: BluePrintProcessorException): + BluePrintManagementOutput { + val err = if (error.protocol == "") { + error.grpc(ErrorCatalogCodes.GENERIC_FAILURE) + } else { + error.convertToGrpc() + } + val errorPayload = errorCatalogService.errorPayload(err.addErrorPayloadMessage(message)) + return BluePrintManagementOutput.newBuilder() + .setCommonHeader(header) + .setStatus( + Status.newBuilder() + .setTimestamp(currentTimestamp()) + .setMessage(BluePrintConstants.STATUS_FAILURE) + .setEventType(EventType.EVENT_COMPONENT_FAILURE) + .setErrorMessage("Error : ${errorPayload.message}") + .setCode(errorPayload.code) + .build() + ) + .build() + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandler.kt deleted file mode 100644 index 97e43ec89..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandler.kt +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api - -import com.google.protobuf.ByteString -import com.google.protobuf.util.JsonFormat -import io.grpc.stub.StreamObserver -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.BlueprintModelHandler -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.common.api.Status -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString -import org.onap.ccsdk.cds.controllerblueprints.core.emptyTONull -import org.onap.ccsdk.cds.controllerblueprints.core.utils.currentTimestamp -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintBootstrapInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintDownloadInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementOutput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementServiceGrpc -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintRemoveInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintUploadInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction -import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk -import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction -import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction -import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes -import org.onap.ccsdk.cds.error.catalog.core.GrpcErrorCodes -import org.onap.ccsdk.cds.error.catalog.core.utils.errorMessageOrDefault -import org.onap.ccsdk.cds.error.catalog.services.ErrorCatalogService -import org.slf4j.LoggerFactory -import org.springframework.security.access.prepost.PreAuthorize -import org.springframework.stereotype.Service - -// TODO("Convert to coroutines handler") -@Service -open class BlueprintManagementGRPCHandler( - private val bluePrintModelHandler: BlueprintModelHandler, - private val errorCatalogService: ErrorCatalogService -) : - BlueprintManagementServiceGrpc.BlueprintManagementServiceImplBase() { - - private val log = LoggerFactory.getLogger(BlueprintManagementGRPCHandler::class.java) - - @PreAuthorize("hasRole('USER')") - override fun uploadBlueprint( - request: BlueprintUploadInput, - responseObserver: StreamObserver - ) { - - runBlocking { - // TODO("catch if request id is missing") - log.info("request(${request.commonHeader.requestId})") - try { - /** Get the file byte array */ - val byteArray = request.fileChunk.chunk.toByteArray() - - /** Get the Upload Action */ - val uploadAction = request.actionIdentifiers?.actionName.emptyTONull() - ?: UploadAction.DRAFT.toString() - - when (uploadAction) { - UploadAction.DRAFT.toString() -> { - val blueprintModel = bluePrintModelHandler.upload(byteArray, false) - responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString())) - } - UploadAction.PUBLISH.toString() -> { - val blueprintModel = bluePrintModelHandler.upload(byteArray, true) - responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString())) - } - UploadAction.VALIDATE.toString() -> { - // TODO("Not Implemented") - responseObserver.onNext( - failStatus( - request.commonHeader, - "Upload action($uploadAction) not implemented", - BlueprintProcessorException("Not Implemented") - ) - ) - } - UploadAction.ENRICH.toString() -> { - val enrichedByteArray = bluePrintModelHandler.enrichBlueprintFileSource(byteArray) - responseObserver.onNext(outputWithFileBytes(request.commonHeader, enrichedByteArray)) - } - else -> { - responseObserver.onNext( - failStatus( - request.commonHeader, - "Upload action($uploadAction) not implemented", - BlueprintProcessorException("Not implemented") - ) - ) - } - } - } catch (e: Exception) { - responseObserver.onNext( - failStatus( - request.commonHeader, - "request(${request.commonHeader.requestId}): Failed to upload CBA", e - ) - ) - } finally { - responseObserver.onCompleted() - } - } - } - - @PreAuthorize("hasRole('USER')") - override fun downloadBlueprint( - request: BlueprintDownloadInput, - responseObserver: StreamObserver - ) { - runBlocking { - val blueprintName = request.actionIdentifiers.blueprintName - val blueprintVersion = request.actionIdentifiers.blueprintVersion - val blueprint = "blueprint $blueprintName:$blueprintVersion" - - /** Get the Search Action */ - val searchAction = request.actionIdentifiers?.actionName.emptyTONull() - ?: DownloadAction.SEARCH.toString() - - log.info("request(${request.commonHeader.requestId}): Received download $blueprint") - try { - when (searchAction) { - DownloadAction.SEARCH.toString() -> { - val downloadByteArray = bluePrintModelHandler.download(blueprintName, blueprintVersion) - responseObserver.onNext(outputWithFileBytes(request.commonHeader, downloadByteArray)) - } - else -> { - responseObserver.onNext( - failStatus( - request.commonHeader, - "Search action($searchAction) not implemented", - BlueprintProcessorException("Not implemented") - ) - ) - } - } - } catch (e: Exception) { - responseObserver.onNext( - failStatus( - request.commonHeader, - "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e - ) - ) - } finally { - responseObserver.onCompleted() - } - } - } - - @PreAuthorize("hasRole('USER')") - override fun removeBlueprint( - request: BlueprintRemoveInput, - responseObserver: - StreamObserver - ) { - - runBlocking { - val blueprintName = request.actionIdentifiers.blueprintName - val blueprintVersion = request.actionIdentifiers.blueprintVersion - val blueprint = "blueprint $blueprintName:$blueprintVersion" - - log.info("request(${request.commonHeader.requestId}): Received delete $blueprint") - - /** Get the Remove Action */ - val removeAction = request.actionIdentifiers?.actionName.emptyTONull() - ?: RemoveAction.DEFAULT.toString() - - try { - when (removeAction) { - RemoveAction.DEFAULT.toString() -> { - bluePrintModelHandler.deleteBlueprintModel(blueprintName, blueprintVersion) - responseObserver.onNext(successStatus(request.commonHeader)) - } - else -> { - responseObserver.onNext( - failStatus( - request.commonHeader, - "Remove action($removeAction) not implemented", - BlueprintProcessorException("Not implemented") - ) - ) - } - } - } catch (e: Exception) { - responseObserver.onNext( - failStatus( - request.commonHeader, - "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e - ) - ) - } finally { - responseObserver.onCompleted() - } - } - } - - override fun bootstrapBlueprint( - request: BlueprintBootstrapInput, - responseObserver: StreamObserver - ) { - runBlocking { - try { - log.info("request(${request.commonHeader.requestId}): Received bootstrap request") - val bootstrapRequest = BootstrapRequest().apply { - loadModelType = request.loadModelType - loadResourceDictionary = request.loadResourceDictionary - loadCBA = request.loadCBA - } - /** Perform bootstrap of Model Types, Resource Definitions and CBA */ - bluePrintModelHandler.bootstrapBlueprint(bootstrapRequest) - responseObserver.onNext(successStatus(request.commonHeader)) - } catch (e: Exception) { - responseObserver.onNext( - failStatus( - request.commonHeader, - "request(${request.commonHeader.requestId}): Failed to bootstrap", e - ) - ) - } finally { - responseObserver.onCompleted() - } - } - } - - private fun outputWithFileBytes(header: CommonHeader, byteArray: ByteArray): BlueprintManagementOutput = - BlueprintManagementOutput.newBuilder() - .setCommonHeader(header) - .setFileChunk(FileChunk.newBuilder().setChunk(ByteString.copyFrom(byteArray))) - .setStatus( - Status.newBuilder() - .setTimestamp(currentTimestamp()) - .setEventType(EventType.EVENT_COMPONENT_EXECUTED) - .setMessage(BlueprintConstants.STATUS_SUCCESS) - .setCode(200) - .build() - ) - .build() - - private fun successStatus(header: CommonHeader, propertyContent: String? = null): BlueprintManagementOutput { - // Populate Response Payload - val propertiesBuilder = BlueprintManagementOutput.newBuilder().propertiesBuilder - propertyContent?.let { - JsonFormat.parser().merge(propertyContent, propertiesBuilder) - } - return BlueprintManagementOutput.newBuilder() - .setCommonHeader(header) - .setProperties(propertiesBuilder.build()) - .setStatus( - Status.newBuilder() - .setTimestamp(currentTimestamp()) - .setMessage(BlueprintConstants.STATUS_SUCCESS) - .setEventType(EventType.EVENT_COMPONENT_EXECUTED) - .setCode(200) - .build() - ) - .build() - } - - private fun failStatus(header: CommonHeader, message: String, e: Exception): BlueprintManagementOutput { - log.error(message, e) - return if (e is BlueprintProcessorException) onErrorCatalog(header, message, e) else onError(header, message, e) - } - - private fun onError(header: CommonHeader, message: String, error: Exception): BlueprintManagementOutput { - val code = GrpcErrorCodes.code(ErrorCatalogCodes.GENERIC_FAILURE) - return BlueprintManagementOutput.newBuilder() - .setCommonHeader(header) - .setStatus( - Status.newBuilder() - .setTimestamp(currentTimestamp()) - .setMessage(BlueprintConstants.STATUS_FAILURE) - .setEventType(EventType.EVENT_COMPONENT_FAILURE) - .setErrorMessage("Error : $message \n Details: ${error.errorMessageOrDefault()}") - .setCode(code) - .build() - ) - .build() - } - - private fun onErrorCatalog(header: CommonHeader, message: String, error: BlueprintProcessorException): - BlueprintManagementOutput { - val err = if (error.protocol == "") { - error.grpc(ErrorCatalogCodes.GENERIC_FAILURE) - } else { - error.convertToGrpc() - } - val errorPayload = errorCatalogService.errorPayload(err.addErrorPayloadMessage(message)) - return BlueprintManagementOutput.newBuilder() - .setCommonHeader(header) - .setStatus( - Status.newBuilder() - .setTimestamp(currentTimestamp()) - .setMessage(BlueprintConstants.STATUS_FAILURE) - .setEventType(EventType.EVENT_COMPONENT_FAILURE) - .setErrorMessage("Error : ${errorPayload.message}") - .setCode(errorPayload.code) - .build() - ) - .build() - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt index f19824d47..66d4b0e16 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt @@ -25,10 +25,10 @@ import io.swagger.annotations.ApiResponse import io.swagger.annotations.ApiResponses import org.jetbrains.annotations.NotNull import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.BlueprintModelHandler +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.BluePrintModelHandler import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintSortByOption import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.mdcWebCoroutineScope -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString import org.springframework.core.io.Resource import org.springframework.data.domain.Page @@ -62,7 +62,7 @@ import org.springframework.web.bind.annotation.RestController value = "Blueprint Model Catalog", description = "Manages all blueprint models which are available in CDS" ) -open class BlueprintModelController(private val bluePrintModelHandler: BlueprintModelHandler) { +open class BlueprintModelController(private val bluePrintModelHandler: BluePrintModelHandler) { @PostMapping( path = arrayOf("/bootstrap"), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE), @@ -79,7 +79,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 500, message = "Internal Server Error") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun bootstrap( @ApiParam(required = true, value = "Specifies which elements to load") @@ -100,7 +100,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 500, message = "Internal Server Error") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun saveBlueprint( @ApiParam(name = "file", value = "CBA file to be uploaded (example: cba.zip)", required = true) @@ -162,7 +162,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint @PathVariable(value = "keyword") keyWord: String ): List = mdcWebCoroutineScope { - bluePrintModelHandler.searchBlueprintModelsByKeyWord(keyWord) + bluePrintModelHandler.searchBluePrintModelsByKeyWord(keyWord) } @GetMapping("/paged/meta-data/{keyword}", produces = [MediaType.APPLICATION_JSON_VALUE]) @@ -186,7 +186,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint offset, limit, Sort.Direction.fromString(sortType), sort.columnName ) - return this.bluePrintModelHandler.searchBlueprintModelsByKeyWordPaged(keyWord, pageRequest) + return this.bluePrintModelHandler.searchBluePrintModelsByKeyWordPaged(keyWord, pageRequest) } @DeleteMapping("/{id}") @@ -198,7 +198,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 200, message = "OK"), ApiResponse(code = 404, message = "RESOURCE_NOT_FOUND") ) - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun deleteBlueprint( @ApiParam(value = "ID of the blueprint model to delete", required = true, example = "67ec1f96-ab55-4b81-aff9-23ee0ed1d7a4") @@ -218,7 +218,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 404, message = "Not Found") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun getBlueprintByNameAndVersion( @ApiParam(value = "Name of the blueprint model", required = true, example = "pnf_netconf") @PathVariable(value = "name") name: String, @@ -242,7 +242,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 404, message = "Not Found") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun downloadBlueprintByNameAndVersion( @ApiParam(value = "Name of the blueprint model", required = true, example = "pnf_netconf") @PathVariable(value = "name") name: String, @@ -262,7 +262,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 404, message = "Not Found") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun getBlueprintModel( @ApiParam(value = "ID of the blueprint model to search for", required = true, example = "67ec1f96-ab55-4b81-aff9-23ee0ed1d7a4") @@ -281,9 +281,9 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 404, message = "Not Found") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") - suspend fun downloadBlueprint( + suspend fun downloadBluePrint( @ApiParam(value = "ID of the blueprint model to download", required = true, example = "67ec1f96-ab55-4b81-aff9-23ee0ed1d7a4") @PathVariable(value = "id") id: String ): ResponseEntity = @@ -304,7 +304,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint "The enrichment process will complete the package by providing all the definition of types used." ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun enrichBlueprint( @ApiParam(name = "file", value = "CBA zip file to be uploaded (example: cba_unenriched.zip)", required = true) @@ -330,7 +330,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 503, message = "Service Unavailable") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun enrichAndPubishlueprint( @ApiParam(name = "file", value = "Unenriched CBA zip file to be uploaded (example: cba_unenriched.zip)", required = true) @@ -346,7 +346,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint response = BlueprintModelSearch::class ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun publishBlueprint( @ApiParam(name = "file", value = "Enriched CBA zip file to be uploaded (example: cba_enriched.zip)", required = true) @@ -405,7 +405,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint "Inputs, outputs and data types of workflow is returned." ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun workflowSpec( @ApiParam(required = true, value = "Blueprint and workflow identification") @@ -428,7 +428,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint notes = "Get all available workflows of a Blueprint identified by its name and version." ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun getWorkflowList( @ApiParam(value = "Name of the blueprint model", example = "pnf_netconf", required = true) diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt index 5406b7792..741a9115c 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt @@ -20,9 +20,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ResourceDictionary -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.DATA_TYPE_JSON -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.DEFAULT_VERSION_NUMBER -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.TOSCA_SPEC +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.DATA_TYPE_JSON +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.DEFAULT_VERSION_NUMBER +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.TOSCA_SPEC import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt index eb9a98091..3689f735e 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt @@ -22,7 +22,7 @@ import io.swagger.annotations.ApiOperation import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ModelTypeHandler import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.mdcWebCoroutineScope -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.springframework.http.MediaType import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping @@ -86,7 +86,7 @@ open class ModelTypeController(private val modelTypeHandler: ModelTypeHandler) { response = ModelType::class ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun saveModelType(@RequestBody modelType: ModelType): ModelType = mdcWebCoroutineScope { modelTypeHandler.saveModel(modelType) } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt index 62997cc1b..8d69ccdde 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt @@ -22,7 +22,7 @@ import io.swagger.annotations.ApiParam import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ResourceDictionary import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ResourceDictionaryHandler import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.mdcWebCoroutineScope -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceSourceMapping import org.springframework.http.MediaType @@ -50,7 +50,7 @@ open class ResourceDictionaryController(private val resourceDictionaryHandler: R response = ResourceDictionary::class ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun getResourceDictionaryByName( @ApiParam(value = "Name of the resource", required = true, example = "\"hostname\"") @PathVariable(value = "name") name: String @@ -69,7 +69,7 @@ open class ResourceDictionaryController(private val resourceDictionaryHandler: R response = ResourceDictionary::class ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun saveResourceDictionary( @ApiParam(value = "Resource dictionary to store", required = true) @RequestBody dataDictionary: ResourceDictionary @@ -90,7 +90,7 @@ open class ResourceDictionaryController(private val resourceDictionaryHandler: R response = ResourceDefinition::class ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun saveResourceDictionary( @ApiParam(value = "Resource definition to generate", required = true) @RequestBody resourceDefinition: ResourceDefinition diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt new file mode 100644 index 000000000..c63c7260d --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt @@ -0,0 +1,92 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.springframework.stereotype.Service + +@Service +open class BluePrintArtifactDefinitionEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService +) : + BluePrintArtifactDefinitionEnhancer { + + companion object { + + const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource" + } + + private val log = logger(BluePrintArtifactDefinitionEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactDefinition: ArtifactDefinition) { + log.info("enhancing ArtifactDefinition($name)") + + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val artifactTypeName = artifactDefinition.type + ?: throw BluePrintException("artifact type is missing for ArtifactDefinition($name)") + + // Populate Artifact Type + BluePrintEnhancerUtils.populateArtifactType(bluePrintContext, bluePrintRepoService, artifactTypeName) + + when (artifactTypeName) { + ARTIFACT_TYPE_MAPPING_SOURCE -> { + enhanceMappingType(name, artifactDefinition) + } + } + } + + // Enhance Resource Mapping + open fun enhanceMappingType(name: String, artifactDefinition: ArtifactDefinition) { + + val artifactFilePath = "${bluePrintContext.rootPath}/${artifactDefinition.file}" + + val alreadyEnhancedKey = "enhanced-${artifactDefinition.file}" + val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey) + + log.info("enhancing resource mapping file(${artifactDefinition.file}) already enhanced($alreadyEnhanced)") + + if (!alreadyEnhanced) { + val resourceAssignments: MutableList = JacksonUtils.getListFromFile(artifactFilePath, ResourceAssignment::class.java) + as? MutableList + ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($artifactFilePath)") + + // Call Resource Assignment Enhancer + resourceAssignmentEnhancerService.enhanceBluePrint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments) + + bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive()) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt new file mode 100644 index 000000000..030fbe8ae --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt @@ -0,0 +1,55 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService + +class BluePrintAttributeDefinitionEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintAttributeDefinitionEnhancer { + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, attributeDefinition: AttributeDefinition) { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val propertyType = attributeDefinition.type + if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) { + } else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) { + val entrySchema = attributeDefinition.entrySchema + ?: throw BluePrintException("Entry Schema is missing for collection property($name)") + + if (!BluePrintTypes.validPrimitiveTypes().contains(entrySchema.type)) { + BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type) + } + } else { + BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt new file mode 100644 index 000000000..8240b1de1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt @@ -0,0 +1,103 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils +import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes +import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault +import org.springframework.stereotype.Service +import java.io.IOException +import java.util.UUID + +@Service +open class BluePrintEnhancerServiceImpl( + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + private val resourceDefinitionEnhancerService: ResourceDefinitionEnhancerService +) : BluePrintEnhancerService { + + private val log = logger(BluePrintEnhancerServiceImpl::class) + + override suspend fun enhance(basePath: String, enrichedBasePath: String): BluePrintContext { + + // Copy the Blueprint Content to Target Location + BluePrintFileUtils.copyBluePrint(basePath, enrichedBasePath) + + // Enhance the Blueprint + return enhance(enrichedBasePath) + } + + @Throws(BluePrintException::class) + override suspend fun enhance(basePath: String): BluePrintContext { + + log.info("Enhancing blueprint($basePath)") + val blueprintRuntimeService = BluePrintMetadataUtils + .getBaseEnhancementBluePrintRuntime(UUID.randomUUID().toString(), basePath) + + try { + + bluePrintTypeEnhancerService.enhanceServiceTemplate( + blueprintRuntimeService, "service_template", + blueprintRuntimeService.bluePrintContext().serviceTemplate + ) + + log.info("##### Enhancing blueprint Resource Definitions") + val resourceDefinitions = resourceDefinitionEnhancerService.enhance( + bluePrintTypeEnhancerService, + blueprintRuntimeService + ) + + // Write the Enhanced Blueprint Definitions + BluePrintFileUtils.writeEnhancedBluePrint(blueprintRuntimeService.bluePrintContext()) + + // Write the Enhanced Blueprint Resource Definitions + ResourceDictionaryUtils.writeResourceDefinitionTypes(basePath, resourceDefinitions) + + if (blueprintRuntimeService.getBluePrintError().allErrors().isNotEmpty()) { + throw BluePrintException(blueprintRuntimeService.getBluePrintError().allErrors().toString()) + } + } catch (e: BluePrintProcessorException) { + val errorMsg = "Error while enriching the CBA package." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong blueprint definitions or resource definitions." + ) + } catch (e: IOException) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "IO Error: CBA file failed enrichment - ${e.message}", e.errorCauseOrDefault() + ) + } catch (e: Exception) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "Error in Enriching CBA: ${e.message}", e.errorCauseOrDefault() + ) + } + return blueprintRuntimeService.bluePrintContext() + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt new file mode 100644 index 000000000..6ca0b2d14 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt @@ -0,0 +1,68 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintNodeTemplateEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintNodeTemplateEnhancer { + + private val log = logger(BluePrintNodeTemplateEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) { + log.info("***** Enhancing NodeTemplate($name)") + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val nodeTypeName = nodeTemplate.type + // Get NodeType from Repo and Update Service Template + val nodeType = BluePrintEnhancerUtils.populateNodeType(bluePrintContext, bluePrintRepoService, nodeTypeName) + + // Enrich NodeType + bluePrintTypeEnhancerService.enhanceNodeType(bluePrintRuntimeService, nodeTypeName, nodeType) + + // Enrich Node Template Artifacts + enhanceNodeTemplateArtifactDefinition(name, nodeTemplate) + } + + open fun enhanceNodeTemplateArtifactDefinition(nodeTemplateName: String, nodeTemplate: NodeTemplate) { + + nodeTemplate.artifacts?.forEach { artifactDefinitionName, artifactDefinition -> + // Enhance Artifacct Definitions + bluePrintTypeEnhancerService.enhanceArtifactDefinition(bluePrintRuntimeService, artifactDefinitionName, artifactDefinition) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt new file mode 100644 index 000000000..bb178b1e6 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt @@ -0,0 +1,157 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintNodeTypeEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : BluePrintNodeTypeEnhancer { + + private val log = logger(BluePrintNodeTypeEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeType: NodeType) { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val derivedFrom = nodeType.derivedFrom + + if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) { + val derivedFromNodeType = BluePrintEnhancerUtils.populateNodeType(bluePrintContext, bluePrintRepoService, name) + // Enrich NodeType + enhance(bluePrintRuntimeService, derivedFrom, derivedFromNodeType) + } + + // NodeType Attribute Definitions + enrichNodeTypeAttributes(name, nodeType) + + // NodeType Property Definitions + enrichNodeTypeProperties(name, nodeType) + + // NodeType Requirement + enrichNodeTypeRequirements(name, nodeType) + + // NodeType Capability + enrichNodeTypeCapabilityProperties(name, nodeType) + + // NodeType Interface + enrichNodeTypeInterfaces(name, nodeType) + } + + open fun enrichNodeTypeAttributes(nodeTypeName: String, nodeType: NodeType) { + nodeType.attributes?.let { + bluePrintTypeEnhancerService.enhanceAttributeDefinitions(bluePrintRuntimeService, nodeType.attributes!!) + } + } + + open fun enrichNodeTypeProperties(nodeTypeName: String, nodeType: NodeType) { + nodeType.properties?.let { + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, nodeType.properties!!) + } + } + + open fun enrichNodeTypeRequirements(nodeTypeName: String, nodeType: NodeType) { + + nodeType.requirements?.forEach { requirementName, requirementDefinition -> + // Populate Requirement Node + requirementDefinition.node?.let { requirementNodeTypeName -> + // Get Requirement NodeType from Repo and Update Service Template + val requirementNodeType = BluePrintEnhancerUtils.populateNodeType( + bluePrintContext, + bluePrintRepoService, requirementNodeTypeName + ) + // Enhance Node Type + enhance(bluePrintRuntimeService, requirementNodeTypeName, requirementNodeType) + + // Enhance Relationship Type + val relationShipTypeName = requirementDefinition.relationship + ?: throw BluePrintException( + "couldn't get relationship name for the NodeType($nodeTypeName) " + + "Requirement($requirementName)" + ) + enrichRelationShipType(relationShipTypeName) + } + } + } + + open fun enrichNodeTypeCapabilityProperties(nodeTypeName: String, nodeType: NodeType) { + nodeType.capabilities?.forEach { _, capabilityDefinition -> + capabilityDefinition.properties?.let { properties -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, properties) + } + } + } + + open fun enrichNodeTypeInterfaces(nodeTypeName: String, nodeType: NodeType) { + nodeType.interfaces?.forEach { interfaceName, interfaceObj -> + // Populate Node type Interface Operation + log.debug("Enriching NodeType({}) Interface({})", nodeTypeName, interfaceName) + populateNodeTypeInterfaceOperation(nodeTypeName, interfaceName, interfaceObj) + } + } + + open fun populateNodeTypeInterfaceOperation(nodeTypeName: String, interfaceName: String, interfaceObj: InterfaceDefinition) { + + interfaceObj.operations?.forEach { operationName, operation -> + enrichNodeTypeInterfaceOperationInputs(nodeTypeName, operationName, operation) + enrichNodeTypeInterfaceOperationOutputs(nodeTypeName, operationName, operation) + } + } + + open fun enrichNodeTypeInterfaceOperationInputs(nodeTypeName: String, operationName: String, operation: OperationDefinition) { + operation.inputs?.let { inputs -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) + } + } + + open fun enrichNodeTypeInterfaceOperationOutputs( + nodeTypeName: String, + operationName: String, + operation: OperationDefinition + ) { + operation.outputs?.let { inputs -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) + } + } + + /** + * Get the Relationship Type from database and add to Blueprint Context + */ + open fun enrichRelationShipType(relationshipName: String) { + BluePrintEnhancerUtils.populateRelationshipType(bluePrintContext, bluePrintRepoService, relationshipName) + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt new file mode 100644 index 000000000..212dc440d --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt @@ -0,0 +1,44 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPolicyTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +class BluePrintPolicyTypeEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintPolicyTypeEnhancer { + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: PolicyType) { + + this.bluePrintRuntimeService = bluePrintRuntimeService + + // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt new file mode 100644 index 000000000..eb7443443 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt @@ -0,0 +1,64 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintPropertyDefinitionEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintPropertyDefinitionEnhancer { + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val propertyType = propertyDefinition.type + if (BluePrintTypes.validPrimitiveTypes().contains(propertyType) || + BluePrintTypes.validComplexTypes().contains(propertyType) + ) { + // Do Nothing, + } else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) { + val entrySchema = propertyDefinition.entrySchema + ?: throw BluePrintException("Entry Schema is missing for collection property($name)") + + if (!BluePrintTypes.validPrimitiveTypes().contains(entrySchema.type)) { + BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type) + } + } else { + BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTemplateEnhancerImpl.kt new file mode 100644 index 000000000..c208f68e5 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTemplateEnhancerImpl.kt @@ -0,0 +1,69 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRelationshipTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintRelationshipTemplateEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintRelationshipTemplateEnhancer { + + private val log = logger(BluePrintRelationshipTemplateEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + relationshipTemplate: RelationshipTemplate + ) { + log.info("***** Enhancing RelationshipTemplate($name)") + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val relationshipTypeName = relationshipTemplate.type + // Get RelationshipType from Repo and Update Service Template + val relationshipType = + BluePrintEnhancerUtils.populateRelationshipType( + bluePrintContext, + bluePrintRepoService, + relationshipTypeName + ) + + // Enrich NodeType + bluePrintTypeEnhancerService.enhanceRelationshipType( + bluePrintRuntimeService, + relationshipTypeName, + relationshipType + ) + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTypeEnhancerImpl.kt new file mode 100644 index 000000000..b0e166090 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTypeEnhancerImpl.kt @@ -0,0 +1,87 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRelationshipTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintRelationshipTypeEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : BluePrintRelationshipTypeEnhancer { + + private val log = logger(BluePrintRelationshipTypeEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + relationshipType: RelationshipType + ) { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val derivedFrom = relationshipType.derivedFrom + + if (!BluePrintTypes.rootRelationshipTypes().contains(derivedFrom)) { + val derivedFromRelationshipType = + BluePrintEnhancerUtils.populateRelationshipType(bluePrintContext, bluePrintRepoService, name) + // Enrich RelationshipType + enhance(bluePrintRuntimeService, derivedFrom, derivedFromRelationshipType) + } + + // NodeType Attribute Definitions + enrichRelationshipTypeAttributes(name, relationshipType) + + // NodeType Property Definitions + enrichRelationshipTypeProperties(name, relationshipType) + + // TODO("Interface Enrichment, If needed") + } + + open fun enrichRelationshipTypeAttributes(nodeTypeName: String, relationshipType: RelationshipType) { + relationshipType.attributes?.let { + bluePrintTypeEnhancerService.enhanceAttributeDefinitions( + bluePrintRuntimeService, + relationshipType.attributes!! + ) + } + } + + open fun enrichRelationshipTypeProperties(nodeTypeName: String, relationshipType: RelationshipType) { + relationshipType.properties?.let { + bluePrintTypeEnhancerService.enhancePropertyDefinitions( + bluePrintRuntimeService, + relationshipType.properties!! + ) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt new file mode 100644 index 000000000..9f4a4592a --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt @@ -0,0 +1,67 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintServiceTemplateEnhancerImpl(private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService) : + BluePrintServiceTemplateEnhancer { + + private val log = logger(BluePrintServiceTemplateEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: ServiceTemplate) { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + initialCleanUp() + enhanceTopologyTemplate() + } + + open fun initialCleanUp() { + bluePrintContext.serviceTemplate.artifactTypes?.clear() + bluePrintContext.serviceTemplate.nodeTypes?.clear() + bluePrintContext.serviceTemplate.dataTypes?.clear() + bluePrintContext.serviceTemplate.policyTypes?.clear() + bluePrintContext.serviceTemplate.relationshipTypes?.clear() + + bluePrintContext.serviceTemplate.artifactTypes = mutableMapOf() + bluePrintContext.serviceTemplate.nodeTypes = mutableMapOf() + bluePrintContext.serviceTemplate.dataTypes = mutableMapOf() + bluePrintContext.serviceTemplate.policyTypes = mutableMapOf() + bluePrintContext.serviceTemplate.relationshipTypes = mutableMapOf() + log.info("reinitialized all type definitions") + } + + open fun enhanceTopologyTemplate() { + bluePrintContext.serviceTemplate.topologyTemplate?.let { topologyTemplate -> + bluePrintTypeEnhancerService.enhanceTopologyTemplate(bluePrintRuntimeService, "topology_template", topologyTemplate) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt new file mode 100644 index 000000000..750cd0ff4 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt @@ -0,0 +1,74 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintTopologyTemplateEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintTopologyTemplateEnhancer { + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: TopologyTemplate) { + this.bluePrintRuntimeService = bluePrintRuntimeService + + enhanceTopologyTemplateInputs(type) + enhanceTopologyTemplateNodeTemplates(type) + enhanceTopologyTemplateRelationshipTemplates(type) + enhanceTopologyTemplateWorkflows(type) + } + + open fun enhanceTopologyTemplateInputs(topologyTemplate: TopologyTemplate) { + topologyTemplate.inputs?.let { inputs -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) + } + } + + open fun enhanceTopologyTemplateNodeTemplates(topologyTemplate: TopologyTemplate) { + topologyTemplate.nodeTemplates?.forEach { nodeTemplateName, nodeTemplate -> + bluePrintTypeEnhancerService.enhanceNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeTemplate) + } + } + + open fun enhanceTopologyTemplateRelationshipTemplates(topologyTemplate: TopologyTemplate) { + topologyTemplate.relationshipTemplates?.forEach { relationshipTemplateName, relationshipTemplate -> + bluePrintTypeEnhancerService.enhanceRelationshipTemplate( + bluePrintRuntimeService, + relationshipTemplateName, + relationshipTemplate + ) + } + } + + open fun enhanceTopologyTemplateWorkflows(topologyTemplate: TopologyTemplate) { + topologyTemplate.workflows?.forEach { workflowName, workflow -> + bluePrintTypeEnhancerService.enhanceWorkflow(bluePrintRuntimeService, workflowName, workflow) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt new file mode 100644 index 000000000..c27c206fa --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt @@ -0,0 +1,84 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPolicyTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRelationshipTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRelationshipTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowEnhancer +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.context.ApplicationContext +import org.springframework.stereotype.Service + +@Service +open class BluePrintTypeEnhancerServiceImpl : BluePrintTypeEnhancerService { + + @Autowired + private lateinit var context: ApplicationContext + + override fun getServiceTemplateEnhancers(): List { + return context.getBeansOfType(BluePrintServiceTemplateEnhancer::class.java).map { it.value } + } + + override fun getTopologyTemplateEnhancers(): List { + return context.getBeansOfType(BluePrintTopologyTemplateEnhancer::class.java).map { it.value } + } + + override fun getWorkflowEnhancers(): List { + return context.getBeansOfType(BluePrintWorkflowEnhancer::class.java).map { it.value } + } + + override fun getNodeTemplateEnhancers(): List { + return context.getBeansOfType(BluePrintNodeTemplateEnhancer::class.java).map { it.value } + } + + override fun getNodeTypeEnhancers(): List { + return context.getBeansOfType(BluePrintNodeTypeEnhancer::class.java).map { it.value } + } + + override fun getRelationshipTemplateEnhancers(): List { + return context.getBeansOfType(BluePrintRelationshipTemplateEnhancer::class.java).map { it.value } + } + + override fun getRelationshipTypeEnhancers(): List { + return context.getBeansOfType(BluePrintRelationshipTypeEnhancer::class.java).map { it.value } + } + + override fun getArtifactDefinitionEnhancers(): List { + return context.getBeansOfType(BluePrintArtifactDefinitionEnhancer::class.java).map { it.value } + } + + override fun getPolicyTypeEnhancers(): List { + return context.getBeansOfType(BluePrintPolicyTypeEnhancer::class.java).map { it.value } + } + + override fun getPropertyDefinitionEnhancers(): List { + return context.getBeansOfType(BluePrintPropertyDefinitionEnhancer::class.java).map { it.value } + } + + override fun getAttributeDefinitionEnhancers(): List { + return context.getBeansOfType(BluePrintAttributeDefinitionEnhancer::class.java).map { it.value } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt new file mode 100644 index 000000000..dd60acac1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt @@ -0,0 +1,233 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintWorkflowEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService +) : + BluePrintWorkflowEnhancer { + + private val log = logger(BluePrintWorkflowEnhancerImpl::class) + + companion object { + + const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource" + const val PROPERTY_DEPENDENCY_NODE_TEMPLATES = "dependency-node-templates" + } + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + private val workflowDataTypes: MutableMap = hashMapOf() + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, workflow: Workflow) { + log.info("##### Enhancing Workflow($name)") + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val dynamicPropertyName = "$name-properties" + if (workflow.inputs == null) { + workflow.inputs = hashMapOf() + } + // Clean Dynamic Property Field, If present + workflow.inputs?.remove(dynamicPropertyName) + + // Enrich Workflow Inputs + enhanceWorkflowInputs(name, workflow) + + // Enrich Workflow Outputs + enhanceWorkflowOutputs(name, workflow) + + // Enrich Only for Resource Assignment and Dynamic Input Properties if any + enhanceStepTargets(name, workflow) + } + + open fun enhanceWorkflowInputs(name: String, workflow: Workflow) { + + workflow.inputs?.let { inputs -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) + } + } + + open fun enhanceWorkflowOutputs(name: String, workflow: Workflow) { + workflow.outputs?.let { outputs -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, outputs) + } + } + + private fun enhanceStepTargets(name: String, workflow: Workflow) { + + // Get the first Step Target NodeTemplate name( It may be Component or DG Node Template) + val firstNodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(name) + + val derivedFrom = bluePrintContext.nodeTemplateNodeType(firstNodeTemplateName).derivedFrom + + when { + derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> { + enhanceStepTargets(name, workflow, firstNodeTemplateName, false) + } + derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW, true) -> { + enhanceStepTargets(name, workflow, firstNodeTemplateName, true) + } + else -> { + throw BluePrintProcessorException( + "couldn't execute workflow($name) step mapped " + + "to node template($firstNodeTemplateName) derived from($derivedFrom)" + ) + } + } + } + + private fun enhanceStepTargets(name: String, workflow: Workflow, nodeTemplateName: String, isDG: Boolean) { + + val dependencyNodeTemplates: List + if (isDG) { + val dgNodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) + + // Get the Dependent Component Node Template Names + val dependencyNodeTemplateNodes = dgNodeTemplate.properties?.get(PROPERTY_DEPENDENCY_NODE_TEMPLATES) + ?: throw BluePrintException("couldn't get property($PROPERTY_DEPENDENCY_NODE_TEMPLATES) ") + + dependencyNodeTemplates = + JacksonUtils.getListFromJsonNode(dependencyNodeTemplateNodes, String::class.java) + } else { + dependencyNodeTemplates = listOf(nodeTemplateName) + } + + log.info("workflow($name) dependent component NodeTemplates($dependencyNodeTemplates)") + + // Check and Get Resource Assignment File + val resourceAssignmentArtifacts = dependencyNodeTemplates?.mapNotNull { componentNodeTemplateName -> + log.info("identified workflow($name) targets($componentNodeTemplateName)") + + val resourceAssignmentArtifacts = bluePrintContext.nodeTemplateByName(componentNodeTemplateName) + .artifacts?.filter { + it.value.type == ARTIFACT_TYPE_MAPPING_SOURCE + }?.map { + log.info("resource assignment artifacts(${it.key}) for NodeType($componentNodeTemplateName)") + it.value.file + } + resourceAssignmentArtifacts + }?.flatten() + + log.info("workflow($name) resource assignment files($resourceAssignmentArtifacts") + + if (resourceAssignmentArtifacts != null && resourceAssignmentArtifacts.isNotEmpty()) { + + // Add Workflow Dynamic Property + addWorkFlowDynamicPropertyDefinitions(name, workflow) + + resourceAssignmentArtifacts.forEach { fileName -> + // Enhance Resource Assignment File + val resourceAssignmentProperties = enhanceResourceAssignmentFile(fileName!!) + // Add Workflow Dynamic DataType + addWorkFlowDynamicDataType(name, resourceAssignmentProperties) + } + } + } + + // Enhancement for Dynamic Properties, Resource Assignment Properties, Resource Sources + private fun enhanceResourceAssignmentFile(fileName: String): MutableMap { + + val filePath = "${bluePrintContext.rootPath}/$fileName" + + log.info("enriching artifacts file($filePath") + + val resourceAssignmentProperties: MutableMap = hashMapOf() + + val resourceAssignments: MutableList = JacksonUtils.getListFromFile(filePath, ResourceAssignment::class.java) + as? MutableList + ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)") + + val alreadyEnhancedKey = "enhanced-$fileName" + val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey) + + log.info("enhancing workflow resource mapping file($fileName) already enhanced($alreadyEnhanced)") + + if (!alreadyEnhanced) { + // Call Resource Assignment Enhancer + resourceAssignmentEnhancerService.enhanceBluePrint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments) + bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive()) + } + + resourceAssignments.forEach { resourceAssignment -> + resourceAssignmentProperties[resourceAssignment.name] = resourceAssignment.property!! + } + return resourceAssignmentProperties + } + + private fun addWorkFlowDynamicPropertyDefinitions(name: String, workflow: Workflow) { + val dynamicPropertyName = "$name-properties" + val propertyDefinition = PropertyDefinition() + propertyDefinition.description = "Dynamic PropertyDefinition for workflow($name)." + propertyDefinition.type = "dt-$dynamicPropertyName" + propertyDefinition.required = true + // Add to Workflow Inputs + workflow.inputs?.put(dynamicPropertyName, propertyDefinition) + } + + private fun addWorkFlowDynamicDataType(workflowName: String, mappingProperties: MutableMap) { + + val dataTypeName = "dt-$workflowName-properties" + + var dynamicDataType: DataType? = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName) + + if (dynamicDataType == null) { + log.info("dataType not present for the recipe({})", dataTypeName) + dynamicDataType = DataType() + dynamicDataType.version = "1.0.0" + dynamicDataType.description = "Dynamic DataType definition for workflow($workflowName)." + dynamicDataType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC + + val dataTypeProperties: MutableMap = hashMapOf() + dynamicDataType.properties = dataTypeProperties + + // Overwrite WorkFlow DataType + bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dynamicDataType) + } else { + log.info("dynamic dataType($dataTypeName) already present for workflow($workflowName).") + } + // Merge all the Recipe Properties + mappingProperties.forEach { (propertyName, propertyDefinition) -> + dynamicDataType.properties?.put(propertyName, propertyDefinition) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintArtifactDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintArtifactDefinitionEnhancerImpl.kt deleted file mode 100644 index a85d71f31..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintArtifactDefinitionEnhancerImpl.kt +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment -import org.springframework.stereotype.Service - -@Service -open class BlueprintArtifactDefinitionEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService -) : - BlueprintArtifactDefinitionEnhancer { - - companion object { - - const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource" - } - - private val log = logger(BlueprintArtifactDefinitionEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, artifactDefinition: ArtifactDefinition) { - log.info("enhancing ArtifactDefinition($name)") - - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val artifactTypeName = artifactDefinition.type - ?: throw BlueprintException("artifact type is missing for ArtifactDefinition($name)") - - // Populate Artifact Type - BlueprintEnhancerUtils.populateArtifactType(bluePrintContext, bluePrintRepoService, artifactTypeName) - - when (artifactTypeName) { - ARTIFACT_TYPE_MAPPING_SOURCE -> { - enhanceMappingType(name, artifactDefinition) - } - } - } - - // Enhance Resource Mapping - open fun enhanceMappingType(name: String, artifactDefinition: ArtifactDefinition) { - - val artifactFilePath = "${bluePrintContext.rootPath}/${artifactDefinition.file}" - - val alreadyEnhancedKey = "enhanced-${artifactDefinition.file}" - val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey) - - log.info("enhancing resource mapping file(${artifactDefinition.file}) already enhanced($alreadyEnhanced)") - - if (!alreadyEnhanced) { - val resourceAssignments: MutableList = JacksonUtils.getListFromFile(artifactFilePath, ResourceAssignment::class.java) - as? MutableList - ?: throw BlueprintProcessorException("couldn't get ResourceAssignment definitions for the file($artifactFilePath)") - - // Call Resource Assignment Enhancer - resourceAssignmentEnhancerService.enhanceBlueprint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments) - - bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive()) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintAttributeDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintAttributeDefinitionEnhancerImpl.kt deleted file mode 100644 index cd05c62e1..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintAttributeDefinitionEnhancerImpl.kt +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintAttributeDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService - -class BlueprintAttributeDefinitionEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintAttributeDefinitionEnhancer { - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, attributeDefinition: AttributeDefinition) { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val propertyType = attributeDefinition.type - if (BlueprintTypes.validPrimitiveTypes().contains(propertyType)) { - } else if (BlueprintTypes.validCollectionTypes().contains(propertyType)) { - val entrySchema = attributeDefinition.entrySchema - ?: throw BlueprintException("Entry Schema is missing for collection property($name)") - - if (!BlueprintTypes.validPrimitiveTypes().contains(entrySchema.type)) { - BlueprintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type) - } - } else { - BlueprintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImpl.kt deleted file mode 100644 index 7603963a1..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImpl.kt +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintFileUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils -import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes -import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault -import org.springframework.stereotype.Service -import java.io.IOException -import java.util.UUID - -@Service -open class BlueprintEnhancerServiceImpl( - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - private val resourceDefinitionEnhancerService: ResourceDefinitionEnhancerService -) : BlueprintEnhancerService { - - private val log = logger(BlueprintEnhancerServiceImpl::class) - - override suspend fun enhance(basePath: String, enrichedBasePath: String): BlueprintContext { - - // Copy the Blueprint Content to Target Location - BlueprintFileUtils.copyBlueprint(basePath, enrichedBasePath) - - // Enhance the Blueprint - return enhance(enrichedBasePath) - } - - @Throws(BlueprintException::class) - override suspend fun enhance(basePath: String): BlueprintContext { - - log.info("Enhancing blueprint($basePath)") - val blueprintRuntimeService = BlueprintMetadataUtils - .getBaseEnhancementBlueprintRuntime(UUID.randomUUID().toString(), basePath) - - try { - - bluePrintTypeEnhancerService.enhanceServiceTemplate( - blueprintRuntimeService, "service_template", - blueprintRuntimeService.bluePrintContext().serviceTemplate - ) - - log.info("##### Enhancing blueprint Resource Definitions") - val resourceDefinitions = resourceDefinitionEnhancerService.enhance( - bluePrintTypeEnhancerService, - blueprintRuntimeService - ) - - // Write the Enhanced Blueprint Definitions - BlueprintFileUtils.writeEnhancedBlueprint(blueprintRuntimeService.bluePrintContext()) - - // Write the Enhanced Blueprint Resource Definitions - ResourceDictionaryUtils.writeResourceDefinitionTypes(basePath, resourceDefinitions) - - if (blueprintRuntimeService.getBlueprintError().allErrors().isNotEmpty()) { - throw BlueprintException(blueprintRuntimeService.getBlueprintError().allErrors().toString()) - } - } catch (e: BlueprintProcessorException) { - val errorMsg = "Error while enriching the CBA package." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong blueprint definitions or resource definitions." - ) - } catch (e: IOException) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "IO Error: CBA file failed enrichment - ${e.message}", e.errorCauseOrDefault() - ) - } catch (e: Exception) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "Error in Enriching CBA: ${e.message}", e.errorCauseOrDefault() - ) - } - return blueprintRuntimeService.bluePrintContext() - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTemplateEnhancerImpl.kt deleted file mode 100644 index 0dd5ed19a..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTemplateEnhancerImpl.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintNodeTemplateEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintNodeTemplateEnhancer { - - private val log = logger(BlueprintNodeTemplateEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) { - log.info("***** Enhancing NodeTemplate($name)") - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val nodeTypeName = nodeTemplate.type - // Get NodeType from Repo and Update Service Template - val nodeType = BlueprintEnhancerUtils.populateNodeType(bluePrintContext, bluePrintRepoService, nodeTypeName) - - // Enrich NodeType - bluePrintTypeEnhancerService.enhanceNodeType(bluePrintRuntimeService, nodeTypeName, nodeType) - - // Enrich Node Template Artifacts - enhanceNodeTemplateArtifactDefinition(name, nodeTemplate) - } - - open fun enhanceNodeTemplateArtifactDefinition(nodeTemplateName: String, nodeTemplate: NodeTemplate) { - - nodeTemplate.artifacts?.forEach { artifactDefinitionName, artifactDefinition -> - // Enhance Artifacct Definitions - bluePrintTypeEnhancerService.enhanceArtifactDefinition(bluePrintRuntimeService, artifactDefinitionName, artifactDefinition) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTypeEnhancerImpl.kt deleted file mode 100644 index 4011918f7..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTypeEnhancerImpl.kt +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintNodeTypeEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : BlueprintNodeTypeEnhancer { - - private val log = logger(BlueprintNodeTypeEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, nodeType: NodeType) { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val derivedFrom = nodeType.derivedFrom - - if (!BlueprintTypes.rootNodeTypes().contains(derivedFrom)) { - val derivedFromNodeType = BlueprintEnhancerUtils.populateNodeType(bluePrintContext, bluePrintRepoService, name) - // Enrich NodeType - enhance(bluePrintRuntimeService, derivedFrom, derivedFromNodeType) - } - - // NodeType Attribute Definitions - enrichNodeTypeAttributes(name, nodeType) - - // NodeType Property Definitions - enrichNodeTypeProperties(name, nodeType) - - // NodeType Requirement - enrichNodeTypeRequirements(name, nodeType) - - // NodeType Capability - enrichNodeTypeCapabilityProperties(name, nodeType) - - // NodeType Interface - enrichNodeTypeInterfaces(name, nodeType) - } - - open fun enrichNodeTypeAttributes(nodeTypeName: String, nodeType: NodeType) { - nodeType.attributes?.let { - bluePrintTypeEnhancerService.enhanceAttributeDefinitions(bluePrintRuntimeService, nodeType.attributes!!) - } - } - - open fun enrichNodeTypeProperties(nodeTypeName: String, nodeType: NodeType) { - nodeType.properties?.let { - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, nodeType.properties!!) - } - } - - open fun enrichNodeTypeRequirements(nodeTypeName: String, nodeType: NodeType) { - - nodeType.requirements?.forEach { requirementName, requirementDefinition -> - // Populate Requirement Node - requirementDefinition.node?.let { requirementNodeTypeName -> - // Get Requirement NodeType from Repo and Update Service Template - val requirementNodeType = BlueprintEnhancerUtils.populateNodeType( - bluePrintContext, - bluePrintRepoService, requirementNodeTypeName - ) - // Enhance Node Type - enhance(bluePrintRuntimeService, requirementNodeTypeName, requirementNodeType) - - // Enhance Relationship Type - val relationShipTypeName = requirementDefinition.relationship - ?: throw BlueprintException( - "couldn't get relationship name for the NodeType($nodeTypeName) " + - "Requirement($requirementName)" - ) - enrichRelationShipType(relationShipTypeName) - } - } - } - - open fun enrichNodeTypeCapabilityProperties(nodeTypeName: String, nodeType: NodeType) { - nodeType.capabilities?.forEach { _, capabilityDefinition -> - capabilityDefinition.properties?.let { properties -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, properties) - } - } - } - - open fun enrichNodeTypeInterfaces(nodeTypeName: String, nodeType: NodeType) { - nodeType.interfaces?.forEach { interfaceName, interfaceObj -> - // Populate Node type Interface Operation - log.debug("Enriching NodeType({}) Interface({})", nodeTypeName, interfaceName) - populateNodeTypeInterfaceOperation(nodeTypeName, interfaceName, interfaceObj) - } - } - - open fun populateNodeTypeInterfaceOperation(nodeTypeName: String, interfaceName: String, interfaceObj: InterfaceDefinition) { - - interfaceObj.operations?.forEach { operationName, operation -> - enrichNodeTypeInterfaceOperationInputs(nodeTypeName, operationName, operation) - enrichNodeTypeInterfaceOperationOutputs(nodeTypeName, operationName, operation) - } - } - - open fun enrichNodeTypeInterfaceOperationInputs(nodeTypeName: String, operationName: String, operation: OperationDefinition) { - operation.inputs?.let { inputs -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) - } - } - - open fun enrichNodeTypeInterfaceOperationOutputs( - nodeTypeName: String, - operationName: String, - operation: OperationDefinition - ) { - operation.outputs?.let { inputs -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) - } - } - - /** - * Get the Relationship Type from database and add to Blueprint Context - */ - open fun enrichRelationShipType(relationshipName: String) { - BlueprintEnhancerUtils.populateRelationshipType(bluePrintContext, bluePrintRepoService, relationshipName) - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPolicyTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPolicyTypeEnhancerImpl.kt deleted file mode 100644 index d58c82f07..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPolicyTypeEnhancerImpl.kt +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPolicyTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -class BlueprintPolicyTypeEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintPolicyTypeEnhancer { - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, type: PolicyType) { - - this.bluePrintRuntimeService = bluePrintRuntimeService - - // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPropertyDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPropertyDefinitionEnhancerImpl.kt deleted file mode 100644 index 4ac52bb17..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPropertyDefinitionEnhancerImpl.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPropertyDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintPropertyDefinitionEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintPropertyDefinitionEnhancer { - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val propertyType = propertyDefinition.type - if (BlueprintTypes.validPrimitiveTypes().contains(propertyType) || - BlueprintTypes.validComplexTypes().contains(propertyType) - ) { - // Do Nothing, - } else if (BlueprintTypes.validCollectionTypes().contains(propertyType)) { - val entrySchema = propertyDefinition.entrySchema - ?: throw BlueprintException("Entry Schema is missing for collection property($name)") - - if (!BlueprintTypes.validPrimitiveTypes().contains(entrySchema.type)) { - BlueprintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type) - } - } else { - BlueprintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTemplateEnhancerImpl.kt deleted file mode 100644 index cd345a81c..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTemplateEnhancerImpl.kt +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRelationshipTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintRelationshipTemplateEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintRelationshipTemplateEnhancer { - - private val log = logger(BlueprintRelationshipTemplateEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - relationshipTemplate: RelationshipTemplate - ) { - log.info("***** Enhancing RelationshipTemplate($name)") - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val relationshipTypeName = relationshipTemplate.type - // Get RelationshipType from Repo and Update Service Template - val relationshipType = - BlueprintEnhancerUtils.populateRelationshipType( - bluePrintContext, - bluePrintRepoService, - relationshipTypeName - ) - - // Enrich NodeType - bluePrintTypeEnhancerService.enhanceRelationshipType( - bluePrintRuntimeService, - relationshipTypeName, - relationshipType - ) - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTypeEnhancerImpl.kt deleted file mode 100644 index 2216cafb6..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTypeEnhancerImpl.kt +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRelationshipTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintRelationshipTypeEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : BlueprintRelationshipTypeEnhancer { - - private val log = logger(BlueprintRelationshipTypeEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - relationshipType: RelationshipType - ) { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val derivedFrom = relationshipType.derivedFrom - - if (!BlueprintTypes.rootRelationshipTypes().contains(derivedFrom)) { - val derivedFromRelationshipType = - BlueprintEnhancerUtils.populateRelationshipType(bluePrintContext, bluePrintRepoService, name) - // Enrich RelationshipType - enhance(bluePrintRuntimeService, derivedFrom, derivedFromRelationshipType) - } - - // NodeType Attribute Definitions - enrichRelationshipTypeAttributes(name, relationshipType) - - // NodeType Property Definitions - enrichRelationshipTypeProperties(name, relationshipType) - - // TODO("Interface Enrichment, If needed") - } - - open fun enrichRelationshipTypeAttributes(nodeTypeName: String, relationshipType: RelationshipType) { - relationshipType.attributes?.let { - bluePrintTypeEnhancerService.enhanceAttributeDefinitions( - bluePrintRuntimeService, - relationshipType.attributes!! - ) - } - } - - open fun enrichRelationshipTypeProperties(nodeTypeName: String, relationshipType: RelationshipType) { - relationshipType.properties?.let { - bluePrintTypeEnhancerService.enhancePropertyDefinitions( - bluePrintRuntimeService, - relationshipType.properties!! - ) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintServiceTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintServiceTemplateEnhancerImpl.kt deleted file mode 100644 index 80855ce4c..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintServiceTemplateEnhancerImpl.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintServiceTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintServiceTemplateEnhancerImpl(private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService) : - BlueprintServiceTemplateEnhancer { - - private val log = logger(BlueprintServiceTemplateEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, type: ServiceTemplate) { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - initialCleanUp() - enhanceTopologyTemplate() - } - - open fun initialCleanUp() { - bluePrintContext.serviceTemplate.artifactTypes?.clear() - bluePrintContext.serviceTemplate.nodeTypes?.clear() - bluePrintContext.serviceTemplate.dataTypes?.clear() - bluePrintContext.serviceTemplate.policyTypes?.clear() - bluePrintContext.serviceTemplate.relationshipTypes?.clear() - - bluePrintContext.serviceTemplate.artifactTypes = mutableMapOf() - bluePrintContext.serviceTemplate.nodeTypes = mutableMapOf() - bluePrintContext.serviceTemplate.dataTypes = mutableMapOf() - bluePrintContext.serviceTemplate.policyTypes = mutableMapOf() - bluePrintContext.serviceTemplate.relationshipTypes = mutableMapOf() - log.info("reinitialized all type definitions") - } - - open fun enhanceTopologyTemplate() { - bluePrintContext.serviceTemplate.topologyTemplate?.let { topologyTemplate -> - bluePrintTypeEnhancerService.enhanceTopologyTemplate(bluePrintRuntimeService, "topology_template", topologyTemplate) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTopologyTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTopologyTemplateEnhancerImpl.kt deleted file mode 100644 index 768f5abe4..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTopologyTemplateEnhancerImpl.kt +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTopologyTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintTopologyTemplateEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintTopologyTemplateEnhancer { - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, type: TopologyTemplate) { - this.bluePrintRuntimeService = bluePrintRuntimeService - - enhanceTopologyTemplateInputs(type) - enhanceTopologyTemplateNodeTemplates(type) - enhanceTopologyTemplateRelationshipTemplates(type) - enhanceTopologyTemplateWorkflows(type) - } - - open fun enhanceTopologyTemplateInputs(topologyTemplate: TopologyTemplate) { - topologyTemplate.inputs?.let { inputs -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) - } - } - - open fun enhanceTopologyTemplateNodeTemplates(topologyTemplate: TopologyTemplate) { - topologyTemplate.nodeTemplates?.forEach { nodeTemplateName, nodeTemplate -> - bluePrintTypeEnhancerService.enhanceNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeTemplate) - } - } - - open fun enhanceTopologyTemplateRelationshipTemplates(topologyTemplate: TopologyTemplate) { - topologyTemplate.relationshipTemplates?.forEach { relationshipTemplateName, relationshipTemplate -> - bluePrintTypeEnhancerService.enhanceRelationshipTemplate( - bluePrintRuntimeService, - relationshipTemplateName, - relationshipTemplate - ) - } - } - - open fun enhanceTopologyTemplateWorkflows(topologyTemplate: TopologyTemplate) { - topologyTemplate.workflows?.forEach { workflowName, workflow -> - bluePrintTypeEnhancerService.enhanceWorkflow(bluePrintRuntimeService, workflowName, workflow) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTypeEnhancerServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTypeEnhancerServiceImpl.kt deleted file mode 100644 index d3b28596c..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTypeEnhancerServiceImpl.kt +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintAttributeDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPolicyTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPropertyDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRelationshipTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRelationshipTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintServiceTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTopologyTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowEnhancer -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.context.ApplicationContext -import org.springframework.stereotype.Service - -@Service -open class BlueprintTypeEnhancerServiceImpl : BlueprintTypeEnhancerService { - - @Autowired - private lateinit var context: ApplicationContext - - override fun getServiceTemplateEnhancers(): List { - return context.getBeansOfType(BlueprintServiceTemplateEnhancer::class.java).map { it.value } - } - - override fun getTopologyTemplateEnhancers(): List { - return context.getBeansOfType(BlueprintTopologyTemplateEnhancer::class.java).map { it.value } - } - - override fun getWorkflowEnhancers(): List { - return context.getBeansOfType(BlueprintWorkflowEnhancer::class.java).map { it.value } - } - - override fun getNodeTemplateEnhancers(): List { - return context.getBeansOfType(BlueprintNodeTemplateEnhancer::class.java).map { it.value } - } - - override fun getNodeTypeEnhancers(): List { - return context.getBeansOfType(BlueprintNodeTypeEnhancer::class.java).map { it.value } - } - - override fun getRelationshipTemplateEnhancers(): List { - return context.getBeansOfType(BlueprintRelationshipTemplateEnhancer::class.java).map { it.value } - } - - override fun getRelationshipTypeEnhancers(): List { - return context.getBeansOfType(BlueprintRelationshipTypeEnhancer::class.java).map { it.value } - } - - override fun getArtifactDefinitionEnhancers(): List { - return context.getBeansOfType(BlueprintArtifactDefinitionEnhancer::class.java).map { it.value } - } - - override fun getPolicyTypeEnhancers(): List { - return context.getBeansOfType(BlueprintPolicyTypeEnhancer::class.java).map { it.value } - } - - override fun getPropertyDefinitionEnhancers(): List { - return context.getBeansOfType(BlueprintPropertyDefinitionEnhancer::class.java).map { it.value } - } - - override fun getAttributeDefinitionEnhancers(): List { - return context.getBeansOfType(BlueprintAttributeDefinitionEnhancer::class.java).map { it.value } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintWorkflowEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintWorkflowEnhancerImpl.kt deleted file mode 100644 index 8b19af0a7..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintWorkflowEnhancerImpl.kt +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintWorkflowEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService -) : - BlueprintWorkflowEnhancer { - - private val log = logger(BlueprintWorkflowEnhancerImpl::class) - - companion object { - - const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource" - const val PROPERTY_DEPENDENCY_NODE_TEMPLATES = "dependency-node-templates" - } - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - private val workflowDataTypes: MutableMap = hashMapOf() - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, workflow: Workflow) { - log.info("##### Enhancing Workflow($name)") - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val dynamicPropertyName = "$name-properties" - if (workflow.inputs == null) { - workflow.inputs = hashMapOf() - } - // Clean Dynamic Property Field, If present - workflow.inputs?.remove(dynamicPropertyName) - - // Enrich Workflow Inputs - enhanceWorkflowInputs(name, workflow) - - // Enrich Workflow Outputs - enhanceWorkflowOutputs(name, workflow) - - // Enrich Only for Resource Assignment and Dynamic Input Properties if any - enhanceStepTargets(name, workflow) - } - - open fun enhanceWorkflowInputs(name: String, workflow: Workflow) { - - workflow.inputs?.let { inputs -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) - } - } - - open fun enhanceWorkflowOutputs(name: String, workflow: Workflow) { - workflow.outputs?.let { outputs -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, outputs) - } - } - - private fun enhanceStepTargets(name: String, workflow: Workflow) { - - // Get the first Step Target NodeTemplate name( It may be Component or DG Node Template) - val firstNodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(name) - - val derivedFrom = bluePrintContext.nodeTemplateNodeType(firstNodeTemplateName).derivedFrom - - when { - derivedFrom.startsWith(BlueprintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> { - enhanceStepTargets(name, workflow, firstNodeTemplateName, false) - } - derivedFrom.startsWith(BlueprintConstants.MODEL_TYPE_NODE_WORKFLOW, true) -> { - enhanceStepTargets(name, workflow, firstNodeTemplateName, true) - } - else -> { - throw BlueprintProcessorException( - "couldn't execute workflow($name) step mapped " + - "to node template($firstNodeTemplateName) derived from($derivedFrom)" - ) - } - } - } - - private fun enhanceStepTargets(name: String, workflow: Workflow, nodeTemplateName: String, isDG: Boolean) { - - val dependencyNodeTemplates: List - if (isDG) { - val dgNodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) - - // Get the Dependent Component Node Template Names - val dependencyNodeTemplateNodes = dgNodeTemplate.properties?.get(PROPERTY_DEPENDENCY_NODE_TEMPLATES) - ?: throw BlueprintException("couldn't get property($PROPERTY_DEPENDENCY_NODE_TEMPLATES) ") - - dependencyNodeTemplates = - JacksonUtils.getListFromJsonNode(dependencyNodeTemplateNodes, String::class.java) - } else { - dependencyNodeTemplates = listOf(nodeTemplateName) - } - - log.info("workflow($name) dependent component NodeTemplates($dependencyNodeTemplates)") - - // Check and Get Resource Assignment File - val resourceAssignmentArtifacts = dependencyNodeTemplates?.mapNotNull { componentNodeTemplateName -> - log.info("identified workflow($name) targets($componentNodeTemplateName)") - - val resourceAssignmentArtifacts = bluePrintContext.nodeTemplateByName(componentNodeTemplateName) - .artifacts?.filter { - it.value.type == ARTIFACT_TYPE_MAPPING_SOURCE - }?.map { - log.info("resource assignment artifacts(${it.key}) for NodeType($componentNodeTemplateName)") - it.value.file - } - resourceAssignmentArtifacts - }?.flatten() - - log.info("workflow($name) resource assignment files($resourceAssignmentArtifacts") - - if (resourceAssignmentArtifacts != null && resourceAssignmentArtifacts.isNotEmpty()) { - - // Add Workflow Dynamic Property - addWorkFlowDynamicPropertyDefinitions(name, workflow) - - resourceAssignmentArtifacts.forEach { fileName -> - // Enhance Resource Assignment File - val resourceAssignmentProperties = enhanceResourceAssignmentFile(fileName!!) - // Add Workflow Dynamic DataType - addWorkFlowDynamicDataType(name, resourceAssignmentProperties) - } - } - } - - // Enhancement for Dynamic Properties, Resource Assignment Properties, Resource Sources - private fun enhanceResourceAssignmentFile(fileName: String): MutableMap { - - val filePath = "${bluePrintContext.rootPath}/$fileName" - - log.info("enriching artifacts file($filePath") - - val resourceAssignmentProperties: MutableMap = hashMapOf() - - val resourceAssignments: MutableList = JacksonUtils.getListFromFile(filePath, ResourceAssignment::class.java) - as? MutableList - ?: throw BlueprintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)") - - val alreadyEnhancedKey = "enhanced-$fileName" - val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey) - - log.info("enhancing workflow resource mapping file($fileName) already enhanced($alreadyEnhanced)") - - if (!alreadyEnhanced) { - // Call Resource Assignment Enhancer - resourceAssignmentEnhancerService.enhanceBlueprint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments) - bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive()) - } - - resourceAssignments.forEach { resourceAssignment -> - resourceAssignmentProperties[resourceAssignment.name] = resourceAssignment.property!! - } - return resourceAssignmentProperties - } - - private fun addWorkFlowDynamicPropertyDefinitions(name: String, workflow: Workflow) { - val dynamicPropertyName = "$name-properties" - val propertyDefinition = PropertyDefinition() - propertyDefinition.description = "Dynamic PropertyDefinition for workflow($name)." - propertyDefinition.type = "dt-$dynamicPropertyName" - propertyDefinition.required = true - // Add to Workflow Inputs - workflow.inputs?.put(dynamicPropertyName, propertyDefinition) - } - - private fun addWorkFlowDynamicDataType(workflowName: String, mappingProperties: MutableMap) { - - val dataTypeName = "dt-$workflowName-properties" - - var dynamicDataType: DataType? = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName) - - if (dynamicDataType == null) { - log.info("dataType not present for the recipe({})", dataTypeName) - dynamicDataType = DataType() - dynamicDataType.version = "1.0.0" - dynamicDataType.description = "Dynamic DataType definition for workflow($workflowName)." - dynamicDataType.derivedFrom = BlueprintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC - - val dataTypeProperties: MutableMap = hashMapOf() - dynamicDataType.properties = dataTypeProperties - - // Overwrite WorkFlow DataType - bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dynamicDataType) - } else { - log.info("dynamic dataType($dataTypeName) already present for workflow($workflowName).") - } - // Merge all the Recipe Properties - mappingProperties.forEach { (propertyName, propertyDefinition) -> - dynamicDataType.properties?.put(propertyName, propertyDefinition) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt index 4d1995d53..621b046e6 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt @@ -17,11 +17,11 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants @@ -37,10 +37,10 @@ import org.springframework.stereotype.Service */ interface ResourceAssignmentEnhancerService { - @Throws(BlueprintException::class) - fun enhanceBlueprint( - bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - bluePrintRuntimeService: BlueprintRuntimeService<*>, + @Throws(BluePrintException::class) + fun enhanceBluePrint( + bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + bluePrintRuntimeService: BluePrintRuntimeService<*>, resourceAssignments: List ) } @@ -61,9 +61,9 @@ open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionR * Get the defined source instance from the ResourceAssignment, * then get the NodeType of the Sources assigned */ - override fun enhanceBlueprint( - bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - bluePrintRuntimeService: BlueprintRuntimeService<*>, + override fun enhanceBluePrint( + bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + bluePrintRuntimeService: BluePrintRuntimeService<*>, resourceAssignments: List ) { @@ -91,7 +91,7 @@ open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionR val resourceDefinition: ResourceDefinition = getResourceDefinition(dictionaryName) val sourceNodeTemplate = resourceDefinition.sources[dictionarySource] - ?: throw BlueprintException("failed to get assigned dictionarySource($dictionarySource) from resourceDefinition($dictionaryName)") + ?: throw BluePrintException("failed to get assigned dictionarySource($dictionarySource) from resourceDefinition($dictionaryName)") // Enrich as NodeTemplate bluePrintTypeEnhancerService.enhanceNodeTemplate(bluePrintRuntimeService, dictionarySource, sourceNodeTemplate) @@ -110,7 +110,7 @@ open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionR resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_INPUT) || resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_DEFAULT) ) && - BlueprintTypes.validPrimitiveOrCollectionPrimitive(resourceAssignment.property!!) + BluePrintTypes.validPrimitiveOrCollectionPrimitive(resourceAssignment.property!!) ) } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt index 08a41f7be..bbec8e685 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt @@ -21,12 +21,12 @@ import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils @@ -34,10 +34,10 @@ import org.springframework.stereotype.Service interface ResourceDefinitionEnhancerService { - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) fun enhance( - bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - bluePrintRuntimeService: BlueprintRuntimeService<*> + bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + bluePrintRuntimeService: BluePrintRuntimeService<*> ): List } @@ -58,8 +58,8 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe // 3. Collect the Resource Definition for Resource Assignment names from database. // 4. Create the Resource Definition under blueprint base path. override fun enhance( - bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - bluePrintRuntimeService: BlueprintRuntimeService<*> + bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + bluePrintRuntimeService: BluePrintRuntimeService<*> ): List { var resourceDefinitions: List = mutableListOf() @@ -77,7 +77,7 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe } // Get all the Mapping files from all node templates. - private fun getAllResourceMappingFiles(blueprintContext: BlueprintContext): List? { + private fun getAllResourceMappingFiles(blueprintContext: BluePrintContext): List? { return blueprintContext.nodeTemplates()?.mapNotNull { nodeTemplateMap -> @@ -91,7 +91,7 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe } // Convert file content to ResourceAssignments asynchronously - private fun getResourceDefinition(blueprintContext: BlueprintContext, files: List) = runBlocking { + private fun getResourceDefinition(blueprintContext: BluePrintContext, files: List) = runBlocking { val blueprintBasePath = blueprintContext.rootPath val deferredResourceAssignments = mutableListOf>>() for (file in files) { @@ -124,7 +124,7 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe } private fun enrichResourceDefinitionSources( - bluePrintContext: BlueprintContext, + bluePrintContext: BluePrintContext, resourceDefinitions: List ) { val sources = resourceDefinitions @@ -138,7 +138,7 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe .flatten().distinct() log.info("Enriching Resource Definition sources Node Template: $sources") sources.forEach { - BlueprintEnhancerUtils.populateNodeType(bluePrintContext, resourceDefinitionRepoService, it) + BluePrintEnhancerUtils.populateNodeType(bluePrintContext, resourceDefinitionRepoService, it) } } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt new file mode 100644 index 000000000..7bbaa8c59 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt @@ -0,0 +1,643 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2019 Orange. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler + +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelContentRepository +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelSearchRepository +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.BootstrapRequest +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowData +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowSpecRequest +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowSpecResponse +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowsResponse +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.BluePrintDatabaseLoadService +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir +import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes +import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault +import org.onap.ccsdk.cds.error.catalog.core.utils.errorMessageOrDefault +import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource +import org.springframework.data.domain.Page +import org.springframework.data.domain.PageRequest +import org.springframework.data.domain.Pageable +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.codec.multipart.FilePart +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import java.io.File +import java.io.IOException +import java.util.UUID + +/** + * BlueprintModelHandler Purpose: Handler service to handle the request from BlurPrintModelRest + * + * @author Brinda Santh + * @version 1.0 + */ + +@Service +open class BluePrintModelHandler( + private val bluePrintDatabaseLoadService: BluePrintDatabaseLoadService, + private val blueprintsProcessorCatalogService: BluePrintCatalogService, + private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, + private val blueprintModelSearchRepository: BlueprintModelSearchRepository, + private val blueprintModelRepository: BlueprintModelRepository, + private val blueprintModelContentRepository: BlueprintModelContentRepository, + private val bluePrintEnhancerService: BluePrintEnhancerService +) { + + private val log = logger(BluePrintModelHandler::class) + + open suspend fun bootstrapBlueprint(bootstrapRequest: BootstrapRequest) { + log.info( + "Bootstrap request with type load(${bootstrapRequest.loadModelType}), " + + "resource dictionary load(${bootstrapRequest.loadResourceDictionary}) and " + + "cba load(${bootstrapRequest.loadCBA})" + ) + if (bootstrapRequest.loadModelType) { + bluePrintDatabaseLoadService.initModelTypes() + } + if (bootstrapRequest.loadResourceDictionary) { + bluePrintDatabaseLoadService.initResourceDictionary() + } + if (bootstrapRequest.loadCBA) { + bluePrintDatabaseLoadService.initBluePrintCatalog() + } + } + + @Throws(BluePrintException::class) + open suspend fun prepareWorkFlowSpec(req: WorkFlowSpecRequest): + WorkFlowSpecResponse { + val basePath = blueprintsProcessorCatalogService.getFromDatabase( + req + .blueprintName, + req.version + ) + log.info("blueprint base path $basePath") + + val blueprintContext = BluePrintMetadataUtils.getBluePrintContext(basePath.toString()) + val workFlow = blueprintContext.workflowByName(req.workflowName) + + val wfRes = WorkFlowSpecResponse() + wfRes.blueprintName = req.blueprintName + wfRes.version = req.version + + val workFlowData = WorkFlowData() + workFlowData.workFlowName = req.workflowName + workFlowData.inputs = workFlow.inputs + workFlowData.outputs = workFlow.outputs + wfRes.workFlowData = workFlowData + + if (workFlow.inputs != null) { + for ((k, v) in workFlow.inputs!!) { + addPropertyInfo(k, v, blueprintContext, wfRes) + } + } + + if (workFlow.outputs != null) { + for ((k, v) in workFlow.outputs!!) { + addPropertyInfo(k, v, blueprintContext, wfRes) + } + } + + return wfRes + } + + private fun addPropertyInfo(propName: String, prop: PropertyDefinition, ctx: BluePrintContext, res: WorkFlowSpecResponse) { + updatePropertyInfo(propName, prop, ctx, res) + addDataType(prop.type, ctx, res) + if (prop.entrySchema != null && prop.entrySchema!!.type != null) { + addDataType(prop.entrySchema!!.type, ctx, res) + } + } + + private fun updatePropertyInfo(name: String, prop: PropertyDefinition, ctx: BluePrintContext, res: WorkFlowSpecResponse) { + if (prop.inputparam == null || prop.inputparam == false) { + var workflow = ctx.workflowByName(res.workFlowData.workFlowName) + for ((k, v) in workflow.steps!!) { + var arts = ctx.nodeTemplateArtifacts(v.target!!) + if (arts != null) { + for ((k, v) in arts.entries!!) { + if (v.type == "artifact-mapping-resource") { + val file: String = v.file + val completePath = ctx.rootPath.plus(File.separator).plus(file) + val resourceAssignment = JacksonUtils.getListFromFile(completePath, ResourceAssignment::class.java) + for (res in resourceAssignment) { + if (res.name == name && res.inputParameter) { + prop.inputparam = true + return + } + } + } + } + } + } + } + } + + private fun addDataType(name: String, ctx: BluePrintContext, res: WorkFlowSpecResponse) { + var data = ctx.dataTypeByName(name) + if (data != null) { + res.dataTypes?.put(name, data) + addParentDataType(data, ctx, res) + } + } + + private fun addParentDataType(data: DataType, ctx: BluePrintContext, res: WorkFlowSpecResponse) { + if (data.properties != null) { + for ((k, v) in data.properties!!) { + addPropertyInfo(k, v, ctx, res) + } + } + } + + @Throws(BluePrintException::class) + open suspend fun getWorkflowNames(name: String, version: String): WorkFlowsResponse { + val basePath = blueprintsProcessorCatalogService.getFromDatabase( + name, version + ) + log.info("blueprint base path $basePath") + + var res = WorkFlowsResponse() + res.blueprintName = name + res.version = version + + val blueprintContext = BluePrintMetadataUtils.getBluePrintContext( + basePath.toString() + ) + if (blueprintContext.workflows() != null) { + res.workflows = blueprintContext.workflows()!!.keys + } + return res + } + + /** + * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database + * + * @return List list of the controller blueprint archives + */ + open fun allBlueprintModel(): List { + return blueprintModelSearchRepository.findAll() + } + + /** + * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database + * + * @return List list of the controller blueprint archives + */ + open fun allBlueprintModel(pageRequest: Pageable): Page { + return blueprintModelSearchRepository.findAll(pageRequest) + } + + /** + * This is a saveBlueprintModel method + * + * @param filePart filePart + * @return Mono + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open suspend fun saveBlueprintModel(filePart: FilePart): BlueprintModelSearch { + try { + return upload(filePart, false) + } catch (e: IOException) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "Error in Save CBA: ${e.message}", e.errorCauseOrDefault() + ) + } + } + + /** + * This is a searchBlueprintModels method + * + * @param tags tags + * @return List + */ + open fun searchBlueprintModels(tags: String): List { + return blueprintModelSearchRepository.findByTagsContainingIgnoreCase(tags) + } + + /** + * This is a getBlueprintModelSearchByNameAndVersion method + * + * @param name name + * @param version version + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelSearchByNameAndVersion(name: String, version: String): BlueprintModelSearch? { + return blueprintModelSearchRepository.findByArtifactNameAndArtifactVersion(name, version) + /*?: throw BluePrintException( + ErrorCode.RESOURCE_NOT_FOUND.value, + String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version) + )*/ + } + + /** + * This is a downloadBlueprintModelFileByNameAndVersion method to download a Blueprint by Name and Version + * + * @param name name + * @param version version + * @return ResponseEntity + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun downloadBlueprintModelFileByNameAndVersion( + name: String, + version: String + ): ResponseEntity { + try { + val archiveByteArray = download(name, version) + val fileName = "${name}_$version.zip" + return prepareResourceEntity(fileName, archiveByteArray) + } catch (e: BluePrintProcessorException) { + e.http(ErrorCatalogCodes.RESOURCE_NOT_FOUND) + val errorMsg = "Error while downloading the CBA file by Blueprint Name ($name) and Version ($version)." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong resource definition or resolution failed." + ) + } + } + + /** + * This is a downloadBlueprintModelFile method to find the target file to download and return a file resource + * + * @return ResponseEntity + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun downloadBlueprintModelFile(id: String): ResponseEntity { + val blueprintModel: BlueprintModel + try { + blueprintModel = getBlueprintModel(id) + } catch (e: BluePrintException) { + throw httpProcessorException( + ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, + "Error while downloading the CBA file: couldn't get blueprint modelby ID ($id)", + e.errorCauseOrDefault() + ) + } + + val fileName = "${blueprintModel.artifactName}_${blueprintModel.artifactVersion}.zip" + val file = blueprintModel.blueprintModelContent?.content + ?: throw httpProcessorException( + ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, + "Error while downloading the CBA file: couldn't get model content" + ) + return prepareResourceEntity(fileName, file) + } + + /** + * @return ResponseEntity + */ + private fun prepareResourceEntity(fileName: String, file: ByteArray): ResponseEntity { + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType("text/plain")) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"") + .body(ByteArrayResource(file)) + } + + /** + * This is a getBlueprintModel method + * + * @param id id + * @return BlueprintModel + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModel(id: String): BlueprintModel { + val blueprintModel: BlueprintModel + val dbBlueprintModel = blueprintModelRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModel = dbBlueprintModel.get() + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) + } + return blueprintModel + } + + /** + * This is a getBlueprintModelByNameAndVersion method + * + * @param name name + * @param version version + * @return BlueprintModel + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelByNameAndVersion(name: String, version: String): BlueprintModel { + val blueprintModel = blueprintModelRepository + .findByArtifactNameAndArtifactVersion(name, version) + if (blueprintModel != null) { + return blueprintModel + } else { + val msg = String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version) + throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) + } + } + + /** + * This is a getBlueprintModelSearch method + * + * @param id id + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelSearch(id: String): BlueprintModelSearch { + return blueprintModelSearchRepository.findById(id) + ?: throw httpProcessorException( + ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, + String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + ) + } + + /** + * This is a searchBluePrintModelsByKeyWord method to retrieve specific BlueprintModel in Database + * where keyword equals updatedBy or tags or artifcat name or artifcat version or artifact type + * @author Shaaban Ebrahim + * @param keyWord + * + * @return List list of the controller blueprint + */ + open fun searchBluePrintModelsByKeyWord(keyWord: String): List { + return blueprintModelSearchRepository.findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType( + keyWord, keyWord, keyWord, keyWord, keyWord + ) + } + + /** + * This is a searchBluePrintModelsByKeyWordPagebale method to retrieve specific BlueprintModel in Database + * where keyword equals updatedBy or tags or artifcat name or artifcat version or artifact type and pageable + * @author Shaaban Ebrahim + * @param keyWord + * + * @return List list of the controller blueprint + */ + open fun searchBluePrintModelsByKeyWordPaged(keyWord: String, pageRequest: PageRequest): Page { + return blueprintModelSearchRepository.findByUpdatedByContainingIgnoreCaseOrTagsContainingIgnoreCaseOrArtifactNameContainingIgnoreCaseOrArtifactVersionContainingIgnoreCaseOrArtifactTypeContainingIgnoreCase( + keyWord, + keyWord, + keyWord, + keyWord, + keyWord, + pageRequest + ) + } + + /** + * This is a deleteBlueprintModel method + * + * @param id id + * @throws BluePrintException BluePrintException + */ + @Transactional + @Throws(BluePrintException::class) + open fun deleteBlueprintModel(id: String) { + val dbBlueprintModel = blueprintModelRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModelContentRepository.deleteByBlueprintModel(dbBlueprintModel.get()) + blueprintModelRepository.delete(dbBlueprintModel.get()) + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) + } + } + + open suspend fun deleteBlueprintModel(name: String, version: String) { + blueprintsProcessorCatalogService.deleteFromDatabase(name, version) + } + + /** + * This is a CBA enrichBlueprint method + * Save the Zip File in archive location and extract the cba content. + * Populate the Enhancement Location + * Enhance the CBA content + * Compress the Enhanced Content + * Return back the the compressed content back to the caller. + * + * @param filePart filePart + * @return ResponseEntity + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open suspend fun enrichBlueprint(filePart: FilePart): ResponseEntity { + try { + val enhancedByteArray = enrichBlueprintFileSource(filePart) + return BluePrintEnhancerUtils.prepareResourceEntity("enhanced-cba.zip", enhancedByteArray) + } catch (e: BluePrintProcessorException) { + e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) + val errorMsg = "Error while enhancing the CBA package." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong CBA file provided, please verify and enrich Again." + ) + } catch (e: Exception) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "EnrichBlueprint: ${e.message}", e.errorCauseOrDefault() + ) + } + } + + /** + * This is a publishBlueprintModel method to change the status published to YES + * NOTE: this method is meant for enriched blueprints only. + * + * @param filePart filePart + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open suspend fun publishBlueprint(filePart: FilePart): BlueprintModelSearch { + try { + return upload(filePart, true) + } catch (e: BluePrintProcessorException) { + e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) + val errorMsg = "Error in Publishing CBA." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong CBA provided, please verify and enrich your CBA." + ) + } catch (e: Exception) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "Error in Publishing CBA: ${e.message}", e.errorCauseOrDefault() + ) + } + } + + /** + * Enrich and publish the blueprint. + * NOTE: this method is meant for the unenriched vs publishBlueprint(filePart) + * which is used for enriched blueprints. + * + * @param filePart filePart + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open suspend fun enrichAndPublishBlueprint(filePart: FilePart): BlueprintModelSearch { + try { + val enhancedByteArray = enrichBlueprintFileSource(filePart) + return upload(enhancedByteArray, true) + } catch (e: BluePrintProcessorException) { + e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) + val errorMsg = "Error while enhancing and uploading the CBA package." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong CBA file provided, please verify the source CBA." + ) + } catch (e: Exception) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "EnrichBlueprint: ${e.message}", e.errorCauseOrDefault() + ) + } + } + + /** Common CBA Save and Publish function for RestController and GRPC Handler, the [fileSource] may be + * byteArray or File Part type.*/ + open suspend fun upload(fileSource: Any, validate: Boolean): BlueprintModelSearch { + val saveId = UUID.randomUUID().toString() + val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, saveId) + val blueprintWorking = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId) + try { + val compressedFile = normalizedFile(blueprintArchive, "cba.zip") + when (fileSource) { + is FilePart -> BluePrintEnhancerUtils.filePartAsFile(fileSource, compressedFile) + is ByteArray -> BluePrintEnhancerUtils.byteArrayAsFile(fileSource, compressedFile) + } + // Save the Copied file to Database + val blueprintId = blueprintsProcessorCatalogService.saveToDatabase(saveId, compressedFile, validate) + + return blueprintModelSearchRepository.findById(blueprintId) + ?: throw httpProcessorException( + ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, + String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, blueprintId) + ) + } catch (e: BluePrintException) { + e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) + val errorMsg = "Error in Upload CBA." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong enriched CBA." + ) + } catch (e: IOException) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "Error in Upload CBA: ${e.errorMessageOrDefault()}", e.errorCauseOrDefault() + ) + } finally { + // Clean blueprint script cache + val cacheKey = BluePrintFileUtils + .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId)) + BluePrintCompileCache.cleanClassLoader(cacheKey) + deleteNBDir(blueprintArchive) + deleteNBDir(blueprintWorking) + } + } + + /** Common CBA download function for RestController and GRPC Handler, the [fileSource] may be + * byteArray or File Part type.*/ + open fun download(name: String, version: String): ByteArray { + try { + val blueprintModel = getBlueprintModelByNameAndVersion(name, version) + return blueprintModel.blueprintModelContent?.content + ?: throw httpProcessorException( + ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, + "Error while downloading the CBA file: couldn't get model content" + ) + } catch (e: BluePrintException) { + e.http(ErrorCatalogCodes.RESOURCE_NOT_FOUND) + val errorMsg = "Fail to get Blueprint Model content." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong name and version was provide." + ) + } + } + + /** Common CBA Enrich function for RestController and GRPC Handler, the [fileSource] may be + * byteArray or File Part type.*/ + open suspend fun enrichBlueprintFileSource(fileSource: Any): ByteArray { + val enhanceId = UUID.randomUUID().toString() + val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, enhanceId) + val blueprintWorkingDir = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, enhanceId) + try { + when (fileSource) { + is FilePart -> + BluePrintEnhancerUtils + .copyFilePartToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir) + is ByteArray -> + BluePrintEnhancerUtils + .copyByteArrayToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir) + } // Enhance the Blue Prints + bluePrintEnhancerService.enhance(blueprintWorkingDir) + + return BluePrintEnhancerUtils.compressEnhanceDirAndReturnByteArray(blueprintWorkingDir, blueprintArchive) + } catch (e: BluePrintException) { + e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) + val errorMsg = "Fail Enriching the CBA." + throw e.updateErrorMessage(DesignerApiDomains.DESIGNER_API, errorMsg) + } catch (e: IOException) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "Error while Enriching the CBA file.", e.errorCauseOrDefault() + ) + } finally { + BluePrintEnhancerUtils.cleanEnhancer(blueprintArchive, blueprintWorkingDir) + } + } + + companion object { + + private const val BLUEPRINT_MODEL_ID_FAILURE_MSG = "failed to get blueprint model id(%s) from repo" + private const val BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG = "failed to get blueprint model by name(%s)" + " and version(%s) from repo" + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BlueprintModelHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BlueprintModelHandler.kt deleted file mode 100644 index 42954c16e..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BlueprintModelHandler.kt +++ /dev/null @@ -1,643 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 IBM. - * Modifications Copyright © 2019 Orange. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler - -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelContentRepository -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelSearchRepository -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.BootstrapRequest -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowData -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowSpecRequest -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowSpecResponse -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowsResponse -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.BlueprintDatabaseLoadService -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir -import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BlueprintCompileCache -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintFileUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment -import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes -import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault -import org.onap.ccsdk.cds.error.catalog.core.utils.errorMessageOrDefault -import org.springframework.core.io.ByteArrayResource -import org.springframework.core.io.Resource -import org.springframework.data.domain.Page -import org.springframework.data.domain.PageRequest -import org.springframework.data.domain.Pageable -import org.springframework.http.HttpHeaders -import org.springframework.http.MediaType -import org.springframework.http.ResponseEntity -import org.springframework.http.codec.multipart.FilePart -import org.springframework.stereotype.Service -import org.springframework.transaction.annotation.Transactional -import java.io.File -import java.io.IOException -import java.util.UUID - -/** - * BlueprintModelHandler Purpose: Handler service to handle the request from BlurPrintModelRest - * - * @author Brinda Santh - * @version 1.0 - */ - -@Service -open class BlueprintModelHandler( - private val bluePrintDatabaseLoadService: BlueprintDatabaseLoadService, - private val blueprintsProcessorCatalogService: BlueprintCatalogService, - private val bluePrintLoadConfiguration: BlueprintLoadConfiguration, - private val blueprintModelSearchRepository: BlueprintModelSearchRepository, - private val blueprintModelRepository: BlueprintModelRepository, - private val blueprintModelContentRepository: BlueprintModelContentRepository, - private val bluePrintEnhancerService: BlueprintEnhancerService -) { - - private val log = logger(BlueprintModelHandler::class) - - open suspend fun bootstrapBlueprint(bootstrapRequest: BootstrapRequest) { - log.info( - "Bootstrap request with type load(${bootstrapRequest.loadModelType}), " + - "resource dictionary load(${bootstrapRequest.loadResourceDictionary}) and " + - "cba load(${bootstrapRequest.loadCBA})" - ) - if (bootstrapRequest.loadModelType) { - bluePrintDatabaseLoadService.initModelTypes() - } - if (bootstrapRequest.loadResourceDictionary) { - bluePrintDatabaseLoadService.initResourceDictionary() - } - if (bootstrapRequest.loadCBA) { - bluePrintDatabaseLoadService.initBlueprintCatalog() - } - } - - @Throws(BlueprintException::class) - open suspend fun prepareWorkFlowSpec(req: WorkFlowSpecRequest): - WorkFlowSpecResponse { - val basePath = blueprintsProcessorCatalogService.getFromDatabase( - req - .blueprintName, - req.version - ) - log.info("blueprint base path $basePath") - - val blueprintContext = BlueprintMetadataUtils.getBlueprintContext(basePath.toString()) - val workFlow = blueprintContext.workflowByName(req.workflowName) - - val wfRes = WorkFlowSpecResponse() - wfRes.blueprintName = req.blueprintName - wfRes.version = req.version - - val workFlowData = WorkFlowData() - workFlowData.workFlowName = req.workflowName - workFlowData.inputs = workFlow.inputs - workFlowData.outputs = workFlow.outputs - wfRes.workFlowData = workFlowData - - if (workFlow.inputs != null) { - for ((k, v) in workFlow.inputs!!) { - addPropertyInfo(k, v, blueprintContext, wfRes) - } - } - - if (workFlow.outputs != null) { - for ((k, v) in workFlow.outputs!!) { - addPropertyInfo(k, v, blueprintContext, wfRes) - } - } - - return wfRes - } - - private fun addPropertyInfo(propName: String, prop: PropertyDefinition, ctx: BlueprintContext, res: WorkFlowSpecResponse) { - updatePropertyInfo(propName, prop, ctx, res) - addDataType(prop.type, ctx, res) - if (prop.entrySchema != null && prop.entrySchema!!.type != null) { - addDataType(prop.entrySchema!!.type, ctx, res) - } - } - - private fun updatePropertyInfo(name: String, prop: PropertyDefinition, ctx: BlueprintContext, res: WorkFlowSpecResponse) { - if (prop.inputparam == null || prop.inputparam == false) { - var workflow = ctx.workflowByName(res.workFlowData.workFlowName) - for ((k, v) in workflow.steps!!) { - var arts = ctx.nodeTemplateArtifacts(v.target!!) - if (arts != null) { - for ((k, v) in arts.entries!!) { - if (v.type == "artifact-mapping-resource") { - val file: String = v.file - val completePath = ctx.rootPath.plus(File.separator).plus(file) - val resourceAssignment = JacksonUtils.getListFromFile(completePath, ResourceAssignment::class.java) - for (res in resourceAssignment) { - if (res.name == name && res.inputParameter) { - prop.inputparam = true - return - } - } - } - } - } - } - } - } - - private fun addDataType(name: String, ctx: BlueprintContext, res: WorkFlowSpecResponse) { - var data = ctx.dataTypeByName(name) - if (data != null) { - res.dataTypes?.put(name, data) - addParentDataType(data, ctx, res) - } - } - - private fun addParentDataType(data: DataType, ctx: BlueprintContext, res: WorkFlowSpecResponse) { - if (data.properties != null) { - for ((k, v) in data.properties!!) { - addPropertyInfo(k, v, ctx, res) - } - } - } - - @Throws(BlueprintException::class) - open suspend fun getWorkflowNames(name: String, version: String): WorkFlowsResponse { - val basePath = blueprintsProcessorCatalogService.getFromDatabase( - name, version - ) - log.info("blueprint base path $basePath") - - var res = WorkFlowsResponse() - res.blueprintName = name - res.version = version - - val blueprintContext = BlueprintMetadataUtils.getBlueprintContext( - basePath.toString() - ) - if (blueprintContext.workflows() != null) { - res.workflows = blueprintContext.workflows()!!.keys - } - return res - } - - /** - * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database - * - * @return List list of the controller blueprint archives - */ - open fun allBlueprintModel(): List { - return blueprintModelSearchRepository.findAll() - } - - /** - * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database - * - * @return List list of the controller blueprint archives - */ - open fun allBlueprintModel(pageRequest: Pageable): Page { - return blueprintModelSearchRepository.findAll(pageRequest) - } - - /** - * This is a saveBlueprintModel method - * - * @param filePart filePart - * @return Mono - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open suspend fun saveBlueprintModel(filePart: FilePart): BlueprintModelSearch { - try { - return upload(filePart, false) - } catch (e: IOException) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "Error in Save CBA: ${e.message}", e.errorCauseOrDefault() - ) - } - } - - /** - * This is a searchBlueprintModels method - * - * @param tags tags - * @return List - */ - open fun searchBlueprintModels(tags: String): List { - return blueprintModelSearchRepository.findByTagsContainingIgnoreCase(tags) - } - - /** - * This is a getBlueprintModelSearchByNameAndVersion method - * - * @param name name - * @param version version - * @return BlueprintModelSearch - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun getBlueprintModelSearchByNameAndVersion(name: String, version: String): BlueprintModelSearch? { - return blueprintModelSearchRepository.findByArtifactNameAndArtifactVersion(name, version) - /*?: throw BlueprintException( - ErrorCode.RESOURCE_NOT_FOUND.value, - String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version) - )*/ - } - - /** - * This is a downloadBlueprintModelFileByNameAndVersion method to download a Blueprint by Name and Version - * - * @param name name - * @param version version - * @return ResponseEntity - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun downloadBlueprintModelFileByNameAndVersion( - name: String, - version: String - ): ResponseEntity { - try { - val archiveByteArray = download(name, version) - val fileName = "${name}_$version.zip" - return prepareResourceEntity(fileName, archiveByteArray) - } catch (e: BlueprintProcessorException) { - e.http(ErrorCatalogCodes.RESOURCE_NOT_FOUND) - val errorMsg = "Error while downloading the CBA file by Blueprint Name ($name) and Version ($version)." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong resource definition or resolution failed." - ) - } - } - - /** - * This is a downloadBlueprintModelFile method to find the target file to download and return a file resource - * - * @return ResponseEntity - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun downloadBlueprintModelFile(id: String): ResponseEntity { - val blueprintModel: BlueprintModel - try { - blueprintModel = getBlueprintModel(id) - } catch (e: BlueprintException) { - throw httpProcessorException( - ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, - "Error while downloading the CBA file: couldn't get blueprint modelby ID ($id)", - e.errorCauseOrDefault() - ) - } - - val fileName = "${blueprintModel.artifactName}_${blueprintModel.artifactVersion}.zip" - val file = blueprintModel.blueprintModelContent?.content - ?: throw httpProcessorException( - ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, - "Error while downloading the CBA file: couldn't get model content" - ) - return prepareResourceEntity(fileName, file) - } - - /** - * @return ResponseEntity - */ - private fun prepareResourceEntity(fileName: String, file: ByteArray): ResponseEntity { - return ResponseEntity.ok() - .contentType(MediaType.parseMediaType("text/plain")) - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"") - .body(ByteArrayResource(file)) - } - - /** - * This is a getBlueprintModel method - * - * @param id id - * @return BlueprintModel - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun getBlueprintModel(id: String): BlueprintModel { - val blueprintModel: BlueprintModel - val dbBlueprintModel = blueprintModelRepository.findById(id) - if (dbBlueprintModel.isPresent) { - blueprintModel = dbBlueprintModel.get() - } else { - val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) - throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) - } - return blueprintModel - } - - /** - * This is a getBlueprintModelByNameAndVersion method - * - * @param name name - * @param version version - * @return BlueprintModel - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun getBlueprintModelByNameAndVersion(name: String, version: String): BlueprintModel { - val blueprintModel = blueprintModelRepository - .findByArtifactNameAndArtifactVersion(name, version) - if (blueprintModel != null) { - return blueprintModel - } else { - val msg = String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version) - throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) - } - } - - /** - * This is a getBlueprintModelSearch method - * - * @param id id - * @return BlueprintModelSearch - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun getBlueprintModelSearch(id: String): BlueprintModelSearch { - return blueprintModelSearchRepository.findById(id) - ?: throw httpProcessorException( - ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, - String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) - ) - } - - /** - * This is a searchBlueprintModelsByKeyWord method to retrieve specific BlueprintModel in Database - * where keyword equals updatedBy or tags or artifcat name or artifcat version or artifact type - * @author Shaaban Ebrahim - * @param keyWord - * - * @return List list of the controller blueprint - */ - open fun searchBlueprintModelsByKeyWord(keyWord: String): List { - return blueprintModelSearchRepository.findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType( - keyWord, keyWord, keyWord, keyWord, keyWord - ) - } - - /** - * This is a searchBlueprintModelsByKeyWordPagebale method to retrieve specific BlueprintModel in Database - * where keyword equals updatedBy or tags or artifcat name or artifcat version or artifact type and pageable - * @author Shaaban Ebrahim - * @param keyWord - * - * @return List list of the controller blueprint - */ - open fun searchBlueprintModelsByKeyWordPaged(keyWord: String, pageRequest: PageRequest): Page { - return blueprintModelSearchRepository.findByUpdatedByContainingIgnoreCaseOrTagsContainingIgnoreCaseOrArtifactNameContainingIgnoreCaseOrArtifactVersionContainingIgnoreCaseOrArtifactTypeContainingIgnoreCase( - keyWord, - keyWord, - keyWord, - keyWord, - keyWord, - pageRequest - ) - } - - /** - * This is a deleteBlueprintModel method - * - * @param id id - * @throws BlueprintException BlueprintException - */ - @Transactional - @Throws(BlueprintException::class) - open fun deleteBlueprintModel(id: String) { - val dbBlueprintModel = blueprintModelRepository.findById(id) - if (dbBlueprintModel.isPresent) { - blueprintModelContentRepository.deleteByBlueprintModel(dbBlueprintModel.get()) - blueprintModelRepository.delete(dbBlueprintModel.get()) - } else { - val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) - throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) - } - } - - open suspend fun deleteBlueprintModel(name: String, version: String) { - blueprintsProcessorCatalogService.deleteFromDatabase(name, version) - } - - /** - * This is a CBA enrichBlueprint method - * Save the Zip File in archive location and extract the cba content. - * Populate the Enhancement Location - * Enhance the CBA content - * Compress the Enhanced Content - * Return back the the compressed content back to the caller. - * - * @param filePart filePart - * @return ResponseEntity - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open suspend fun enrichBlueprint(filePart: FilePart): ResponseEntity { - try { - val enhancedByteArray = enrichBlueprintFileSource(filePart) - return BlueprintEnhancerUtils.prepareResourceEntity("enhanced-cba.zip", enhancedByteArray) - } catch (e: BlueprintProcessorException) { - e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) - val errorMsg = "Error while enhancing the CBA package." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong CBA file provided, please verify and enrich Again." - ) - } catch (e: Exception) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "EnrichBlueprint: ${e.message}", e.errorCauseOrDefault() - ) - } - } - - /** - * This is a publishBlueprintModel method to change the status published to YES - * NOTE: this method is meant for enriched blueprints only. - * - * @param filePart filePart - * @return BlueprintModelSearch - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open suspend fun publishBlueprint(filePart: FilePart): BlueprintModelSearch { - try { - return upload(filePart, true) - } catch (e: BlueprintProcessorException) { - e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) - val errorMsg = "Error in Publishing CBA." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong CBA provided, please verify and enrich your CBA." - ) - } catch (e: Exception) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "Error in Publishing CBA: ${e.message}", e.errorCauseOrDefault() - ) - } - } - - /** - * Enrich and publish the blueprint. - * NOTE: this method is meant for the unenriched vs publishBlueprint(filePart) - * which is used for enriched blueprints. - * - * @param filePart filePart - * @return BlueprintModelSearch - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open suspend fun enrichAndPublishBlueprint(filePart: FilePart): BlueprintModelSearch { - try { - val enhancedByteArray = enrichBlueprintFileSource(filePart) - return upload(enhancedByteArray, true) - } catch (e: BlueprintProcessorException) { - e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) - val errorMsg = "Error while enhancing and uploading the CBA package." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong CBA file provided, please verify the source CBA." - ) - } catch (e: Exception) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "EnrichBlueprint: ${e.message}", e.errorCauseOrDefault() - ) - } - } - - /** Common CBA Save and Publish function for RestController and GRPC Handler, the [fileSource] may be - * byteArray or File Part type.*/ - open suspend fun upload(fileSource: Any, validate: Boolean): BlueprintModelSearch { - val saveId = UUID.randomUUID().toString() - val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, saveId) - val blueprintWorking = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId) - try { - val compressedFile = normalizedFile(blueprintArchive, "cba.zip") - when (fileSource) { - is FilePart -> BlueprintEnhancerUtils.filePartAsFile(fileSource, compressedFile) - is ByteArray -> BlueprintEnhancerUtils.byteArrayAsFile(fileSource, compressedFile) - } - // Save the Copied file to Database - val blueprintId = blueprintsProcessorCatalogService.saveToDatabase(saveId, compressedFile, validate) - - return blueprintModelSearchRepository.findById(blueprintId) - ?: throw httpProcessorException( - ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, - String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, blueprintId) - ) - } catch (e: BlueprintException) { - e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) - val errorMsg = "Error in Upload CBA." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong enriched CBA." - ) - } catch (e: IOException) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "Error in Upload CBA: ${e.errorMessageOrDefault()}", e.errorCauseOrDefault() - ) - } finally { - // Clean blueprint script cache - val cacheKey = BlueprintFileUtils - .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId)) - BlueprintCompileCache.cleanClassLoader(cacheKey) - deleteNBDir(blueprintArchive) - deleteNBDir(blueprintWorking) - } - } - - /** Common CBA download function for RestController and GRPC Handler, the [fileSource] may be - * byteArray or File Part type.*/ - open fun download(name: String, version: String): ByteArray { - try { - val blueprintModel = getBlueprintModelByNameAndVersion(name, version) - return blueprintModel.blueprintModelContent?.content - ?: throw httpProcessorException( - ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, - "Error while downloading the CBA file: couldn't get model content" - ) - } catch (e: BlueprintException) { - e.http(ErrorCatalogCodes.RESOURCE_NOT_FOUND) - val errorMsg = "Fail to get Blueprint Model content." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong name and version was provide." - ) - } - } - - /** Common CBA Enrich function for RestController and GRPC Handler, the [fileSource] may be - * byteArray or File Part type.*/ - open suspend fun enrichBlueprintFileSource(fileSource: Any): ByteArray { - val enhanceId = UUID.randomUUID().toString() - val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, enhanceId) - val blueprintWorkingDir = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, enhanceId) - try { - when (fileSource) { - is FilePart -> - BlueprintEnhancerUtils - .copyFilePartToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir) - is ByteArray -> - BlueprintEnhancerUtils - .copyByteArrayToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir) - } // Enhance the Blue Prints - bluePrintEnhancerService.enhance(blueprintWorkingDir) - - return BlueprintEnhancerUtils.compressEnhanceDirAndReturnByteArray(blueprintWorkingDir, blueprintArchive) - } catch (e: BlueprintException) { - e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) - val errorMsg = "Fail Enriching the CBA." - throw e.updateErrorMessage(DesignerApiDomains.DESIGNER_API, errorMsg) - } catch (e: IOException) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "Error while Enriching the CBA file.", e.errorCauseOrDefault() - ) - } finally { - BlueprintEnhancerUtils.cleanEnhancer(blueprintArchive, blueprintWorkingDir) - } - } - - companion object { - - private const val BLUEPRINT_MODEL_ID_FAILURE_MSG = "failed to get blueprint model id(%s) from repo" - private const val BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG = "failed to get blueprint model by name(%s)" + " and version(%s) from repo" - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt index 864fe7ca9..0d94aab27 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt @@ -21,7 +21,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ModelTypeRepository import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.ModelTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes import org.slf4j.LoggerFactory @@ -68,9 +68,9 @@ open class ModelTypeHandler(private val modelTypeRepository: ModelTypeRepository * * @param modelType modelType * @return ModelType - * @throws BlueprintException BlueprintException + * @throws BluePrintException BluePrintException */ - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) open suspend fun saveModel(modelType: ModelType): ModelType { lateinit var dbModel: ModelType ModelTypeValidator.validateModelType(modelType) diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt index e2e726843..3f06a4a98 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt @@ -23,7 +23,7 @@ import org.apache.commons.lang3.StringUtils import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ResourceDictionary import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ResourceDictionaryRepository -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition @@ -40,9 +40,9 @@ class ResourceDictionaryHandler(private val resourceDictionaryRepository: Resour * * @param name name * @return DataDictionary - * @throws BlueprintException BlueprintException + * @throws BluePrintException BluePrintException */ - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun getResourceDictionaryByName(name: String): ResourceDictionary { Preconditions.checkArgument(StringUtils.isNotBlank(name), "Resource dictionary Name Information is missing.") val resourceDictionaryDb = resourceDictionaryRepository.findByName(name) @@ -84,7 +84,7 @@ class ResourceDictionaryHandler(private val resourceDictionaryRepository: Resour * @param resourceDictionary resourceDictionary * @return DataDictionary */ - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun saveResourceDictionary(resourceDictionary: ResourceDictionary): ResourceDictionary { var resourceDictionary = resourceDictionary @@ -133,7 +133,7 @@ class ResourceDictionaryHandler(private val resourceDictionaryRepository: Resour * @param resourceDefinition ResourceDefinition * @return ResourceDefinition */ - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun saveResourceDefinition(resourceDefinition: ResourceDefinition): ResourceDefinition { val resourceDictionary = ResourceDictionary() resourceDictionary.name = resourceDefinition.name diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt new file mode 100644 index 000000000..8d209449c --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt @@ -0,0 +1,69 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load + +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import org.apache.commons.lang.text.StrBuilder +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Service +import java.io.File +import java.util.UUID + +@Service +open class BluePrintCatalogLoadService(private val controllerBlueprintsCatalogService: BluePrintCatalogService) { + + private val log = LoggerFactory.getLogger(BluePrintCatalogLoadService::class.java) + + open fun loadPathsBluePrintModelCatalog(paths: List) { + paths.forEach { loadPathBluePrintModelCatalog(it) } + } + + open fun loadPathBluePrintModelCatalog(path: String) { + + val files = File(path).listFiles() + runBlocking { + val errorBuilder = StrBuilder() + val deferredResults = mutableListOf>() + + for (file in files) { + deferredResults += async { + loadBluePrintModelCatalog(errorBuilder, file) + } + } + + for (deferredResult in deferredResults) { + deferredResult.await() + } + + if (!errorBuilder.isEmpty) { + log.error(errorBuilder.toString()) + } + } + } + + open suspend fun loadBluePrintModelCatalog(errorBuilder: StrBuilder, file: File) { + try { + controllerBlueprintsCatalogService.saveToDatabase(UUID.randomUUID().toString(), file) + } catch (e: Exception) { + errorBuilder.appendln("Couldn't load BlueprintModel(${file.name}: ${e.message}") + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt new file mode 100644 index 000000000..02d6ad3c1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt @@ -0,0 +1,67 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load + +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Service + +@Service +open class BluePrintDatabaseLoadService( + private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, + private val modelTypeLoadService: ModelTypeLoadService, + private val resourceDictionaryLoadService: ResourceDictionaryLoadService, + private val bluePrintCatalogLoadService: BluePrintCatalogLoadService +) { + + private val log = LoggerFactory.getLogger(BluePrintDatabaseLoadService::class.java) + + open fun init() = runBlocking { + initModelTypes() + initResourceDictionary() + initBluePrintCatalog() + } + + open suspend fun initModelTypes() { + log.info("model types load from paths(${bluePrintLoadConfiguration.loadModeTypePaths})") + + val paths = bluePrintLoadConfiguration.loadModeTypePaths?.split(",") + paths?.let { + modelTypeLoadService.loadPathsModelType(paths) + } + } + + open suspend fun initResourceDictionary() { + log.info("resource dictionary load from paths(${bluePrintLoadConfiguration.loadResourceDictionaryPaths})") + + val paths = bluePrintLoadConfiguration.loadResourceDictionaryPaths?.split(",") + paths?.let { + resourceDictionaryLoadService.loadPathsResourceDictionary(paths) + } + } + + open suspend fun initBluePrintCatalog() { + log.info("cba load from paths(${bluePrintLoadConfiguration.loadBluePrintPaths})") + + val paths = bluePrintLoadConfiguration.loadBluePrintPaths?.split(",") + paths?.let { + bluePrintCatalogLoadService.loadPathsBluePrintModelCatalog(paths) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintCatalogLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintCatalogLoadService.kt deleted file mode 100644 index bcb1ebbed..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintCatalogLoadService.kt +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load - -import kotlinx.coroutines.Deferred -import kotlinx.coroutines.async -import kotlinx.coroutines.runBlocking -import org.apache.commons.lang.text.StrBuilder -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Service -import java.io.File -import java.util.UUID - -@Service -open class BlueprintCatalogLoadService(private val controllerBlueprintsCatalogService: BlueprintCatalogService) { - - private val log = LoggerFactory.getLogger(BlueprintCatalogLoadService::class.java) - - open fun loadPathsBlueprintModelCatalog(paths: List) { - paths.forEach { loadPathBlueprintModelCatalog(it) } - } - - open fun loadPathBlueprintModelCatalog(path: String) { - - val files = File(path).listFiles() - runBlocking { - val errorBuilder = StrBuilder() - val deferredResults = mutableListOf>() - - for (file in files) { - deferredResults += async { - loadBlueprintModelCatalog(errorBuilder, file) - } - } - - for (deferredResult in deferredResults) { - deferredResult.await() - } - - if (!errorBuilder.isEmpty) { - log.error(errorBuilder.toString()) - } - } - } - - open suspend fun loadBlueprintModelCatalog(errorBuilder: StrBuilder, file: File) { - try { - controllerBlueprintsCatalogService.saveToDatabase(UUID.randomUUID().toString(), file) - } catch (e: Exception) { - errorBuilder.appendln("Couldn't load BlueprintModel(${file.name}: ${e.message}") - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintDatabaseLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintDatabaseLoadService.kt deleted file mode 100644 index 0534e16a5..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintDatabaseLoadService.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load - -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Service - -@Service -open class BlueprintDatabaseLoadService( - private val bluePrintLoadConfiguration: BlueprintLoadConfiguration, - private val modelTypeLoadService: ModelTypeLoadService, - private val resourceDictionaryLoadService: ResourceDictionaryLoadService, - private val bluePrintCatalogLoadService: BlueprintCatalogLoadService -) { - - private val log = LoggerFactory.getLogger(BlueprintDatabaseLoadService::class.java) - - open fun init() = runBlocking { - initModelTypes() - initResourceDictionary() - initBlueprintCatalog() - } - - open suspend fun initModelTypes() { - log.info("model types load from paths(${bluePrintLoadConfiguration.loadModeTypePaths})") - - val paths = bluePrintLoadConfiguration.loadModeTypePaths?.split(",") - paths?.let { - modelTypeLoadService.loadPathsModelType(paths) - } - } - - open suspend fun initResourceDictionary() { - log.info("resource dictionary load from paths(${bluePrintLoadConfiguration.loadResourceDictionaryPaths})") - - val paths = bluePrintLoadConfiguration.loadResourceDictionaryPaths?.split(",") - paths?.let { - resourceDictionaryLoadService.loadPathsResourceDictionary(paths) - } - } - - open suspend fun initBlueprintCatalog() { - log.info("cba load from paths(${bluePrintLoadConfiguration.loadBlueprintPaths})") - - val paths = bluePrintLoadConfiguration.loadBlueprintPaths?.split(",") - paths?.let { - bluePrintCatalogLoadService.loadPathsBlueprintModelCatalog(paths) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt index cb7953363..e96daf9f0 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt @@ -24,8 +24,8 @@ import org.apache.commons.io.FilenameUtils import org.apache.commons.lang3.text.StrBuilder import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ModelTypeHandler -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType import org.onap.ccsdk.cds.controllerblueprints.core.data.EntityType @@ -118,19 +118,19 @@ open class ModelTypeLoadService(private val modelTypeHandler: ModelTypeHandler) val definitionType: String? when (T::class) { DataType::class -> { - definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE } RelationshipType::class -> { - definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE + definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE } ArtifactType::class -> { - definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE + definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE } NodeType::class -> { - definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE + definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE } else -> { - throw BlueprintException("couldn't process model type($classType) definition") + throw BluePrintException("couldn't process model type($classType) definition") } } modelType.definitionType = definitionType diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt index 295e89a9e..15cf3dcb0 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt @@ -22,7 +22,7 @@ import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import org.apache.commons.lang3.text.StrBuilder import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ResourceDictionaryHandler -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.readNBText import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils @@ -75,7 +75,7 @@ open class ResourceDictionaryLoadService(private val resourceDictionaryHandler: resourceDictionaryHandler.saveResourceDefinition(resourceDefinition) log.trace("Resource dictionary(${file.name}) loaded successfully ") } else { - throw BlueprintException("couldn't get dictionary from content information") + throw BluePrintException("couldn't get dictionary from content information") } } catch (e: Exception) { errorBuilder.appendln("Couldn't load Resource dictionary (${file.name}: ${e.message})") diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt new file mode 100644 index 000000000..420a9fcd7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt @@ -0,0 +1,115 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service + +import com.fasterxml.jackson.databind.JsonNode +import com.google.common.base.Preconditions +import org.apache.commons.lang3.StringUtils +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ModelTypeRepository +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ResourceDictionaryRepository +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition +import org.springframework.stereotype.Service + +interface ResourceDefinitionRepoService : BluePrintRepoService { + + @Throws(BluePrintException::class) + fun getResourceDefinition(resourceDefinitionName: String): ResourceDefinition +} + +@Service +open class BluePrintRepoFileService( + private val modelTypeRepository: ModelTypeRepository, + private val resourceDictionaryRepository: ResourceDictionaryRepository +) : ResourceDefinitionRepoService { + + @Throws(BluePrintException::class) + override fun getNodeType(nodeTypeName: String): NodeType { + return getModelType(nodeTypeName, NodeType::class.java) + ?: throw BluePrintException("couldn't get NodeType($nodeTypeName)") + } + + @Throws(BluePrintException::class) + override fun getDataType(dataTypeName: String): DataType { + return getModelType(dataTypeName, DataType::class.java) + ?: throw BluePrintException("couldn't get DataType($dataTypeName)") + } + + @Throws(BluePrintException::class) + override fun getArtifactType(artifactTypeName: String): ArtifactType { + return getModelType(artifactTypeName, ArtifactType::class.java) + ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName)") + } + + @Throws(BluePrintException::class) + override fun getRelationshipType(relationshipTypeName: String): RelationshipType { + return getModelType(relationshipTypeName, RelationshipType::class.java) + ?: throw BluePrintException("couldn't get RelationshipType($relationshipTypeName)") + } + + @Throws(BluePrintException::class) + override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition { + return getModelType(capabilityDefinitionName, CapabilityDefinition::class.java) + ?: throw BluePrintException("couldn't get CapabilityDefinition($capabilityDefinitionName)") + } + + @Throws(BluePrintException::class) + override fun getResourceDefinition(resourceDefinitionName: String): ResourceDefinition { + val dbResourceDictionary = resourceDictionaryRepository.findByName(resourceDefinitionName) + return if (dbResourceDictionary != null) { + dbResourceDictionary.definition + } else { + throw BluePrintException(String.format("failed to get resource dictionary (%s) from repo", resourceDefinitionName)) + } + } + + @Throws(BluePrintException::class) + private fun getModelType(modelName: String, valueClass: Class): T? { + Preconditions.checkArgument( + StringUtils.isNotBlank(modelName), + "Failed to get model from repo, model name is missing" + ) + + val modelDefinition = getModelDefinition(modelName) + Preconditions.checkNotNull( + modelDefinition, + String.format("Failed to get model content for model name (%s)", modelName) + ) + + return JacksonUtils.readValue(modelDefinition, valueClass) + } + + @Throws(BluePrintException::class) + private fun getModelDefinition(modelName: String): JsonNode { + val modelDefinition: JsonNode + val modelTypeDb = modelTypeRepository.findByModelName(modelName) + if (modelTypeDb != null) { + modelDefinition = modelTypeDb.definition + } else { + throw BluePrintException(String.format("failed to get model definition (%s) from repo", modelName)) + } + return modelDefinition + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BlueprintRepoServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BlueprintRepoServiceImpl.kt deleted file mode 100644 index 19f4e61b7..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BlueprintRepoServiceImpl.kt +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service - -import com.fasterxml.jackson.databind.JsonNode -import com.google.common.base.Preconditions -import org.apache.commons.lang3.StringUtils -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ModelTypeRepository -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ResourceDictionaryRepository -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition -import org.springframework.stereotype.Service - -interface ResourceDefinitionRepoService : BlueprintRepoService { - - @Throws(BlueprintException::class) - fun getResourceDefinition(resourceDefinitionName: String): ResourceDefinition -} - -@Service -open class BlueprintRepoFileService( - private val modelTypeRepository: ModelTypeRepository, - private val resourceDictionaryRepository: ResourceDictionaryRepository -) : ResourceDefinitionRepoService { - - @Throws(BlueprintException::class) - override fun getNodeType(nodeTypeName: String): NodeType { - return getModelType(nodeTypeName, NodeType::class.java) - ?: throw BlueprintException("couldn't get NodeType($nodeTypeName)") - } - - @Throws(BlueprintException::class) - override fun getDataType(dataTypeName: String): DataType { - return getModelType(dataTypeName, DataType::class.java) - ?: throw BlueprintException("couldn't get DataType($dataTypeName)") - } - - @Throws(BlueprintException::class) - override fun getArtifactType(artifactTypeName: String): ArtifactType { - return getModelType(artifactTypeName, ArtifactType::class.java) - ?: throw BlueprintException("couldn't get ArtifactType($artifactTypeName)") - } - - @Throws(BlueprintException::class) - override fun getRelationshipType(relationshipTypeName: String): RelationshipType { - return getModelType(relationshipTypeName, RelationshipType::class.java) - ?: throw BlueprintException("couldn't get RelationshipType($relationshipTypeName)") - } - - @Throws(BlueprintException::class) - override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition { - return getModelType(capabilityDefinitionName, CapabilityDefinition::class.java) - ?: throw BlueprintException("couldn't get CapabilityDefinition($capabilityDefinitionName)") - } - - @Throws(BlueprintException::class) - override fun getResourceDefinition(resourceDefinitionName: String): ResourceDefinition { - val dbResourceDictionary = resourceDictionaryRepository.findByName(resourceDefinitionName) - return if (dbResourceDictionary != null) { - dbResourceDictionary.definition - } else { - throw BlueprintException(String.format("failed to get resource dictionary (%s) from repo", resourceDefinitionName)) - } - } - - @Throws(BlueprintException::class) - private fun getModelType(modelName: String, valueClass: Class): T? { - Preconditions.checkArgument( - StringUtils.isNotBlank(modelName), - "Failed to get model from repo, model name is missing" - ) - - val modelDefinition = getModelDefinition(modelName) - Preconditions.checkNotNull( - modelDefinition, - String.format("Failed to get model content for model name (%s)", modelName) - ) - - return JacksonUtils.readValue(modelDefinition, valueClass) - } - - @Throws(BlueprintException::class) - private fun getModelDefinition(modelName: String): JsonNode { - val modelDefinition: JsonNode - val modelTypeDb = modelTypeRepository.findByModelName(modelName) - if (modelTypeDb != null) { - modelDefinition = modelTypeDb.definition - } else { - throw BlueprintException(String.format("failed to get model definition (%s) from repo", modelName)) - } - return modelDefinition - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt new file mode 100644 index 000000000..6d72c2741 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt @@ -0,0 +1,191 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils + +import kotlinx.coroutines.reactive.awaitSingle +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.deCompress +import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.reCreateNBDirs +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils +import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.codec.multipart.FilePart +import java.io.File +import java.nio.file.Paths + +class BluePrintEnhancerUtils { + companion object { + + val log = logger(BluePrintEnhancerUtils) + + fun populateDataTypes( + bluePrintContext: BluePrintContext, + bluePrintRepoService: BluePrintRepoService, + dataTypeName: String + ): DataType { + val dataType = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName) + ?: bluePrintRepoService.getDataType(dataTypeName) + ?: throw BluePrintException("couldn't get DataType($dataTypeName) from repo.") + bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dataType) + return dataType + } + + fun populateRelationshipType( + bluePrintContext: BluePrintContext, + bluePrintRepoService: BluePrintRepoService, + relationshipName: String + ): RelationshipType { + + val relationshipType = bluePrintContext.serviceTemplate.relationshipTypes?.get(relationshipName) + ?: bluePrintRepoService.getRelationshipType(relationshipName) + ?: throw BluePrintException("couldn't get RelationshipType($relationshipName) from repo.") + bluePrintContext.serviceTemplate.relationshipTypes?.put(relationshipName, relationshipType) + return relationshipType + } + + fun populateNodeType( + bluePrintContext: BluePrintContext, + bluePrintRepoService: BluePrintRepoService, + nodeTypeName: String + ): NodeType { + + val nodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(nodeTypeName) + ?: bluePrintRepoService.getNodeType(nodeTypeName) + ?: throw BluePrintException("couldn't get NodeType($nodeTypeName) from repo.") + bluePrintContext.serviceTemplate.nodeTypes?.put(nodeTypeName, nodeType) + return nodeType + } + + fun populateArtifactType( + bluePrintContext: BluePrintContext, + bluePrintRepoService: BluePrintRepoService, + artifactTypeName: String + ): ArtifactType { + + val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName) + ?: bluePrintRepoService.getArtifactType(artifactTypeName) + ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName) from repo.") + bluePrintContext.serviceTemplate.artifactTypes?.put(artifactTypeName, artifactType) + return artifactType + } + + suspend fun byteArrayAsFile(byteArray: ByteArray, targetFile: File): File { + // Recreate Folder + targetFile.parentFile.reCreateNBDirs() + targetFile.writeBytes(byteArray).apply { + log.info("CBA file(${targetFile.absolutePath} written successfully") + } + return targetFile + } + + suspend fun filePartAsFile(filePart: FilePart, targetFile: File): File { + // Delete the Directory + targetFile.parentFile.reCreateNBDirs() + return filePart.transferTo(targetFile) + .thenReturn(targetFile) + .awaitSingle() + } + + private suspend fun byteArrayAsArchiveFile(byteArray: ByteArray, archiveDir: String, enhanceDir: String): File { + // Recreate the Base Directories + normalizedFile(archiveDir).reCreateNBDirs() + normalizedFile(enhanceDir).reCreateNBDirs() + val archiveFile = normalizedFile(archiveDir, "cba.zip") + // Copy the File Part to ZIP + return byteArrayAsFile(byteArray, archiveFile) + } + + private suspend fun filePartAsArchiveFile(filePart: FilePart, archiveDir: String, enhanceDir: String): File { + // Recreate the Base Directories + normalizedFile(archiveDir).reCreateNBDirs() + normalizedFile(enhanceDir).reCreateNBDirs() + val archiveFile = normalizedFile(archiveDir, "cba.zip") + // Copy the File Part to ZIP + return filePartAsFile(filePart, archiveFile) + } + + /** copy the [byteArray] zip file to [archiveDir] and then decompress to [enhanceDir] */ + suspend fun copyByteArrayToEnhanceDir(byteArray: ByteArray, archiveDir: String, enhanceDir: String): File { + val archiveFile = byteArrayAsArchiveFile(byteArray, archiveDir, enhanceDir) + val deCompressFileName = normalizedPathName(enhanceDir) + return archiveFile.deCompress(deCompressFileName) + } + + /** copy the [filePart] zip file to [archiveDir] and then decompress to [enhanceDir] */ + suspend fun copyFilePartToEnhanceDir(filePart: FilePart, archiveDir: String, enhanceDir: String): File { + val filePartFile = filePartAsArchiveFile(filePart, archiveDir, enhanceDir) + val deCompressFileName = normalizedPathName(enhanceDir) + return filePartFile.deCompress(deCompressFileName) + } + + /** compress [enhanceDir] to [archiveDir] and return ByteArray */ + suspend fun compressEnhanceDirAndReturnByteArray( + enhanceDir: String, + archiveDir: String, + outputFileName: String = "enhanced-cba.zip" + ): ByteArray { + val compressedFile = normalizedFile(archiveDir, outputFileName) + BluePrintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile) + return compressedFile.readBytes() + } + + /** compress [enhanceDir] to [archiveDir] and return ResponseEntity */ + suspend fun compressEnhanceDirAndReturnFilePart( + enhanceDir: String, + archiveDir: String, + outputFileName: String = "enhanced-cba.zip" + ): + ResponseEntity { + val compressedFile = normalizedFile(archiveDir, outputFileName) + BluePrintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile) + return prepareResourceEntity(compressedFile) + } + + /** convert [file] to ResourceEntity */ + suspend fun prepareResourceEntity(file: File): ResponseEntity { + return prepareResourceEntity(file.name, file.readBytes()) + } + + /** convert [byteArray] to ResourceEntity with [fileName]*/ + fun prepareResourceEntity(fileName: String, byteArray: ByteArray): ResponseEntity { + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType("text/plain")) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"") + .body(ByteArrayResource(byteArray)) + } + + suspend fun cleanEnhancer(archiveLocation: String, enhancementLocation: String) { + deleteNBDir(archiveLocation) + deleteNBDir(enhancementLocation) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtils.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtils.kt deleted file mode 100644 index b10b17025..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtils.kt +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils - -import kotlinx.coroutines.reactive.awaitSingle -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.deCompress -import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.reCreateNBDirs -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintArchiveUtils -import org.springframework.core.io.ByteArrayResource -import org.springframework.core.io.Resource -import org.springframework.http.HttpHeaders -import org.springframework.http.MediaType -import org.springframework.http.ResponseEntity -import org.springframework.http.codec.multipart.FilePart -import java.io.File -import java.nio.file.Paths - -class BlueprintEnhancerUtils { - companion object { - - val log = logger(BlueprintEnhancerUtils) - - fun populateDataTypes( - bluePrintContext: BlueprintContext, - bluePrintRepoService: BlueprintRepoService, - dataTypeName: String - ): DataType { - val dataType = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName) - ?: bluePrintRepoService.getDataType(dataTypeName) - ?: throw BlueprintException("couldn't get DataType($dataTypeName) from repo.") - bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dataType) - return dataType - } - - fun populateRelationshipType( - bluePrintContext: BlueprintContext, - bluePrintRepoService: BlueprintRepoService, - relationshipName: String - ): RelationshipType { - - val relationshipType = bluePrintContext.serviceTemplate.relationshipTypes?.get(relationshipName) - ?: bluePrintRepoService.getRelationshipType(relationshipName) - ?: throw BlueprintException("couldn't get RelationshipType($relationshipName) from repo.") - bluePrintContext.serviceTemplate.relationshipTypes?.put(relationshipName, relationshipType) - return relationshipType - } - - fun populateNodeType( - bluePrintContext: BlueprintContext, - bluePrintRepoService: BlueprintRepoService, - nodeTypeName: String - ): NodeType { - - val nodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(nodeTypeName) - ?: bluePrintRepoService.getNodeType(nodeTypeName) - ?: throw BlueprintException("couldn't get NodeType($nodeTypeName) from repo.") - bluePrintContext.serviceTemplate.nodeTypes?.put(nodeTypeName, nodeType) - return nodeType - } - - fun populateArtifactType( - bluePrintContext: BlueprintContext, - bluePrintRepoService: BlueprintRepoService, - artifactTypeName: String - ): ArtifactType { - - val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName) - ?: bluePrintRepoService.getArtifactType(artifactTypeName) - ?: throw BlueprintException("couldn't get ArtifactType($artifactTypeName) from repo.") - bluePrintContext.serviceTemplate.artifactTypes?.put(artifactTypeName, artifactType) - return artifactType - } - - suspend fun byteArrayAsFile(byteArray: ByteArray, targetFile: File): File { - // Recreate Folder - targetFile.parentFile.reCreateNBDirs() - targetFile.writeBytes(byteArray).apply { - log.info("CBA file(${targetFile.absolutePath} written successfully") - } - return targetFile - } - - suspend fun filePartAsFile(filePart: FilePart, targetFile: File): File { - // Delete the Directory - targetFile.parentFile.reCreateNBDirs() - return filePart.transferTo(targetFile) - .thenReturn(targetFile) - .awaitSingle() - } - - private suspend fun byteArrayAsArchiveFile(byteArray: ByteArray, archiveDir: String, enhanceDir: String): File { - // Recreate the Base Directories - normalizedFile(archiveDir).reCreateNBDirs() - normalizedFile(enhanceDir).reCreateNBDirs() - val archiveFile = normalizedFile(archiveDir, "cba.zip") - // Copy the File Part to ZIP - return byteArrayAsFile(byteArray, archiveFile) - } - - private suspend fun filePartAsArchiveFile(filePart: FilePart, archiveDir: String, enhanceDir: String): File { - // Recreate the Base Directories - normalizedFile(archiveDir).reCreateNBDirs() - normalizedFile(enhanceDir).reCreateNBDirs() - val archiveFile = normalizedFile(archiveDir, "cba.zip") - // Copy the File Part to ZIP - return filePartAsFile(filePart, archiveFile) - } - - /** copy the [byteArray] zip file to [archiveDir] and then decompress to [enhanceDir] */ - suspend fun copyByteArrayToEnhanceDir(byteArray: ByteArray, archiveDir: String, enhanceDir: String): File { - val archiveFile = byteArrayAsArchiveFile(byteArray, archiveDir, enhanceDir) - val deCompressFileName = normalizedPathName(enhanceDir) - return archiveFile.deCompress(deCompressFileName) - } - - /** copy the [filePart] zip file to [archiveDir] and then decompress to [enhanceDir] */ - suspend fun copyFilePartToEnhanceDir(filePart: FilePart, archiveDir: String, enhanceDir: String): File { - val filePartFile = filePartAsArchiveFile(filePart, archiveDir, enhanceDir) - val deCompressFileName = normalizedPathName(enhanceDir) - return filePartFile.deCompress(deCompressFileName) - } - - /** compress [enhanceDir] to [archiveDir] and return ByteArray */ - suspend fun compressEnhanceDirAndReturnByteArray( - enhanceDir: String, - archiveDir: String, - outputFileName: String = "enhanced-cba.zip" - ): ByteArray { - val compressedFile = normalizedFile(archiveDir, outputFileName) - BlueprintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile) - return compressedFile.readBytes() - } - - /** compress [enhanceDir] to [archiveDir] and return ResponseEntity */ - suspend fun compressEnhanceDirAndReturnFilePart( - enhanceDir: String, - archiveDir: String, - outputFileName: String = "enhanced-cba.zip" - ): - ResponseEntity { - val compressedFile = normalizedFile(archiveDir, outputFileName) - BlueprintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile) - return prepareResourceEntity(compressedFile) - } - - /** convert [file] to ResourceEntity */ - suspend fun prepareResourceEntity(file: File): ResponseEntity { - return prepareResourceEntity(file.name, file.readBytes()) - } - - /** convert [byteArray] to ResourceEntity with [fileName]*/ - fun prepareResourceEntity(fileName: String, byteArray: ByteArray): ResponseEntity { - return ResponseEntity.ok() - .contentType(MediaType.parseMediaType("text/plain")) - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"") - .body(ByteArrayResource(byteArray)) - } - - suspend fun cleanEnhancer(archiveLocation: String, enhancementLocation: String) { - deleteNBDir(archiveLocation) - deleteNBDir(enhancementLocation) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt index 78f9e1688..08de136d8 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt @@ -18,9 +18,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils import com.fasterxml.jackson.databind.JsonNode import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType @@ -41,25 +41,25 @@ class ModelTypeValidator { fun validateModelTypeDefinition(definitionType: String, definitionContent: JsonNode): Boolean { when (definitionType) { - BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE -> { + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE -> { JacksonUtils.readValue(definitionContent, DataType::class.java) - ?: throw BlueprintException("Model type definition is not DataType valid content $definitionContent") + ?: throw BluePrintException("Model type definition is not DataType valid content $definitionContent") } - BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE -> { + BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE -> { JacksonUtils.readValue(definitionContent, NodeType::class.java) - ?: throw BlueprintException("Model type definition is not NodeType valid content $definitionContent") + ?: throw BluePrintException("Model type definition is not NodeType valid content $definitionContent") } - BlueprintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE -> { + BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE -> { JacksonUtils.readValue(definitionContent, ArtifactType::class.java) - ?: throw BlueprintException("Model type definition is not ArtifactType valid content $definitionContent") + ?: throw BluePrintException("Model type definition is not ArtifactType valid content $definitionContent") } - BlueprintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE -> { + BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE -> { JacksonUtils.readValue(definitionContent, CapabilityDefinition::class.java) - ?: throw BlueprintException("Model type definition is not CapabilityDefinition valid content $definitionContent") + ?: throw BluePrintException("Model type definition is not CapabilityDefinition valid content $definitionContent") } - BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE -> { + BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE -> { JacksonUtils.readValue(definitionContent, RelationshipType::class.java) - ?: throw BlueprintException("Model type definition is not RelationshipType valid content $definitionContent") + ?: throw BluePrintException("Model type definition is not RelationshipType valid content $definitionContent") } } return true @@ -74,7 +74,7 @@ class ModelTypeValidator { fun validateModelType(modelType: ModelType?): Boolean { checkNotNull(modelType) { "Model Type Information is missing." } - val validRootTypes = BlueprintTypes.validModelTypes() + val validRootTypes = BluePrintTypes.validModelTypes() check(validRootTypes.contains(modelType.definitionType)) { "Not Valid Model Root Type(${modelType.definitionType}), It should be $validRootTypes" diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt new file mode 100644 index 000000000..a2f208367 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt @@ -0,0 +1,252 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api + +import com.google.protobuf.ByteString +import io.grpc.testing.GrpcServerRule +import kotlinx.coroutines.runBlocking +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.TokenAuthGrpcClientService +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.compress +import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintBootstrapInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintDownloadInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintRemoveInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction +import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk +import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction +import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +@RunWith(SpringRunner::class) +@ContextConfiguration( + classes = [DesignerApiTestConfiguration::class, ErrorCatalogTestConfiguration::class] +) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class BluePrintManagementGRPCHandlerTest { + + @get:Rule + val grpcServerRule = GrpcServerRule().directExecutor() + + @Autowired + lateinit var bluePrintManagementGRPCHandler: BluePrintManagementGRPCHandler + + @BeforeTest + fun init() { + + deleteDir("target", "blueprints") + + // Create sample CBA zip + normalizedFile("./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") + .compress(normalizedFile("./target/blueprints/generated-cba.zip")) + + // Create a server, add service, start, and register for automatic graceful shutdown. + grpcServerRule.serviceRegistry.addService(bluePrintManagementGRPCHandler) + } + + @AfterTest + fun cleanDir() { + deleteDir("target", "blueprints") + } + + @Test + fun testBootstrap() { + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) + val id = "123_Bootstrap" + val req = createBootstrapInputRequest(id) + val bootstrapOutput = blockingStub.bootstrapBlueprint(req) + assertEquals(200, bootstrapOutput.status.code) + assertTrue( + bootstrapOutput.status.message!!.contentEquals(BluePrintConstants.STATUS_SUCCESS), + "failed to get success status" + ) + assertEquals(EventType.EVENT_COMPONENT_EXECUTED, bootstrapOutput.status.eventType) + assertEquals(id, bootstrapOutput.commonHeader.requestId) + } + + @Test + fun `test upload and download blueprint`() { + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) + val id = "123_upload" + val req = createUploadInputRequest(id, UploadAction.PUBLISH.toString()) + val output = blockingStub.uploadBlueprint(req) + + assertEquals(200, output.status.code) + assertTrue( + output.status.message!!.contentEquals(BluePrintConstants.STATUS_SUCCESS), + "failed to get success status" + ) + assertEquals(EventType.EVENT_COMPONENT_EXECUTED, output.status.eventType) + assertEquals(id, output.commonHeader.requestId) + + val downloadId = "123_download" + val downloadReq = createDownloadInputRequest(downloadId, DownloadAction.SEARCH.toString()) + + val downloadOutput = blockingStub.downloadBlueprint(downloadReq) + assertEquals(200, downloadOutput.status.code) + assertTrue( + downloadOutput.status.message!!.contentEquals(BluePrintConstants.STATUS_SUCCESS), + "failed to get success status" + ) + assertEquals(EventType.EVENT_COMPONENT_EXECUTED, downloadOutput.status.eventType) + assertNotNull(downloadOutput.fileChunk?.chunk, "failed to get cba file chunks") + assertEquals(downloadId, downloadOutput.commonHeader.requestId) + } + + @Test + fun `test delete blueprint`() { + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) + val id = "123_delete" + val req = createUploadInputRequest(id, UploadAction.DRAFT.toString()) + + var output = blockingStub.uploadBlueprint(req) + assertEquals(200, output.status.code) + assertTrue( + output.status.message!!.contentEquals(BluePrintConstants.STATUS_SUCCESS), + "failed to get success status" + ) + assertEquals(id, output.commonHeader.requestId) + assertEquals(EventType.EVENT_COMPONENT_EXECUTED, output.status.eventType) + + val removeReq = createRemoveInputRequest(id) + output = blockingStub.removeBlueprint(removeReq) + assertEquals(200, output.status.code) + } + + /** This is Integration test sample, Do not enable this test case in server build, this is for local desktop testing*/ + private fun integrationTestGrpcManagement() { + runBlocking { + val tokenAuthGrpcClientProperties = TokenAuthGrpcClientProperties().apply { + host = "127.0.0.1" + port = 9111 + type = GRPCLibConstants.TYPE_TOKEN_AUTH + token = "Basic Y2NzZGthcHBzOmNjc2RrYXBwcw==" + } + val basicAuthGrpcClientService = TokenAuthGrpcClientService(tokenAuthGrpcClientProperties) + val channel = basicAuthGrpcClientService.channel() + + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(channel) + + val bluePrintUploadInput = createUploadInputRequest("12345", UploadAction.DRAFT.toString()) + + val bluePrintManagementOutput = blockingStub.uploadBlueprint(bluePrintUploadInput) + assertNotNull(bluePrintManagementOutput, "failed to get response") + } + } + + private fun createBootstrapInputRequest(id: String): BluePrintBootstrapInput { + val commonHeader = CommonHeader + .newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId(id) + .setSubRequestId("1234-56").build() + + return BluePrintBootstrapInput.newBuilder() + .setCommonHeader(commonHeader) + .setLoadModelType(false) + .setLoadResourceDictionary(false) + .setLoadCBA(false) + .build() + } + + private fun createUploadInputRequest(id: String, action: String): BluePrintUploadInput { + val file = normalizedFile("./target/blueprints/generated-cba.zip") + assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") + + val commonHeader = CommonHeader + .newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId(id) + .setSubRequestId("1234-56").build() + + val actionIdentifier = ActionIdentifiers.newBuilder() + .setActionName(action) + .setBlueprintName("sample") + .setBlueprintVersion("1.0.0") + .build() + + val fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(file.inputStream().readBytes())) + .build() + + return BluePrintUploadInput.newBuilder() + .setCommonHeader(commonHeader) + .setActionIdentifiers(actionIdentifier) + .setFileChunk(fileChunk) + .build() + } + + private fun createDownloadInputRequest(id: String, action: String): BluePrintDownloadInput { + val commonHeader = CommonHeader + .newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId(id) + .setSubRequestId("1234-56").build() + + return BluePrintDownloadInput.newBuilder() + .setCommonHeader(commonHeader) + .setActionIdentifiers( + ActionIdentifiers.newBuilder() + .setBlueprintName("baseconfiguration") + .setBlueprintVersion("1.0.0") + .setActionName(action).build() + ) + .build() + } + + private fun createRemoveInputRequest(id: String): BluePrintRemoveInput { + val commonHeader = CommonHeader + .newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId(id) + .setSubRequestId("1234-56").build() + + return BluePrintRemoveInput.newBuilder() + .setCommonHeader(commonHeader) + .setActionIdentifiers( + ActionIdentifiers.newBuilder() + .setBlueprintName("sample") + .setBlueprintVersion("1.0.0") + .setActionName(RemoveAction.DEFAULT.toString()).build() + ) + .build() + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandlerTest.kt deleted file mode 100644 index ed60f721a..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandlerTest.kt +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api - -import com.google.protobuf.ByteString -import io.grpc.testing.GrpcServerRule -import kotlinx.coroutines.runBlocking -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.TokenAuthGrpcClientService -import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.compress -import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintBootstrapInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintDownloadInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementServiceGrpc -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintRemoveInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintUploadInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction -import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk -import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction -import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -@RunWith(SpringRunner::class) -@ContextConfiguration( - classes = [DesignerApiTestConfiguration::class, ErrorCatalogTestConfiguration::class] -) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -class BlueprintManagementGRPCHandlerTest { - - @get:Rule - val grpcServerRule = GrpcServerRule().directExecutor() - - @Autowired - lateinit var bluePrintManagementGRPCHandler: BlueprintManagementGRPCHandler - - @BeforeTest - fun init() { - - deleteDir("target", "blueprints") - - // Create sample CBA zip - normalizedFile("./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") - .compress(normalizedFile("./target/blueprints/generated-cba.zip")) - - // Create a server, add service, start, and register for automatic graceful shutdown. - grpcServerRule.serviceRegistry.addService(bluePrintManagementGRPCHandler) - } - - @AfterTest - fun cleanDir() { - deleteDir("target", "blueprints") - } - - @Test - fun testBootstrap() { - val blockingStub = BlueprintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) - val id = "123_Bootstrap" - val req = createBootstrapInputRequest(id) - val bootstrapOutput = blockingStub.bootstrapBlueprint(req) - assertEquals(200, bootstrapOutput.status.code) - assertTrue( - bootstrapOutput.status.message!!.contentEquals(BlueprintConstants.STATUS_SUCCESS), - "failed to get success status" - ) - assertEquals(EventType.EVENT_COMPONENT_EXECUTED, bootstrapOutput.status.eventType) - assertEquals(id, bootstrapOutput.commonHeader.requestId) - } - - @Test - fun `test upload and download blueprint`() { - val blockingStub = BlueprintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) - val id = "123_upload" - val req = createUploadInputRequest(id, UploadAction.PUBLISH.toString()) - val output = blockingStub.uploadBlueprint(req) - - assertEquals(200, output.status.code) - assertTrue( - output.status.message!!.contentEquals(BlueprintConstants.STATUS_SUCCESS), - "failed to get success status" - ) - assertEquals(EventType.EVENT_COMPONENT_EXECUTED, output.status.eventType) - assertEquals(id, output.commonHeader.requestId) - - val downloadId = "123_download" - val downloadReq = createDownloadInputRequest(downloadId, DownloadAction.SEARCH.toString()) - - val downloadOutput = blockingStub.downloadBlueprint(downloadReq) - assertEquals(200, downloadOutput.status.code) - assertTrue( - downloadOutput.status.message!!.contentEquals(BlueprintConstants.STATUS_SUCCESS), - "failed to get success status" - ) - assertEquals(EventType.EVENT_COMPONENT_EXECUTED, downloadOutput.status.eventType) - assertNotNull(downloadOutput.fileChunk?.chunk, "failed to get cba file chunks") - assertEquals(downloadId, downloadOutput.commonHeader.requestId) - } - - @Test - fun `test delete blueprint`() { - val blockingStub = BlueprintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) - val id = "123_delete" - val req = createUploadInputRequest(id, UploadAction.DRAFT.toString()) - - var output = blockingStub.uploadBlueprint(req) - assertEquals(200, output.status.code) - assertTrue( - output.status.message!!.contentEquals(BlueprintConstants.STATUS_SUCCESS), - "failed to get success status" - ) - assertEquals(id, output.commonHeader.requestId) - assertEquals(EventType.EVENT_COMPONENT_EXECUTED, output.status.eventType) - - val removeReq = createRemoveInputRequest(id) - output = blockingStub.removeBlueprint(removeReq) - assertEquals(200, output.status.code) - } - - /** This is Integration test sample, Do not enable this test case in server build, this is for local desktop testing*/ - private fun integrationTestGrpcManagement() { - runBlocking { - val tokenAuthGrpcClientProperties = TokenAuthGrpcClientProperties().apply { - host = "127.0.0.1" - port = 9111 - type = GRPCLibConstants.TYPE_TOKEN_AUTH - token = "Basic Y2NzZGthcHBzOmNjc2RrYXBwcw==" - } - val basicAuthGrpcClientService = TokenAuthGrpcClientService(tokenAuthGrpcClientProperties) - val channel = basicAuthGrpcClientService.channel() - - val blockingStub = BlueprintManagementServiceGrpc.newBlockingStub(channel) - - val bluePrintUploadInput = createUploadInputRequest("12345", UploadAction.DRAFT.toString()) - - val bluePrintManagementOutput = blockingStub.uploadBlueprint(bluePrintUploadInput) - assertNotNull(bluePrintManagementOutput, "failed to get response") - } - } - - private fun createBootstrapInputRequest(id: String): BlueprintBootstrapInput { - val commonHeader = CommonHeader - .newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId(id) - .setSubRequestId("1234-56").build() - - return BlueprintBootstrapInput.newBuilder() - .setCommonHeader(commonHeader) - .setLoadModelType(false) - .setLoadResourceDictionary(false) - .setLoadCBA(false) - .build() - } - - private fun createUploadInputRequest(id: String, action: String): BlueprintUploadInput { - val file = normalizedFile("./target/blueprints/generated-cba.zip") - assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") - - val commonHeader = CommonHeader - .newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId(id) - .setSubRequestId("1234-56").build() - - val actionIdentifier = ActionIdentifiers.newBuilder() - .setActionName(action) - .setBlueprintName("sample") - .setBlueprintVersion("1.0.0") - .build() - - val fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(file.inputStream().readBytes())) - .build() - - return BlueprintUploadInput.newBuilder() - .setCommonHeader(commonHeader) - .setActionIdentifiers(actionIdentifier) - .setFileChunk(fileChunk) - .build() - } - - private fun createDownloadInputRequest(id: String, action: String): BlueprintDownloadInput { - val commonHeader = CommonHeader - .newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId(id) - .setSubRequestId("1234-56").build() - - return BlueprintDownloadInput.newBuilder() - .setCommonHeader(commonHeader) - .setActionIdentifiers( - ActionIdentifiers.newBuilder() - .setBlueprintName("baseconfiguration") - .setBlueprintVersion("1.0.0") - .setActionName(action).build() - ) - .build() - } - - private fun createRemoveInputRequest(id: String): BlueprintRemoveInput { - val commonHeader = CommonHeader - .newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId(id) - .setSubRequestId("1234-56").build() - - return BlueprintRemoveInput.newBuilder() - .setCommonHeader(commonHeader) - .setActionIdentifiers( - ActionIdentifiers.newBuilder() - .setBlueprintName("sample") - .setBlueprintVersion("1.0.0") - .setActionName(RemoveAction.DEFAULT.toString()).build() - ) - .build() - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt index 92f369b01..a42ac05e7 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt @@ -28,7 +28,7 @@ import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch import org.onap.ccsdk.cds.controllerblueprints.core.compress -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile @@ -79,7 +79,7 @@ class BlueprintModelControllerTest { @Autowired lateinit var webTestClient: WebTestClient - private var bluePrintLoadConfiguration: BlueprintLoadConfiguration? = null + private var bluePrintLoadConfiguration: BluePrintLoadConfiguration? = null private val blueprintDir = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" private var zipBlueprintFileName: String? = null @@ -90,7 +90,7 @@ class BlueprintModelControllerTest { fun setUp() { assertNotNull(webTestClient, " Failed to create WebTestClient") - bluePrintLoadConfiguration = BlueprintLoadConfiguration().apply { + bluePrintLoadConfiguration = BluePrintLoadConfiguration().apply { blueprintArchivePath = "./target/blueprints/archive" blueprintWorkingPath = "./target/blueprints/work" blueprintDeployPath = "./target/blueprints/deploy" @@ -113,7 +113,7 @@ class BlueprintModelControllerTest { } @Test - fun test01_saveBlueprint() { + fun test01_saveBluePrint() { bp = runBlocking { val body = MultipartBodyBuilder().apply { part( @@ -146,7 +146,7 @@ class BlueprintModelControllerTest { @Test @Throws(JSONException::class) - fun test02_getBlueprintByNameAndVersion() { + fun test02_getBluePrintByNameAndVersion() { webTestClient( HttpMethod.GET, null, "/api/v1/blueprint-model/by-name/${bp!!.artifactName}/version/${bp!!.artifactVersion}", @@ -172,7 +172,7 @@ class BlueprintModelControllerTest { @Test @Throws(JSONException::class) - fun test05_downloadBlueprint() { + fun test05_downloadBluePrint() { webTestClient( HttpMethod.GET, null, "/api/v1/blueprint-model/download/${bp!!.id}", @@ -237,7 +237,7 @@ class BlueprintModelControllerTest { } @Test - fun test10_deleteBlueprint() { + fun test10_deleteBluePrint() { // webTestClient.delete().uri("/api/v1/blueprint-model/${bp!!.id}") // .header("Authorization", "Basic " + Base64Utils // .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8))) diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt index bcce13e4c..8226aaad0 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt @@ -23,7 +23,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired @@ -56,15 +56,15 @@ class ModelTypeControllerTest { val content = JacksonUtils.getClassPathFileContent("model_type/data_type/datatype-property.json") var modelType = ModelType() - modelType.definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE - modelType.derivedFrom = BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + modelType.definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + modelType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT modelType.description = "Definition for Sample Datatype " modelType.definition = JacksonUtils.jsonNode(content) modelType.modelName = modelName modelType.version = "1.0.0" modelType.tags = ( - "test-datatype ," + BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + - BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + "test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE ) modelType.updatedBy = "xxxxxx@xxx.com" modelType = modelTypeController.saveModelType(modelType) @@ -108,7 +108,7 @@ class ModelTypeControllerTest { Assert.assertNotNull("Failed to get Id for api call getModelByName ", dbModelType!!.modelName) val dbDatatypeModelTypes = - modelTypeController.getModelTypeByDefinitionType(BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) + modelTypeController.getModelTypeByDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) Assert.assertNotNull("Failed to find getModelTypeByDefinitionType by tags", dbDatatypeModelTypes) Assert.assertTrue("Failed to find getModelTypeByDefinitionType by count", dbDatatypeModelTypes.isNotEmpty()) } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt index 7fcea4dcc..6808a2717 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration import org.springframework.context.annotation.Bean @@ -29,7 +29,7 @@ import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration -@Import(BlueprintDBLibConfiguration::class) +@Import(BluePrintDBLibConfiguration::class) @EnableJpaRepositories( basePackages = [ "org.onap.ccsdk.cds.blueprintsprocessor.db.primary", diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt new file mode 100644 index 000000000..a866dcad3 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt @@ -0,0 +1,114 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import kotlinx.coroutines.runBlocking +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.ModelTypeLoadService +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.ResourceDictionaryLoadService +import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner + +@RunWith(SpringRunner::class) +@ContextConfiguration( + classes = [DesignerApiTestConfiguration::class] +) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class BluePrintEnhancerServiceImplTest { + + @Autowired + lateinit var modelTypeLoadService: ModelTypeLoadService + + @Autowired + lateinit var resourceDictionaryLoadService: ResourceDictionaryLoadService + + @Autowired + lateinit var bluePrintEnhancerService: BluePrintEnhancerService + + @Autowired + lateinit var bluePrintValidatorService: BluePrintValidatorService + + @Test + @Throws(Exception::class) + fun testEnhancementAndValidation() { + + runBlocking { + modelTypeLoadService.loadPathModelType("./../../../../../components/model-catalog/definition-type/starter-type") + + val dictPaths: MutableList = arrayListOf() + dictPaths.add("./../../../../../components/model-catalog/resource-dictionary/starter-dictionary") + dictPaths.add("./../../../../../components/model-catalog/resource-dictionary/test-dictionary") + resourceDictionaryLoadService.loadPathsResourceDictionary(dictPaths) + + testBaseConfigEnhancementAndValidation() + testGoldenEnhancementAndValidation() + testRemoteScriptsEnhancementAndValidation() + testCapabilityCliEnhancementAndValidation() + } + } + + private fun testBaseConfigEnhancementAndValidation() { + val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" + testComponentInvokeEnhancementAndValidation(basePath, "base-enhance") + } + + private fun testGoldenEnhancementAndValidation() { + val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/golden" + testComponentInvokeEnhancementAndValidation(basePath, "golden-enhance") + } + + private fun testRemoteScriptsEnhancementAndValidation() { + val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts" + testComponentInvokeEnhancementAndValidation(basePath, "remote_scripts-enhance") + } + + private fun testCapabilityCliEnhancementAndValidation() { + val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/capability_cli" + testComponentInvokeEnhancementAndValidation(basePath, "capability_cli-enhance") + } + + private fun testComponentInvokeEnhancementAndValidation(basePath: String, targetDirName: String) { + runBlocking { + val targetPath = normalizedPathName("target/blueprints/enrichment", targetDirName) + + deleteDir(targetPath) + + val bluePrintContext = bluePrintEnhancerService.enhance(basePath, targetPath) + Assert.assertNotNull("failed to get blueprintContext ", bluePrintContext) + + // Validate the Generated BluePrints + val valid = bluePrintValidatorService.validateBluePrints(targetPath) + Assert.assertTrue("blueprint($basePath) validation failed ", valid) + + // Enable this to get the enhanced zip file + // val compressFile = normalizedFile("target/blueprints/enrichment", "$targetDirName.zip") + // normalizedFile(targetPath).compress(compressFile) + + deleteDir(targetPath) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImplTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImplTest.kt deleted file mode 100644 index 8bdfbbb22..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImplTest.kt +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import kotlinx.coroutines.runBlocking -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.ModelTypeLoadService -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.ResourceDictionaryLoadService -import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner - -@RunWith(SpringRunner::class) -@ContextConfiguration( - classes = [DesignerApiTestConfiguration::class] -) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -class BlueprintEnhancerServiceImplTest { - - @Autowired - lateinit var modelTypeLoadService: ModelTypeLoadService - - @Autowired - lateinit var resourceDictionaryLoadService: ResourceDictionaryLoadService - - @Autowired - lateinit var bluePrintEnhancerService: BlueprintEnhancerService - - @Autowired - lateinit var bluePrintValidatorService: BlueprintValidatorService - - @Test - @Throws(Exception::class) - fun testEnhancementAndValidation() { - - runBlocking { - modelTypeLoadService.loadPathModelType("./../../../../../components/model-catalog/definition-type/starter-type") - - val dictPaths: MutableList = arrayListOf() - dictPaths.add("./../../../../../components/model-catalog/resource-dictionary/starter-dictionary") - dictPaths.add("./../../../../../components/model-catalog/resource-dictionary/test-dictionary") - resourceDictionaryLoadService.loadPathsResourceDictionary(dictPaths) - - testBaseConfigEnhancementAndValidation() - testGoldenEnhancementAndValidation() - testRemoteScriptsEnhancementAndValidation() - testCapabilityCliEnhancementAndValidation() - } - } - - private fun testBaseConfigEnhancementAndValidation() { - val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" - testComponentInvokeEnhancementAndValidation(basePath, "base-enhance") - } - - private fun testGoldenEnhancementAndValidation() { - val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/golden" - testComponentInvokeEnhancementAndValidation(basePath, "golden-enhance") - } - - private fun testRemoteScriptsEnhancementAndValidation() { - val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts" - testComponentInvokeEnhancementAndValidation(basePath, "remote_scripts-enhance") - } - - private fun testCapabilityCliEnhancementAndValidation() { - val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/capability_cli" - testComponentInvokeEnhancementAndValidation(basePath, "capability_cli-enhance") - } - - private fun testComponentInvokeEnhancementAndValidation(basePath: String, targetDirName: String) { - runBlocking { - val targetPath = normalizedPathName("target/blueprints/enrichment", targetDirName) - - deleteDir(targetPath) - - val bluePrintContext = bluePrintEnhancerService.enhance(basePath, targetPath) - Assert.assertNotNull("failed to get blueprintContext ", bluePrintContext) - - // Validate the Generated Blueprints - val valid = bluePrintValidatorService.validateBlueprints(targetPath) - Assert.assertTrue("blueprint($basePath) validation failed ", valid) - - // Enable this to get the enhanced zip file - // val compressFile = normalizedFile("target/blueprints/enrichment", "$targetDirName.zip") - // normalizedFile(targetPath).compress(compressFile) - - deleteDir(targetPath) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt index 3112bfb66..8ee2eb3a2 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt @@ -24,7 +24,7 @@ import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired @@ -57,15 +57,15 @@ class ModelTypeServiceTest { val content = JacksonUtils.getClassPathFileContent("model_type/data_type/datatype-property.json") var modelType = ModelType() - modelType.definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE - modelType.derivedFrom = BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + modelType.definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + modelType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT modelType.description = "Definition for Sample Datatype " modelType.definition = JacksonUtils.jsonNode(content) modelType.modelName = modelName modelType.version = "1.0.0" modelType.tags = ( - "test-datatype ," + BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + - BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + "test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE ) modelType.updatedBy = "xxxxxx@xxx.com" modelType = modelTypeHandler!!.saveModel(modelType) @@ -110,11 +110,11 @@ class ModelTypeServiceTest { Assert.assertNotNull("Failed to get response for api call getModelByName ", dbModelType) Assert.assertNotNull("Failed to get Id for api call getModelByName ", dbModelType!!.modelName) - val dbDatatypeModelTypes = modelTypeHandler.getModelTypeByDefinitionType(BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) + val dbDatatypeModelTypes = modelTypeHandler.getModelTypeByDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) Assert.assertNotNull("Failed to find getModelTypeByDefinitionType by tags", dbDatatypeModelTypes) Assert.assertTrue("Failed to find getModelTypeByDefinitionType by count", dbDatatypeModelTypes.size > 0) - val dbModelTypeByDerivedFroms = modelTypeHandler.getModelTypeByDerivedFrom(BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT) + val dbModelTypeByDerivedFroms = modelTypeHandler.getModelTypeByDerivedFrom(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT) Assert.assertNotNull("Failed to find getModelTypeByDerivedFrom by tags", dbModelTypeByDerivedFroms) Assert.assertTrue("Failed to find getModelTypeByDerivedFrom by count", dbModelTypeByDerivedFroms.size > 0) } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt index 9bc8c6291..ca85ed22f 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt @@ -23,7 +23,7 @@ import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired @@ -59,15 +59,15 @@ class ModelTypeReactRepositoryTest { val content = normalizedFile("./src/test/resources/model_type/data_type/datatype-property.json") .readText(Charset.defaultCharset()) val modelType = ModelType() - modelType.definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE - modelType.derivedFrom = BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + modelType.definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + modelType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT modelType.description = "Definition for Sample Datatype " modelType.definition = JacksonUtils.jsonNode(content) modelType.modelName = modelName modelType.version = "1.0.0" modelType.tags = ( - "test-datatype ," + BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + - BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + "test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE ) modelType.updatedBy = "xxxxxx@xxx.com" @@ -81,11 +81,11 @@ class ModelTypeReactRepositoryTest { Assert.assertNotNull("Failed to findByModelName ", dbFindByModelName) val dbFindByDefinitionType = - modelTypeReactRepository.findByDefinitionType(BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE).collectList().block() + modelTypeReactRepository.findByDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE).collectList().block() Assert.assertNotNull("Failed to findByDefinitionType ", dbFindByDefinitionType) Assert.assertTrue("Failed to findByDefinitionType count", dbFindByDefinitionType!!.size > 0) - val dbFindByDerivedFrom = modelTypeReactRepository.findByDerivedFrom(BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT).collectList().block() + val dbFindByDerivedFrom = modelTypeReactRepository.findByDerivedFrom(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT).collectList().block() Assert.assertNotNull("Failed to find findByDerivedFrom", dbFindByDerivedFrom) Assert.assertTrue("Failed to find findByDerivedFrom by count", dbFindByDerivedFrom!!.size > 0) @@ -94,12 +94,12 @@ class ModelTypeReactRepositoryTest { Assert.assertTrue("Failed to findByModelNameIn by count", dbFindByModelNameIn!!.size > 0) val dbFindByDefinitionTypeIn = - modelTypeReactRepository.findByDefinitionTypeIn(Arrays.asList(BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)).collectList().block() + modelTypeReactRepository.findByDefinitionTypeIn(Arrays.asList(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)).collectList().block() Assert.assertNotNull("Failed to findByDefinitionTypeIn", dbFindByDefinitionTypeIn) Assert.assertTrue("Failed to findByDefinitionTypeIn by count", dbFindByDefinitionTypeIn!!.size > 0) val dbFindByDerivedFromIn = - modelTypeReactRepository.findByDerivedFromIn(Arrays.asList(BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT)).collectList().block() + modelTypeReactRepository.findByDerivedFromIn(Arrays.asList(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT)).collectList().block() Assert.assertNotNull("Failed to find findByDerivedFromIn", dbFindByDerivedFromIn) Assert.assertTrue("Failed to find findByDerivedFromIn by count", dbFindByDerivedFromIn!!.size > 0) } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt new file mode 100644 index 000000000..c644aeedd --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt @@ -0,0 +1,68 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils + +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.mock.MockFilePart +import org.onap.ccsdk.cds.controllerblueprints.core.compress +import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.reCreateDirs +import java.util.UUID +import kotlin.test.assertTrue + +class BluePrintEnhancerUtilsTest { + + private val blueprintDir = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" + private val blueprintArchivePath: String = "./target/blueprints/archive" + private val blueprintEnrichmentPath: String = "./target/blueprints/enrichment" + private var zipBlueprintFileName = normalizedPathName(blueprintArchivePath, "test.zip") + + @Before + fun setUp() { + val archiveDir = normalizedFile(blueprintArchivePath).reCreateDirs() + assertTrue(archiveDir.exists(), "failed to create archiveDir(${archiveDir.absolutePath}") + val enhancerDir = normalizedFile(blueprintEnrichmentPath).reCreateDirs() + assertTrue(enhancerDir.exists(), "failed to create enhancerDir(${enhancerDir.absolutePath}") + val blueprintFile = normalizedFile(blueprintDir) + val testZipFile = blueprintFile.compress(zipBlueprintFileName) + assertTrue(testZipFile.exists(), "Failed to create blueprint test zip(${testZipFile.absolutePath}") + } + + @After + fun tearDown() { + deleteDir(blueprintArchivePath) + deleteDir(blueprintEnrichmentPath) + } + + @Test + fun testFilePartCompressionNDeCompression() { + val filePart = MockFilePart(zipBlueprintFileName) + + runBlocking { + val enhanceId = UUID.randomUUID().toString() + val blueprintArchiveLocation = normalizedPathName(blueprintArchivePath, enhanceId) + val blueprintEnrichmentLocation = normalizedPathName(blueprintEnrichmentPath, enhanceId) + BluePrintEnhancerUtils.copyFilePartToEnhanceDir(filePart, blueprintArchiveLocation, blueprintEnrichmentLocation) + BluePrintEnhancerUtils.compressEnhanceDirAndReturnFilePart(blueprintEnrichmentLocation, blueprintArchiveLocation) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtilsTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtilsTest.kt deleted file mode 100644 index 461af84c4..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtilsTest.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils - -import kotlinx.coroutines.runBlocking -import org.junit.After -import org.junit.Before -import org.junit.Test -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.mock.MockFilePart -import org.onap.ccsdk.cds.controllerblueprints.core.compress -import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.reCreateDirs -import java.util.UUID -import kotlin.test.assertTrue - -class BlueprintEnhancerUtilsTest { - - private val blueprintDir = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" - private val blueprintArchivePath: String = "./target/blueprints/archive" - private val blueprintEnrichmentPath: String = "./target/blueprints/enrichment" - private var zipBlueprintFileName = normalizedPathName(blueprintArchivePath, "test.zip") - - @Before - fun setUp() { - val archiveDir = normalizedFile(blueprintArchivePath).reCreateDirs() - assertTrue(archiveDir.exists(), "failed to create archiveDir(${archiveDir.absolutePath}") - val enhancerDir = normalizedFile(blueprintEnrichmentPath).reCreateDirs() - assertTrue(enhancerDir.exists(), "failed to create enhancerDir(${enhancerDir.absolutePath}") - val blueprintFile = normalizedFile(blueprintDir) - val testZipFile = blueprintFile.compress(zipBlueprintFileName) - assertTrue(testZipFile.exists(), "Failed to create blueprint test zip(${testZipFile.absolutePath}") - } - - @After - fun tearDown() { - deleteDir(blueprintArchivePath) - deleteDir(blueprintEnrichmentPath) - } - - @Test - fun testFilePartCompressionNDeCompression() { - val filePart = MockFilePart(zipBlueprintFileName) - - runBlocking { - val enhanceId = UUID.randomUUID().toString() - val blueprintArchiveLocation = normalizedPathName(blueprintArchivePath, enhanceId) - val blueprintEnrichmentLocation = normalizedPathName(blueprintEnrichmentPath, enhanceId) - BlueprintEnhancerUtils.copyFilePartToEnhanceDir(filePart, blueprintArchiveLocation, blueprintEnrichmentLocation) - BlueprintEnhancerUtils.compressEnhanceDirAndReturnFilePart(blueprintEnrichmentLocation, blueprintArchiveLocation) - } - } -} -- cgit 1.2.3-korg