Enabling Code Formatter
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / inbounds / designer-api / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / designer / api / BluePrintManagementGRPCHandler.kt
index 5f2a6df..54f8dbc 100644 (file)
@@ -24,37 +24,57 @@ 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.*
+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")
+// TODO("Convert to coroutines handler")
 @Service
-open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: BluePrintModelHandler)
-    : BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() {
+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<BluePrintManagementOutput>) {
+    override fun uploadBlueprint(
+        request: BluePrintUploadInput,
+        responseObserver: StreamObserver<BluePrintManagementOutput>
+    ) {
 
         runBlocking {
-            //TODO("catch if request id is missing")
+            // TODO("catch if request id is missing")
             log.info("request(${request.commonHeader.requestId})")
             try {
                 /** Get the file byte array */
                 val byteArray = request.fileChunk.chunk.toByteArray()
+
                 /** Get the Upload Action */
                 val uploadAction = request.actionIdentifiers?.actionName.emptyTONull()
-                        ?: UploadAction.DRAFT.toString()
+                    ?: UploadAction.DRAFT.toString()
 
                 when (uploadAction) {
                     UploadAction.DRAFT.toString() -> {
@@ -66,24 +86,36 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
                         responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString()))
                     }
                     UploadAction.VALIDATE.toString() -> {
-                        //TODO("Not Implemented")
-                        responseObserver.onNext(failStatus(request.commonHeader,
+                        // TODO("Not Implemented")
+                        responseObserver.onNext(
+                            failStatus(
+                                request.commonHeader,
                                 "Upload action($uploadAction) not implemented",
-                                BluePrintProcessorException("Not Implemented")))
+                                BluePrintProcessorException("Not Implemented")
+                            )
+                        )
                     }
                     UploadAction.ENRICH.toString() -> {
                         val enrichedByteArray = bluePrintModelHandler.enrichBlueprintFileSource(byteArray)
                         responseObserver.onNext(outputWithFileBytes(request.commonHeader, enrichedByteArray))
                     }
                     else -> {
-                        responseObserver.onNext(failStatus(request.commonHeader,
+                        responseObserver.onNext(
+                            failStatus(
+                                request.commonHeader,
                                 "Upload action($uploadAction) not implemented",
-                                BluePrintProcessorException("Not implemented")))
+                                BluePrintProcessorException("Not implemented")
+                            )
+                        )
                     }
                 }
             } catch (e: Exception) {
-                responseObserver.onNext(failStatus(request.commonHeader,
-                        "request(${request.commonHeader.requestId}): Failed to upload CBA", e))
+                responseObserver.onNext(
+                    failStatus(
+                        request.commonHeader,
+                        "request(${request.commonHeader.requestId}): Failed to upload CBA", e
+                    )
+                )
             } finally {
                 responseObserver.onCompleted()
             }
@@ -91,8 +123,10 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
     }
 
     @PreAuthorize("hasRole('USER')")
