aboutsummaryrefslogtreecommitdiffstats
path: root/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt
blob: 7ab3126bb80d7644b80458087127d750672e259d (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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/*
 * Copyright © 2017-2018 AT&T Intellectual Property.
 * Modifications Copyright (c) 2019 IBM, Bell Canada.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils

import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.NullNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.node.TextNode
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants.LOG_REDACTED
import org.onap.ccsdk.cds.controllerblueprints.core.isComplexType
import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
import org.onap.ccsdk.cds.controllerblueprints.core.isNullOrMissing
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonReactorUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.PropertyDefinitionUtils.Companion.hasLogProtect
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.DictionaryMetadataEntry
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.KeyIdentifier
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResolutionSummary
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
import org.slf4j.LoggerFactory
import java.util.Date

class ResourceAssignmentUtils {
    companion object {

        private val logger = LoggerFactory.getLogger(ResourceAssignmentUtils::class.toString())

        suspend fun resourceDefinitions(blueprintBasePath: String): MutableMap<String, ResourceDefinition> {
            val dictionaryFile = normalizedFile(
                blueprintBasePath, BluePrintConstants.TOSCA_DEFINITIONS_DIR,
                ResourceResolutionConstants.FILE_NAME_RESOURCE_DEFINITION_TYPES
            )
            checkFileExists(dictionaryFile) { "resource definition file(${dictionaryFile.absolutePath}) is missing" }
            return JacksonReactorUtils.getMapFromFile(dictionaryFile, ResourceDefinition::class.java)
        }

        @Throws(BluePrintProcessorException::class)
        fun setResourceDataValue(
            resourceAssignment: ResourceAssignment,
            raRuntimeService: ResourceAssignmentRuntimeService,
            value: Any?
        ) {
            // TODO("See if Validation is needed in future with respect to conversion and Types")
            return setResourceDataValue(resourceAssignment, raRuntimeService, value.asJsonType())
        }

        @Throws(BluePrintProcessorException::class)
        fun setResourceDataValue(
            resourceAssignment: ResourceAssignment,
            raRuntimeService: ResourceAssignmentRuntimeService,
            value: JsonNode
        ) {
            val resourceProp = checkNotNull(resourceAssignment.property) {
                "Failed in setting resource value for resource mapping $resourceAssignment"
            }
            checkNotEmpty(resourceAssignment.name) {
                "Failed in setting resource value for resource mapping $resourceAssignment"
            }

            if (resourceAssignment.dictionaryName.isNullOrEmpty()) {
                resourceAssignment.dictionaryName = resourceAssignment.name
                logger.warn(
                    "Missing dictionary key, setting with template key (${resourceAssignment.name}) " +
                        "as dictionary key (${resourceAssignment.dictionaryName})"
                )
            }

            try {
                if (resourceProp.type.isNotEmpty()) {
                    val metadata = resourceAssignment.property!!.metadata
                    val valueToPrint = getValueToLog(metadata, value)
                    logger.info(
                        "Setting Resource Value ($valueToPrint) for Resource Name " +
                            "(${resourceAssignment.name}), definition(${resourceAssignment.dictionaryName}) " +
                            "of type (${resourceProp.type})"
                    )
                    setResourceValue(resourceAssignment, raRuntimeService, value)
                    resourceAssignment.updatedDate = Date()
                    resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
                    resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS
                }
            } catch (e: Exception) {
                throw BluePrintProcessorException(
                    "Failed in setting value for template key " +
                        "(${resourceAssignment.name}) and dictionary key (${resourceAssignment.dictionaryName}) of " +
                        "type (${resourceProp.type}) with error message (${e.message})",
                    e
                )
            }
        }

        private fun setResourceValue(
            resourceAssignment: ResourceAssignment,
            raRuntimeService: ResourceAssignmentRuntimeService,
            value: JsonNode
        ) {
            // TODO("See if Validation is needed wrt to type before storing")
            raRuntimeService.putResolutionStore(resourceAssignment.name, value)
            raRuntimeService.putDictionaryStore(resourceAssignment.dictionaryName!!, value)
            resourceAssignment.property!!.value = value

            val metadata = resourceAssignment.property?.metadata
            metadata?.get(ResourceResolutionConstants.METADATA_TRANSFORM_TEMPLATE)
                ?.let { if (it.contains("$")) it else null }
                ?.let { template ->
                    val resolutionStore = raRuntimeService.getResolutionStore()
                        .mapValues { e -> e.value.asText() } as MutableMap<String, Any>
                    val newValue: JsonNode
                    try {
                        newValue = BluePrintVelocityTemplateService
                            .generateContent(template, null, true, resolutionStore)
                            .also {
                                if (hasLogProtect(metadata))
                                    logger.info("Transformed value: $resourceAssignment.name")
                                else
                                    logger.info("Transformed value: $value -> $it")
                            }
                            .let { v -> v.asJsonType() }
                    } catch (e: Exception) {
                        throw BluePrintProcessorException(
                            "transform-template failed: $template", e
                        )
                    }
                    with(resourceAssignment) {
                        raRuntimeService.putResolutionStore(this.name, newValue)
                        raRuntimeService.putDictionaryStore(this.dictionaryName!!, newValue)
                        this.property!!.value = newValue
                    }
                }
        }

        fun setFailedResourceDataValue(resourceAssignment: ResourceAssignment, message: String?) {
            if (isNotEmpty(resourceAssignment.name)) {
                resourceAssignment.updatedDate = Date()
                resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
                resourceAssignment.status = BluePrintConstants.STATUS_FAILURE
                resourceAssignment.message = message
            }
        }

        @Throws(BluePrintProcessorException::class)
        fun assertTemplateKeyValueNotNull(resourceAssignment: ResourceAssignment) {
            val resourceProp = checkNotNull(resourceAssignment.property) {
                "Failed to populate mandatory resource resource mapping $resourceAssignment"
            }
            if (resourceProp.required != null && resourceProp.required!! && resourceProp.value.isNullOrMissing()) {
                logger.error("failed to populate mandatory resource mapping ($resourceAssignment)")
                throw BluePrintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)")
            }
        }

        @Throws(BluePrintProcessorException::class)
        fun generateResourceDataForAssignments(assignments: List<ResourceAssignment>): String {
            val result: String
            try {
                val mapper = ObjectMapper()
                mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true)
                val root: ObjectNode = mapper.createObjectNode()

                var containsLogProtected = false
                assignments.forEach {
                    if (isNotEmpty(it.name) && it.property != null) {
                        val rName = it.name
                        val metadata = it.property!!.metadata
                        val type = nullToEmpty(it.property?.type).toLowerCase()
                        val value = useDefaultValueIfNull(it, rName)
                        val valueToPrint = getValueToLog(metadata, value)
                        containsLogProtected = hasLogProtect(metadata)
                        logger.trace("Generating Resource name ($rName), type ($type), value ($valueToPrint)")
                        root.set<JsonNode>(rName, value)
                    }
                }
                result = mapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(mapper.treeToValue(root, Object::class.java))

                if (!containsLogProtected) {
                    logger.info("Generated Resource Param Data ($result)")
                }
            } catch (e: Exception) {
                throw BluePrintProcessorException("Resource Assignment is failed with $e.message", e)
            }

            return result
        }

        @Throws(BluePrintProcessorException::class)
        fun generateResourceForAssignments(assignments: List<ResourceAssignment>): MutableMap<String, JsonNode> {
            val data: MutableMap<String, JsonNode> = hashMapOf()
            assignments.forEach {
                if (isNotEmpty(it.name) && it.property != null) {
                    val rName = it.name
                    val metadata = it.property!!.metadata
                    val type = nullToEmpty(it.property?.type).toLowerCase()
                    val value = useDefaultValueIfNull(it, rName)
                    val valueToPrint = getValueToLog(metadata, value)

                    logger.trace("Generating Resource name ($rName), type ($type), value ($valueToPrint)")
                    data[rName] = value
                }
            }
            return data
        }

        fun generateResolutionSummaryData(
            resourceAssignments: List<ResourceAssignment>,
            resourceDefinitions: Map<String, ResourceDefinition>
        ): String {
            val emptyTextNode = TextNode.valueOf("")
            val resolutionSummaryList = resourceAssignments.map {
                val definition = resourceDefinitions[it.name]
                val description = definition?.property?.description ?: ""
                val value = it.property?.value
                    ?.let { v -> if (v.isNullOrMissing()) emptyTextNode else v }
                    ?: emptyTextNode

                var payload: JsonNode = definition?.sources?.get(it.dictionarySource)
                    ?.properties?.get("resolved-payload")
                    ?.let { p -> if (p.isNullOrMissing()) emptyTextNode else p }
                    ?: emptyTextNode

                val metadata = definition?.property?.metadata
                    ?.map { e -> DictionaryMetadataEntry(e.key, e.value) }
                    ?.toMutableList() ?: mutableListOf()

                val keyIdentifiers: MutableList<KeyIdentifier> = it.keyIdentifiers.map { k ->
                    if (k.value.isNullOrMissing()) KeyIdentifier(k.name, emptyTextNode) else k
                }.toMutableList()

                ResolutionSummary(
                    it.name,
                    value,
                    it.property?.required ?: false,
                    it.property?.type ?: "",
                    keyIdentifiers,
                    description,
                    metadata,
                    it.dictionaryName ?: "",
                    it.dictionarySource ?: "",
                    payload,
                    it.status ?: "",
                    it.message ?: ""
                )
            }
            // Wrapper needed for integration with SDNC
            val data = mapOf("resolution-summary" to resolutionSummaryList)
            return JacksonUtils.getJson(data, includeNull = true)
        }

        private fun useDefaultValueIfNull(
            resourceAssignment: ResourceAssignment,
            resourceAssignmentName: String
        ): JsonNode {
            if (resourceAssignment.property?.value == null) {
                val defaultValue = "\${$resourceAssignmentName}"
                return TextNode(defaultValue)
            } else {
                return resourceAssignment.property!!.value!!
            }
        }

        fun transformToRARuntimeService(
            blueprintRuntimeService: BluePrintRuntimeService<*>,
            templateArtifactName: String
        ): ResourceAssignmentRuntimeService {

            val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService(
                blueprintRuntimeService.id(),
                blueprintRuntimeService.bluePrintContext()
            )
            resourceAssignmentRuntimeService.createUniqueId(templateArtifactName)
            resourceAssignmentRuntimeService.setExecutionContext(blueprintRuntimeService.getExecutionContext() as MutableMap<String, JsonNode>)

            return resourceAssignmentRuntimeService
        }

        @Throws(BluePrintProcessorException::class)
        fun getPropertyType(
            raRuntimeService: ResourceAssignmentRuntimeService,
            dataTypeName: String,
            propertyName: String
        ): String {
            lateinit var type: String
            try {
                val dataTypeProps =
                    checkNotNull(raRuntimeService.bluePrintContext().dataTypeByName(dataTypeName)?.properties)

                val propertyDefinition = checkNotNull(dataTypeProps[propertyName])
                type = checkNotEmpty(propertyDefinition.type) { "Couldn't get data type ($dataTypeName)" }
                logger.trace("Data type({})'s property ({}) is ({})", dataTypeName, propertyName, type)
            } catch (e: Exception) {
                logger.error("couldn't get data type($dataTypeName)'s property ($propertyName), error message $e")
                throw BluePrintProcessorException("${e.message}", e)
            }
            return type
        }

        @Throws(BluePrintProcessorException::class)
        fun parseResponseNode(
            responseNode: JsonNode,
            resourceAssignment: ResourceAssignment,
            raRuntimeService: ResourceAssignmentRuntimeService,
            outputKeyMapping: MutableMap<String, String>
        ): JsonNode {
            val metadata = resourceAssignment.property!!.metadata
            try {
                if ((resourceAssignment.property?.type).isNullOrEmpty()) {
                    throw BluePrintProcessorException("Couldn't get data dictionary type for dictionary name (${resourceAssignment.name})")
                }
                val type = resourceAssignment.property!!.type
                val valueToPrint = getValueToLog(metadata, responseNode)

                logger.info("For template key (${resourceAssignment.name}) trying to get value from responseNode ($valueToPrint)")
                return when (type) {
                    in BluePrintTypes.validPrimitiveTypes() -> {
                        // Primitive Types
                        parseResponseNodeForPrimitiveTypes(responseNode, resourceAssignment, outputKeyMapping)
                    }
                    in BluePrintTypes.validCollectionTypes() -> {
                        // Array Types
                        parseResponseNodeForCollection(responseNode, resourceAssignment, raRuntimeService, outputKeyMapping)
                    }
                    else -> {
                        // Complex Types
                        parseResponseNodeForComplexType(responseNode, resourceAssignment, raRuntimeService, outputKeyMapping)
                    }
                }
            } catch (e: Exception) {
                logger.error("Fail to parse response data, error message $e")
                throw BluePrintProcessorException("${e.message}", e)
            }
        }

        private fun parseResponseNodeForPrimitiveTypes(
            responseNode: JsonNode,
            resourceAssignment: ResourceAssignment,
            outputKeyMapping: MutableMap<String, String>
        ): JsonNode {
            // Return responseNode if is not a Complex Type
            if (!responseNode.isComplexType()) {
                return responseNode
            }

            val outputKey = outputKeyMapping.keys.firstOrNull()
            var returnNode = if (responseNode is ArrayNode) {
                val arrayNode = responseNode.toList()
                if (outputKey.isNullOrEmpty()) {
                    arrayNode.first()
                } else {
                    arrayNode.firstOrNull { element ->
                        element.isComplexType() && element.has(outputKeyMapping[outputKey])
                    }
                }
            } else {
                responseNode
            }

            if (returnNode.isNullOrMissing() || returnNode!!.isComplexType() && !returnNode.has(outputKeyMapping[outputKey])) {
                throw BluePrintProcessorException("Fail to find output key mapping ($outputKey) in the responseNode.")
            }

            val returnValue = if (returnNode.isComplexType()) {
                returnNode[outputKeyMapping[outputKey]]
            } else {
                returnNode
            }

            outputKey?.let { KeyIdentifier(it, returnValue) }
                ?.let { resourceAssignment.keyIdentifiers.add(it) }
            return returnValue
        }

        private fun parseResponseNodeForCollection(
            responseNode: JsonNode,
            resourceAssignment: ResourceAssignment,
            raRuntimeService: ResourceAssignmentRuntimeService,
            outputKeyMapping: MutableMap<String, String>
        ): JsonNode {
            val dName = resourceAssignment.dictionaryName
            val metadata = resourceAssignment.property!!.metadata
            var resultNode: JsonNode
            if ((resourceAssignment.property?.entrySchema?.type).isNullOrEmpty()) {
                throw BluePrintProcessorException(
                    "Couldn't get data type for dictionary type " +
                        "(${resourceAssignment.property!!.type}) and dictionary name ($dName)"
                )
            }
            val entrySchemaType = resourceAssignment.property!!.entrySchema!!.type

            var arrayNode = JacksonUtils.objectMapper.createArrayNode()
            if (outputKeyMapping.isNotEmpty()) {
                when (responseNode) {
                    is ArrayNode -> {
                        val responseArrayNode = responseNode.toList()
                        for (responseSingleJsonNode in responseArrayNode) {
                            val arrayChildNode = parseSingleElementOfArrayResponseNode(
                                entrySchemaType, resourceAssignment,
                                outputKeyMapping, raRuntimeService, responseSingleJsonNode, metadata
                            )
                            arrayNode.add(arrayChildNode)
                        }
                        resultNode = arrayNode
                    }
                    is ObjectNode -> {
                        val responseArrayNode = responseNode.rootFieldsToMap()
                        resultNode =
                            parseObjectResponseNode(
                                resourceAssignment, entrySchemaType, outputKeyMapping,
                                responseArrayNode, metadata
                            )
                    }
                    else -> {
                        throw BluePrintProcessorException("Key-value response expected to match the responseNode.")
                    }
                }
            } else {
                when (responseNode) {
                    is ArrayNode -> {
                        responseNode.forEach { elementNode ->
                            arrayNode.add(elementNode)
                        }
                        resultNode = arrayNode
                    }
                    is ObjectNode -> {
                        val responseArrayNode = responseNode.rootFieldsToMap()
                        for ((key, responseSingleJsonNode) in responseArrayNode) {
                            val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
                            logKeyValueResolvedResource(metadata, key, responseSingleJsonNode, entrySchemaType)
                            JacksonUtils.populateJsonNodeValues(
                                key,
                                responseSingleJsonNode,
                                entrySchemaType,
                                arrayChildNode
                            )
                            arrayNode.add(arrayChildNode)
                        }
                        resultNode = arrayNode
                    }
                    else -> {
                        resultNode = responseNode
                    }
                }
            }

            return resultNode
        }

        private fun parseSingleElementOfArrayResponseNode(
            entrySchemaType: String,
            resourceAssignment: ResourceAssignment,
            outputKeyMapping: MutableMap<String, String>,
            raRuntimeService: ResourceAssignmentRuntimeService,
            responseNode: JsonNode,
            metadata: MutableMap<String, String>?
        ): ObjectNode {
            val outputKeyMappingHasOnlyOneElement = checkIfOutputKeyMappingProvideOneElement(outputKeyMapping)
            when (entrySchemaType) {
                in BluePrintTypes.validPrimitiveTypes() -> {
                    if (outputKeyMappingHasOnlyOneElement) {
                        val outputKeyMap = outputKeyMapping.entries.first()
                        if (resourceAssignment.keyIdentifiers.none { it.name == outputKeyMap.key }) {
                            resourceAssignment.keyIdentifiers.add(
                                KeyIdentifier(outputKeyMap.key, JacksonUtils.objectMapper.createArrayNode())
                            )
                        }
                        return parseSingleElementNodeWithOneOutputKeyMapping(
                            resourceAssignment,
                            responseNode,
                            outputKeyMap.key,
                            outputKeyMap.value,
                            entrySchemaType,
                            metadata
                        )
                    } else {
                        throw BluePrintProcessorException("Expect one entry in output-key-mapping")
                    }
                }
                else -> {
                    return when {
                        checkOutputKeyMappingAllElementsInDataTypeProperties(
                            entrySchemaType,
                            outputKeyMapping,
                            raRuntimeService
                        ) -> {
                            parseSingleElementNodeWithAllOutputKeyMapping(
                                resourceAssignment,
                                responseNode,
                                outputKeyMapping,
                                entrySchemaType,
                                metadata
                            )
                        }
                        outputKeyMappingHasOnlyOneElement -> {
                            val outputKeyMap = outputKeyMapping.entries.first()
                            parseSingleElementNodeWithOneOutputKeyMapping(
                                resourceAssignment,
                                responseNode,
                                outputKeyMap.key,
                                outputKeyMap.value,
                                entrySchemaType,
                                metadata
                            )
                        }
                        else -> {
                            throw BluePrintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType")
                        }
                    }
                }
            }
        }

        private fun parseObjectResponseNode(
            resourceAssignment: ResourceAssignment,
            entrySchemaType: String,
            outputKeyMapping: MutableMap<String, String>,
            responseArrayNode: MutableMap<String, JsonNode>,
            metadata: MutableMap<String, String>?
        ): ObjectNode {
            val outputKeyMappingHasOnlyOneElement = checkIfOutputKeyMappingProvideOneElement(outputKeyMapping)
            if (outputKeyMappingHasOnlyOneElement) {
                val outputKeyMap = outputKeyMapping.entries.first()
                val returnValue = parseObjectResponseNodeWithOneOutputKeyMapping(
                    responseArrayNode, outputKeyMap.key, outputKeyMap.value,
                    entrySchemaType, metadata
                )
                resourceAssignment.keyIdentifiers.add(KeyIdentifier(outputKeyMap.key, returnValue))
                return returnValue
            } else {
                throw BluePrintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType")
            }
        }

        private fun parseSingleElementNodeWithOneOutputKeyMapping(
            resourceAssignment: ResourceAssignment,
            responseSingleJsonNode: JsonNode,
            outputKeyMappingKey: String,
            outputKeyMappingValue: String,
            type: String,
            metadata: MutableMap<String, String>?
        ): ObjectNode {
            val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()

            val responseKeyValue = if (responseSingleJsonNode.has(outputKeyMappingValue)) {
                responseSingleJsonNode.get(outputKeyMappingValue)
            } else {
                NullNode.getInstance()
            }

            logKeyValueResolvedResource(metadata, outputKeyMappingKey, responseKeyValue, type)
            JacksonUtils.populateJsonNodeValues(outputKeyMappingKey, responseKeyValue, type, arrayChildNode)
            resourceAssignment.keyIdentifiers.find { it.name == outputKeyMappingKey && it.value.isArray }
                .let {
                    if (it != null)
                        (it.value as ArrayNode).add(responseKeyValue)
                    else
                        resourceAssignment.keyIdentifiers.add(
                            KeyIdentifier(outputKeyMappingKey, responseKeyValue)
                        )
                }
            return arrayChildNode
        }

        private fun parseSingleElementNodeWithAllOutputKeyMapping(
            resourceAssignment: ResourceAssignment,
            responseSingleJsonNode: JsonNode,
            outputKeyMapping: MutableMap<String, String>,
            type: String,
            metadata: MutableMap<String, String>?
        ): ObjectNode {
            val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
            outputKeyMapping.map {
                val responseKeyValue = if (responseSingleJsonNode.has(it.value)) {
                    responseSingleJsonNode.get(it.value)
                } else {
                    NullNode.getInstance()
                }

                logKeyValueResolvedResource(metadata, it.key, responseKeyValue, type)
                JacksonUtils.populateJsonNodeValues(it.key, responseKeyValue, type, arrayChildNode)
                resourceAssignment.keyIdentifiers.add(KeyIdentifier(it.key, responseKeyValue))
            }
            return arrayChildNode
        }

        private fun parseObjectResponseNodeWithOneOutputKeyMapping(
            responseArrayNode: MutableMap<String, JsonNode>,
            outputKeyMappingKey: String,
            outputKeyMappingValue: String,
            type: String,
            metadata: MutableMap<String, String>?
        ): ObjectNode {
            val objectNode = JacksonUtils.objectMapper.createObjectNode()
            val responseSingleJsonNode = responseArrayNode.filterKeys { key ->
                key == outputKeyMappingValue
            }.entries.firstOrNull()

            if (responseSingleJsonNode == null) {
                logKeyValueResolvedResource(metadata, outputKeyMappingKey, NullNode.getInstance(), type)
                JacksonUtils.populateJsonNodeValues(outputKeyMappingKey, NullNode.getInstance(), type, objectNode)
            } else {
                logKeyValueResolvedResource(metadata, outputKeyMappingKey, responseSingleJsonNode.value, type)
                JacksonUtils.populateJsonNodeValues(outputKeyMappingKey, responseSingleJsonNode.value, type, objectNode)
            }
            return objectNode
        }

        private fun parseResponseNodeForComplexType(
            responseNode: JsonNode,
            resourceAssignment: ResourceAssignment,
            raRuntimeService: ResourceAssignmentRuntimeService,
            outputKeyMapping: MutableMap<String, String>
        ): JsonNode {
            val entrySchemaType = resourceAssignment.property!!.type
            val dictionaryName = resourceAssignment.dictionaryName!!
            val metadata = resourceAssignment.property!!.metadata
            val outputKeyMappingHasOnlyOneElement = checkIfOutputKeyMappingProvideOneElement(outputKeyMapping)

            if (outputKeyMapping.isNotEmpty()) {
                return when {
                    checkOutputKeyMappingAllElementsInDataTypeProperties(
                        entrySchemaType,
                        outputKeyMapping,
                        raRuntimeService
                    ) -> {
                        parseSingleElementNodeWithAllOutputKeyMapping(
                            resourceAssignment,
                            responseNode,
                            outputKeyMapping,
                            entrySchemaType,
                            metadata
                        )
                    }
                    outputKeyMappingHasOnlyOneElement -> {
                        val outputKeyMap = outputKeyMapping.entries.first()
                        parseSingleElementNodeWithOneOutputKeyMapping(
                            resourceAssignment, responseNode, outputKeyMap.key,
                            outputKeyMap.value, entrySchemaType, metadata
                        )
                    }
                    else -> {
                        throw BluePrintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType")
                    }
                }
            } else {
                val childNode = JacksonUtils.objectMapper.createObjectNode()
                JacksonUtils.populateJsonNodeValues(dictionaryName, responseNode, entrySchemaType, childNode)
                return childNode
            }
        }

        private fun checkOutputKeyMappingAllElementsInDataTypeProperties(
            dataTypeName: String,
            outputKeyMapping: MutableMap<String, String>,
            raRuntimeService: ResourceAssignmentRuntimeService
        ): Boolean {
            val dataTypeProps = raRuntimeService.bluePrintContext().dataTypeByName(dataTypeName)?.properties
            var result: String? = null
            if (dataTypeProps != null)
                result = outputKeyMapping.filterKeys { !dataTypeProps.containsKey(it) }.keys.firstOrNull()
            return result == null
        }

        private fun logKeyValueResolvedResource(
            metadata: MutableMap<String, String>?,
            key: String,
            value: JsonNode,
            type: String
        ) {
            val valueToPrint = getValueToLog(metadata, value)

            logger.info(
                "For List Type Resource: key ($key), value ($valueToPrint), " +
                    "type  ({$type})"
            )
        }

        private fun checkIfOutputKeyMappingProvideOneElement(outputKeyMapping: MutableMap<String, String>): Boolean {
            return (outputKeyMapping.size == 1)
        }

        fun getValueToLog(metadata: MutableMap<String, String>?, value: Any): Any =
            if (hasLogProtect(metadata)) LOG_REDACTED else value
    }
}