aboutsummaryrefslogtreecommitdiffstats
path: root/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BlueprintModelHandler.kt
blob: 42954c16e5ab5f0d305fa3323114a73e016dc86c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
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<BlueprintModelSearch> list of the controller blueprint archives
     </BlueprintModelSearch> */
    open fun allBlueprintModel(): List<BlueprintModelSearch> {
        return blueprintModelSearchRepository.findAll()
    }

    /**
     * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database
     *
     * @return List<BlueprintModelSearch> list of the controller blueprint archives
     </BlueprintModelSearch> */
    open fun allBlueprintModel(pageRequest: Pageable): Page<BlueprintModelSearch> {
        return blueprintModelSearchRepository.findAll(pageRequest)
    }

    /**
     * This is a saveBlueprintModel method
     *
     * @param filePart filePart
     * @return Mono<BlueprintModelSearch>
     * @throws BlueprintException BlueprintException
     </BlueprintModelSearch> */
    @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<BlueprintModelSearch>
     </BlueprintModelSearch> */
    open fun searchBlueprintModels(tags: String): List<BlueprintModelSearch> {
        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<Resource>
     * @throws BlueprintException BlueprintException
     </Resource> */
    @Throws(BlueprintException::class)
    open fun downloadBlueprintModelFileByNameAndVersion(
        name: String,
        version: String
    ): ResponseEntity<Resource> {
        try {
            val archiveByteArray = download(name, version)
            val fileName = "${name}_$version.zip"
            return prepareResourceEntity(fileName, archiveByteArray)
        } catch (e: 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<Resource>
     * @throws BlueprintException BlueprintException
     </Resource> */
    @Throws(BlueprintException::class)
    open fun downloadBlueprintModelFile(id: String): ResponseEntity<Resource> {
        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<Resource>
     </Resource> */
    private fun prepareResourceEntity(fileName: String, file: ByteArray): ResponseEntity<Resource> {
        return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("text/plain"))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"")
            .body(ByteArrayResource(file))
    }

    /**
     * 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<BlueprintModelSearch> list of the controller blueprint
     </BlueprintModelSearch> */
    open fun searchBlueprintModelsByKeyWord(keyWord: String): List<BlueprintModelSearch> {
        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<BlueprintModelSearch> list of the controller blueprint
     </BlueprintModelSearch> */
    open fun searchBlueprintModelsByKeyWordPaged(keyWord: String, pageRequest: PageRequest): Page<BlueprintModelSearch> {
        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<Resource>
     * @throws BlueprintException BlueprintException
     */
    @Throws(BlueprintException::class)
    open suspend fun enrichBlueprint(filePart: FilePart): ResponseEntity<Resource> {
        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"
    }
}