-    override fun downloadBlueprint(request: BluePrintDownloadInput,
-                                   responseObserver: StreamObserver<BluePrintManagementOutput>) {
+    override fun downloadBlueprint(
+        request: BluePrintDownloadInput,
+        responseObserver: StreamObserver<BluePrintManagementOutput>
+    ) {
         runBlocking {
             val blueprintName = request.actionIdentifiers.blueprintName
             val blueprintVersion = request.actionIdentifiers.blueprintVersion
@@ -100,7 +134,7 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
 
             /** Get the Search Action */
             val searchAction = request.actionIdentifiers?.actionName.emptyTONull()
-                    ?: DownloadAction.SEARCH.toString()
+                ?: DownloadAction.SEARCH.toString()
 
             log.info("request(${request.commonHeader.requestId}): Received download $blueprint")
             try {
@@ -110,14 +144,22 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
                         responseObserver.onNext(outputWithFileBytes(request.commonHeader, downloadByteArray))
                     }
                     else -> {
-                        responseObserver.onNext(failStatus(request.commonHeader,
+                        responseObserver.onNext(
+                            failStatus(
+                                request.commonHeader,
                                 "Search action($searchAction) not implemented",
-                                BluePrintProcessorException("Not implemented")))
+                                BluePrintProcessorException("Not implemented")
+                            )
+                        )
                     }
                 }
             } catch (e: Exception) {
-                responseObserver.onNext(failStatus(request.commonHeader,
-                        "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e))
+                responseObserver.onNext(
+                    failStatus(
+                        request.commonHeader,
+                        "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e
+                    )
+                )
             } finally {
                 responseObserver.onCompleted()
             }
@@ -125,8 +167,11 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
     }
 
     @PreAuthorize("hasRole('USER')")
-    override fun removeBlueprint(request: BluePrintRemoveInput, responseObserver:
-    StreamObserver<BluePrintManagementOutput>) {
+    override fun removeBlueprint(
+        request: BluePrintRemoveInput,
+        responseObserver:
+            StreamObserver<BluePrintManagementOutput>
+    ) {
 
         runBlocking {
             val blueprintName = request.actionIdentifiers.blueprintName
@@ -137,7 +182,7 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
 
             /** Get the Remove Action */
             val removeAction = request.actionIdentifiers?.actionName.emptyTONull()
-                    ?: RemoveAction.DEFAULT.toString()
+                ?: RemoveAction.DEFAULT.toString()
 
             try {
                 when (removeAction) {
@@ -146,22 +191,32 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
                         responseObserver.onNext(successStatus(request.commonHeader))
                     }
                     else -> {
-                        responseObserver.onNext(failStatus(request.commonHeader,
+                        responseObserver.onNext(
+                            failStatus(
+                                request.commonHeader,
                                 "Remove action($removeAction) not implemented",
-                                BluePrintProcessorException("Not implemented")))
+                                BluePrintProcessorException("Not implemented")
+                            )
+                        )
                     }
                 }
             } catch (e: Exception) {
-                responseObserver.onNext(failStatus(request.commonHeader,
-                        "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e))
+                responseObserver.onNext(
+                    failStatus(
+                        request.commonHeader,
+                        "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e
+                    )
+                )
             } finally {
                 responseObserver.onCompleted()
             }
         }
     }
 
-    override fun bootstrapBlueprint(request: BluePrintBootstrapInput,
-                                    responseObserver: StreamObserver<BluePrintManagementOutput>) {
+    override fun bootstrapBlueprint(
+        request: BluePrintBootstrapInput,
+        responseObserver: StreamObserver<BluePrintManagementOutput>
+    ) {
         runBlocking {
             try {
                 log.info("request(${request.commonHeader.requestId}): Received bootstrap request")
@@ -173,10 +228,13 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
                 /** Perform bootstrap of Model Types, Resource Definitions and CBA */
                 bluePrintModelHandler.bootstrapBlueprint(bootstrapRequest)
                 responseObserver.onNext(successStatus(request.commonHeader))
-
             } catch (e: Exception) {
-                responseObserver.onNext(failStatus(request.commonHeader,
-                        "request(${request.commonHeader.requestId}): Failed to bootstrap", e))
+                responseObserver.onNext(
+                    failStatus(
+                        request.commonHeader,
+                        "request(${request.commonHeader.requestId}): Failed to bootstrap", e
+                    )
+                )
             } finally {
                 responseObserver.onCompleted()
             }
@@ -184,15 +242,18 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
     }
 
     private fun outputWithFileBytes(header: CommonHeader, byteArray: ByteArray): BluePrintManagementOutput =
-            BluePrintManagementOutput.newBuilder()
-                    .setCommonHeader(header)
-                    .setFileChunk(FileChunk.newBuilder().setChunk(ByteString.copyFrom(byteArray)))
-                    .setStatus(Status.newBuilder()
-                            .setTimestamp(currentTimestamp())
-                            .setMessage(BluePrintConstants.STATUS_SUCCESS)
-                            .setCode(200)
-                            .build())
+        BluePrintManagementOutput.newBuilder()
+            .setCommonHeader(header)
+            .setFileChunk(FileChunk.newBuilder().setChunk(ByteString.copyFrom(byteArray)))
+            .setStatus(
+                Status.newBuilder()
+                    .setTimestamp(currentTimestamp())
+                    .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
@@ -201,30 +262,59 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
             JsonFormat.parser().merge(propertyContent, propertiesBuilder)
         }
         return BluePrintManagementOutput.newBuilder()
-                .setCommonHeader(header)
-                .setProperties(propertiesBuilder.build())
-                .setStatus(Status.newBuilder()
-                        .setTimestamp(currentTimestamp())
-                        .setMessage(BluePrintConstants.STATUS_SUCCESS)
-                        .setCode(200)
-                        .build())
-                .build()
+            .setCommonHeader(header)
+            .setProperties(propertiesBuilder.build())
+            .setStatus(
+                Status.newBuilder()
+                    .setTimestamp(currentTimestamp())
+                    .setMessage(BluePrintConstants.STATUS_SUCCESS)
+                    .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()
+                .setStatus(
+                    Status.newBuilder()
                         .setTimestamp(currentTimestamp())
                         .setMessage(BluePrintConstants.STATUS_FAILURE)
-                        .setErrorMessage(message)
-                        .setCode(500)
-                        .build())
+                        .setEventType(EventType.EVENT_COMPONENT_FAILURE)
+                        .setErrorMessage("Error : ${errorPayload.message}")
+                        .setCode(errorPayload.code)
+                        .build()
+                )
                 .build()
-//        return io.grpc.Status.INTERNAL
-//                .withDescription(message)
-//                .withCause(e)
-//                .asException()
-    }
+        }
 }