Add ResourceResolutionResult to ResourceResolutionService
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / resource / resolution / utils / ResourceAssignmentUtils.kt
1 /*
2  * Copyright © 2017-2018 AT&T Intellectual Property.
3  * Modifications Copyright (c) 2019 IBM, Bell Canada.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils
19
20 import com.fasterxml.jackson.databind.JsonNode
21 import com.fasterxml.jackson.databind.ObjectMapper
22 import com.fasterxml.jackson.databind.SerializationFeature
23 import com.fasterxml.jackson.databind.node.ArrayNode
24 import com.fasterxml.jackson.databind.node.NullNode
25 import com.fasterxml.jackson.databind.node.ObjectNode
26 import com.fasterxml.jackson.databind.node.TextNode
27 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
28 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
29 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
30 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
31 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
32 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
33 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
34 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
35 import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants.LOG_REDACTED
36 import org.onap.ccsdk.cds.controllerblueprints.core.isComplexType
37 import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
38 import org.onap.ccsdk.cds.controllerblueprints.core.isNullOrMissing
39 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
40 import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
41 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
42 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
43 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService
44 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonReactorUtils
45 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
46 import org.onap.ccsdk.cds.controllerblueprints.core.utils.PropertyDefinitionUtils.Companion.hasLogProtect
47 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.DictionaryMetadataEntry
48 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.KeyIdentifier
49 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResolutionSummary
50 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
51 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
52 import org.slf4j.LoggerFactory
53 import java.util.Date
54
55 class ResourceAssignmentUtils {
56     companion object {
57
58         private val logger = LoggerFactory.getLogger(ResourceAssignmentUtils::class.toString())
59
60         suspend fun resourceDefinitions(blueprintBasePath: String): MutableMap<String, ResourceDefinition> {
61             val dictionaryFile = normalizedFile(
62                 blueprintBasePath, BluePrintConstants.TOSCA_DEFINITIONS_DIR,
63                 ResourceResolutionConstants.FILE_NAME_RESOURCE_DEFINITION_TYPES
64             )
65             checkFileExists(dictionaryFile) { "resource definition file(${dictionaryFile.absolutePath}) is missing" }
66             return JacksonReactorUtils.getMapFromFile(dictionaryFile, ResourceDefinition::class.java)
67         }
68
69         @Throws(BluePrintProcessorException::class)
70         fun setResourceDataValue(
71             resourceAssignment: ResourceAssignment,
72             raRuntimeService: ResourceAssignmentRuntimeService,
73             value: Any?
74         ) {
75             // TODO("See if Validation is needed in future with respect to conversion and Types")
76             return setResourceDataValue(resourceAssignment, raRuntimeService, value.asJsonType())
77         }
78
79         @Throws(BluePrintProcessorException::class)
80         fun setResourceDataValue(
81             resourceAssignment: ResourceAssignment,
82             raRuntimeService: ResourceAssignmentRuntimeService,
83             value: JsonNode
84         ) {
85             val resourceProp = checkNotNull(resourceAssignment.property) {
86                 "Failed in setting resource value for resource mapping $resourceAssignment"
87             }
88             checkNotEmpty(resourceAssignment.name) {
89                 "Failed in setting resource value for resource mapping $resourceAssignment"
90             }
91
92             if (resourceAssignment.dictionaryName.isNullOrEmpty()) {
93                 resourceAssignment.dictionaryName = resourceAssignment.name
94                 logger.warn(
95                     "Missing dictionary key, setting with template key (${resourceAssignment.name}) " +
96                             "as dictionary key (${resourceAssignment.dictionaryName})"
97                 )
98             }
99
100             try {
101                 if (resourceProp.type.isNotEmpty()) {
102                     val metadata = resourceAssignment.property!!.metadata
103                     val valueToPrint = getValueToLog(metadata, value)
104                     logger.info(
105                         "Setting Resource Value ($valueToPrint) for Resource Name " +
106                                 "(${resourceAssignment.name}), definition(${resourceAssignment.dictionaryName}) " +
107                                 "of type (${resourceProp.type})"
108                     )
109                     setResourceValue(resourceAssignment, raRuntimeService, value)
110                     resourceAssignment.updatedDate = Date()
111                     resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
112                     resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS
113                 }
114             } catch (e: Exception) {
115                 throw BluePrintProcessorException(
116                     "Failed in setting value for template key " +
117                             "(${resourceAssignment.name}) and dictionary key (${resourceAssignment.dictionaryName}) of " +
118                             "type (${resourceProp.type}) with error message (${e.message})", e
119                 )
120             }
121         }
122
123         private fun setResourceValue(
124             resourceAssignment: ResourceAssignment,
125             raRuntimeService: ResourceAssignmentRuntimeService,
126             value: JsonNode
127         ) {
128             // TODO("See if Validation is needed wrt to type before storing")
129             raRuntimeService.putResolutionStore(resourceAssignment.name, value)
130             raRuntimeService.putDictionaryStore(resourceAssignment.dictionaryName!!, value)
131             resourceAssignment.property!!.value = value
132
133             val metadata = resourceAssignment.property?.metadata
134             metadata?.get(ResourceResolutionConstants.METADATA_TRANSFORM_TEMPLATE)
135                     ?.let { if (it.contains("$")) it else null }
136                     ?.let { template ->
137                         val resolutionStore = raRuntimeService.getResolutionStore()
138                                 .mapValues { e -> e.value.asText() } as MutableMap<String, Any>
139                         val newValue: JsonNode
140                         try {
141                             newValue = BluePrintVelocityTemplateService
142                                     .generateContent(template, null, true, resolutionStore)
143                                     .also { if (hasLogProtect(metadata))
144                                         logger.info("Transformed value: $resourceAssignment.name")
145                                     else
146                                         logger.info("Transformed value: $value -> $it") }
147                                     .let { v -> v.asJsonType() }
148                         } catch (e: Exception) {
149                             throw BluePrintProcessorException(
150                                     "transform-template failed: $template", e)
151                         }
152                         with(resourceAssignment) {
153                             raRuntimeService.putResolutionStore(this.name, newValue)
154                             raRuntimeService.putDictionaryStore(this.dictionaryName!!, newValue)
155                             this.property!!.value = newValue
156                         }
157                     }
158         }
159
160         fun setFailedResourceDataValue(resourceAssignment: ResourceAssignment, message: String?) {
161             if (isNotEmpty(resourceAssignment.name)) {
162                 resourceAssignment.updatedDate = Date()
163                 resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
164                 resourceAssignment.status = BluePrintConstants.STATUS_FAILURE
165                 resourceAssignment.message = message
166             }
167         }
168
169         @Throws(BluePrintProcessorException::class)
170         fun assertTemplateKeyValueNotNull(resourceAssignment: ResourceAssignment) {
171             val resourceProp = checkNotNull(resourceAssignment.property) {
172                 "Failed to populate mandatory resource resource mapping $resourceAssignment"
173             }
174             if (resourceProp.required != null && resourceProp.required!! && resourceProp.value.isNullOrMissing()) {
175                 logger.error("failed to populate mandatory resource mapping ($resourceAssignment)")
176                 throw BluePrintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)")
177             }
178         }
179
180         @Throws(BluePrintProcessorException::class)
181         fun generateResourceDataForAssignments(assignments: List<ResourceAssignment>): String {
182             val result: String
183             try {
184                 val mapper = ObjectMapper()
185                 mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true)
186                 val root: ObjectNode = mapper.createObjectNode()
187
188                 var containsLogProtected = false
189                 assignments.forEach {
190                     if (isNotEmpty(it.name) && it.property != null) {
191                         val rName = it.name
192                         val metadata = it.property!!.metadata
193                         val type = nullToEmpty(it.property?.type).toLowerCase()
194                         val value = useDefaultValueIfNull(it, rName)
195                         val valueToPrint = getValueToLog(metadata, value)
196                         containsLogProtected = hasLogProtect(metadata)
197                         logger.trace("Generating Resource name ($rName), type ($type), value ($valueToPrint)")
198                         root.set<JsonNode>(rName, value)
199                     }
200                 }
201                 result = mapper.writerWithDefaultPrettyPrinter()
202                         .writeValueAsString(mapper.treeToValue(root, Object::class.java))
203
204                 if (!containsLogProtected) {
205                     logger.info("Generated Resource Param Data ($result)")
206                 }
207             } catch (e: Exception) {
208                 throw BluePrintProcessorException("Resource Assignment is failed with $e.message", e)
209             }
210
211             return result
212         }
213
214         @Throws(BluePrintProcessorException::class)
215         fun generateResourceForAssignments(assignments: List<ResourceAssignment>): MutableMap<String, JsonNode> {
216             val data: MutableMap<String, JsonNode> = hashMapOf()
217             assignments.forEach {
218                 if (isNotEmpty(it.name) && it.property != null) {
219                     val rName = it.name
220                     val metadata = it.property!!.metadata
221                     val type = nullToEmpty(it.property?.type).toLowerCase()
222                     val value = useDefaultValueIfNull(it, rName)
223                     val valueToPrint = getValueToLog(metadata, value)
224
225                     logger.trace("Generating Resource name ($rName), type ($type), value ($valueToPrint)")
226                     data[rName] = value
227                 }
228             }
229             return data
230         }
231
232         fun generateResolutionSummaryData(
233             resourceAssignments: List<ResourceAssignment>,
234             resourceDefinitions: Map<String, ResourceDefinition>
235         ): String {
236             val emptyTextNode = TextNode.valueOf("")
237             val resolutionSummaryList = resourceAssignments.map {
238                 val definition = resourceDefinitions[it.name]
239                 val description = definition?.property?.description ?: ""
240                 val value = it.property?.value
241                         ?.let { v -> if (v.isNullOrMissing()) emptyTextNode else v }
242                         ?: emptyTextNode
243
244                 var payload: JsonNode = definition?.sources?.get(it.dictionarySource)
245                         ?.properties?.get("resolved-payload")
246                         ?.let { p -> if (p.isNullOrMissing()) emptyTextNode else p }
247                         ?: emptyTextNode
248
249                 val metadata = definition?.property?.metadata
250                         ?.map { e -> DictionaryMetadataEntry(e.key, e.value) }
251                         ?.toMutableList() ?: mutableListOf()
252
253                 val keyIdentifiers: MutableList<KeyIdentifier> = it.keyIdentifiers.map { k ->
254                     if (k.value.isNullOrMissing()) KeyIdentifier(k.name, emptyTextNode) else k
255                 }.toMutableList()
256
257                 ResolutionSummary(
258                         it.name,
259                         value,
260                         it.property?.required ?: false,
261                         it.property?.type ?: "",
262                         keyIdentifiers,
263                         description,
264                         metadata,
265                         it.dictionaryName ?: "",
266                         it.dictionarySource ?: "",
267                         payload,
268                         it.status ?: "",
269                         it.message ?: ""
270                 )
271             }
272             // Wrapper needed for integration with SDNC
273             val data = mapOf("resolution-summary" to resolutionSummaryList)
274             return JacksonUtils.getJson(data, includeNull = true)
275         }
276
277         private fun useDefaultValueIfNull(
278             resourceAssignment: ResourceAssignment,
279             resourceAssignmentName: String
280         ): JsonNode {
281             if (resourceAssignment.property?.value == null) {
282                 val defaultValue = "\${$resourceAssignmentName}"
283                 return TextNode(defaultValue)
284             } else {
285                 return resourceAssignment.property!!.value!!
286             }
287         }
288
289         fun transformToRARuntimeService(
290             blueprintRuntimeService: BluePrintRuntimeService<*>,
291             templateArtifactName: String
292         ): ResourceAssignmentRuntimeService {
293
294             val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService(
295                 blueprintRuntimeService.id(),
296                 blueprintRuntimeService.bluePrintContext()
297             )
298             resourceAssignmentRuntimeService.createUniqueId(templateArtifactName)
299             resourceAssignmentRuntimeService.setExecutionContext(blueprintRuntimeService.getExecutionContext() as MutableMap<String, JsonNode>)
300
301             return resourceAssignmentRuntimeService
302         }
303
304         @Throws(BluePrintProcessorException::class)
305         fun getPropertyType(
306             raRuntimeService: ResourceAssignmentRuntimeService,
307             dataTypeName: String,
308             propertyName: String
309         ): String {
310             lateinit var type: String
311             try {
312                 val dataTypeProps =
313                     checkNotNull(raRuntimeService.bluePrintContext().dataTypeByName(dataTypeName)?.properties)
314
315                 val propertyDefinition = checkNotNull(dataTypeProps[propertyName])
316                 type = checkNotEmpty(propertyDefinition.type) { "Couldn't get data type ($dataTypeName)" }
317                 logger.trace("Data type({})'s property ({}) is ({})", dataTypeName, propertyName, type)
318             } catch (e: Exception) {
319                 logger.error("couldn't get data type($dataTypeName)'s property ($propertyName), error message $e")
320                 throw BluePrintProcessorException("${e.message}", e)
321             }
322             return type
323         }
324
325         @Throws(BluePrintProcessorException::class)
326         fun parseResponseNode(
327             responseNode: JsonNode,
328             resourceAssignment: ResourceAssignment,
329             raRuntimeService: ResourceAssignmentRuntimeService,
330             outputKeyMapping: MutableMap<String, String>
331         ): JsonNode {
332             val metadata = resourceAssignment.property!!.metadata
333             try {
334                 if ((resourceAssignment.property?.type).isNullOrEmpty()) {
335                     throw BluePrintProcessorException("Couldn't get data dictionary type for dictionary name (${resourceAssignment.name})")
336                 }
337                 val type = resourceAssignment.property!!.type
338                 val valueToPrint = getValueToLog(metadata, responseNode)
339
340                 logger.info("For template key (${resourceAssignment.name}) trying to get value from responseNode ($valueToPrint)")
341                 return when (type) {
342                     in BluePrintTypes.validPrimitiveTypes() -> {
343                         // Primitive Types
344                         parseResponseNodeForPrimitiveTypes(responseNode, resourceAssignment, outputKeyMapping)
345                     }
346                     in BluePrintTypes.validCollectionTypes() -> {
347                         // Array Types
348                         parseResponseNodeForCollection(responseNode, resourceAssignment, raRuntimeService, outputKeyMapping)
349                     }
350                     else -> {
351                         // Complex Types
352                         parseResponseNodeForComplexType(responseNode, resourceAssignment, raRuntimeService, outputKeyMapping)
353                     }
354                 }
355             } catch (e: Exception) {
356                 logger.error("Fail to parse response data, error message $e")
357                 throw BluePrintProcessorException("${e.message}", e)
358             }
359         }
360
361         private fun parseResponseNodeForPrimitiveTypes(
362             responseNode: JsonNode,
363             resourceAssignment: ResourceAssignment,
364             outputKeyMapping: MutableMap<String, String>
365         ): JsonNode {
366             // Return responseNode if is not a Complex Type
367             if (!responseNode.isComplexType()) {
368                 return responseNode
369             }
370
371             val outputKey = outputKeyMapping.keys.firstOrNull()
372             var returnNode = if (responseNode is ArrayNode) {
373                 val arrayNode = responseNode.toList()
374                 if (outputKey.isNullOrEmpty()) {
375                     arrayNode.first()
376                 } else {
377                     arrayNode.firstOrNull { element ->
378                         element.isComplexType() && element.has(outputKeyMapping[outputKey])
379                     }
380                 }
381             } else {
382                 responseNode
383             }
384
385             if (returnNode.isNullOrMissing() || returnNode!!.isComplexType() && !returnNode.has(outputKeyMapping[outputKey])) {
386                 throw BluePrintProcessorException("Fail to find output key mapping ($outputKey) in the responseNode.")
387             }
388
389             val returnValue = if (returnNode.isComplexType()) {
390                 returnNode[outputKeyMapping[outputKey]]
391             } else {
392                 returnNode
393             }
394
395             outputKey?.let { KeyIdentifier(it, returnValue) }
396                 ?.let { resourceAssignment.keyIdentifiers.add(it) }
397             return returnValue
398         }
399
400         private fun parseResponseNodeForCollection(
401             responseNode: JsonNode,
402             resourceAssignment: ResourceAssignment,
403             raRuntimeService: ResourceAssignmentRuntimeService,
404             outputKeyMapping: MutableMap<String, String>
405         ): JsonNode {
406             val dName = resourceAssignment.dictionaryName
407             val metadata = resourceAssignment.property!!.metadata
408             var resultNode: JsonNode
409             if ((resourceAssignment.property?.entrySchema?.type).isNullOrEmpty()) {
410                 throw BluePrintProcessorException(
411                     "Couldn't get data type for dictionary type " +
412                             "(${resourceAssignment.property!!.type}) and dictionary name ($dName)"
413                 )
414             }
415             val entrySchemaType = resourceAssignment.property!!.entrySchema!!.type
416
417             var arrayNode = JacksonUtils.objectMapper.createArrayNode()
418             if (outputKeyMapping.isNotEmpty()) {
419                 when (responseNode) {
420                     is ArrayNode -> {
421                         val responseArrayNode = responseNode.toList()
422                         for (responseSingleJsonNode in responseArrayNode) {
423                             val arrayChildNode = parseSingleElementOfArrayResponseNode(
424                                 entrySchemaType, resourceAssignment,
425                                 outputKeyMapping, raRuntimeService, responseSingleJsonNode, metadata
426                             )
427                             arrayNode.add(arrayChildNode)
428                         }
429                         resultNode = arrayNode
430                     }
431                     is ObjectNode -> {
432                         val responseArrayNode = responseNode.rootFieldsToMap()
433                         resultNode =
434                             parseObjectResponseNode(
435                                 resourceAssignment, entrySchemaType, outputKeyMapping,
436                                 responseArrayNode, metadata
437                             )
438                     }
439                     else -> {
440                         throw BluePrintProcessorException("Key-value response expected to match the responseNode.")
441                     }
442                 }
443             } else {
444                 when (responseNode) {
445                     is ArrayNode -> {
446                         responseNode.forEach { elementNode ->
447                             arrayNode.add(elementNode)
448                         }
449                         resultNode = arrayNode
450                     }
451                     is ObjectNode -> {
452                         val responseArrayNode = responseNode.rootFieldsToMap()
453                         for ((key, responseSingleJsonNode) in responseArrayNode) {
454                             val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
455                             logKeyValueResolvedResource(metadata, key, responseSingleJsonNode, entrySchemaType)
456                             JacksonUtils.populateJsonNodeValues(
457                                 key,
458                                 responseSingleJsonNode,
459                                 entrySchemaType,
460                                 arrayChildNode
461                             )
462                             arrayNode.add(arrayChildNode)
463                         }
464                         resultNode = arrayNode
465                     }
466                     else -> {
467                         resultNode = responseNode
468                     }
469                 }
470             }
471
472             return resultNode
473         }
474
475         private fun parseSingleElementOfArrayResponseNode(
476             entrySchemaType: String,
477             resourceAssignment: ResourceAssignment,
478             outputKeyMapping: MutableMap<String, String>,
479             raRuntimeService: ResourceAssignmentRuntimeService,
480             responseNode: JsonNode,
481             metadata: MutableMap<String, String>?
482         ): ObjectNode {
483             val outputKeyMappingHasOnlyOneElement = checkIfOutputKeyMappingProvideOneElement(outputKeyMapping)
484             when (entrySchemaType) {
485                 in BluePrintTypes.validPrimitiveTypes() -> {
486                     if (outputKeyMappingHasOnlyOneElement) {
487                         val outputKeyMap = outputKeyMapping.entries.first()
488                         if (resourceAssignment.keyIdentifiers.none { it.name == outputKeyMap.key }) {
489                             resourceAssignment.keyIdentifiers.add(
490                                     KeyIdentifier(outputKeyMap.key, JacksonUtils.objectMapper.createArrayNode())
491                             )
492                         }
493                         return parseSingleElementNodeWithOneOutputKeyMapping(
494                             resourceAssignment,
495                             responseNode,
496                             outputKeyMap.key,
497                             outputKeyMap.value,
498                             entrySchemaType,
499                             metadata
500                         )
501                     } else {
502                         throw BluePrintProcessorException("Expect one entry in output-key-mapping")
503                     }
504                 }
505                 else -> {
506                     return when {
507                         checkOutputKeyMappingAllElementsInDataTypeProperties(
508                             entrySchemaType,
509                             outputKeyMapping,
510                             raRuntimeService
511                         ) -> {
512                             parseSingleElementNodeWithAllOutputKeyMapping(
513                                 resourceAssignment,
514                                 responseNode,
515                                 outputKeyMapping,
516                                 entrySchemaType,
517                                 metadata
518                             )
519                         }
520                         outputKeyMappingHasOnlyOneElement -> {
521                             val outputKeyMap = outputKeyMapping.entries.first()
522                             parseSingleElementNodeWithOneOutputKeyMapping(
523                                 resourceAssignment,
524                                 responseNode,
525                                 outputKeyMap.key,
526                                 outputKeyMap.value,
527                                 entrySchemaType,
528                                 metadata
529                             )
530                         }
531                         else -> {
532                             throw BluePrintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType")
533                         }
534                     }
535                 }
536             }
537         }
538
539         private fun parseObjectResponseNode(
540             resourceAssignment: ResourceAssignment,
541             entrySchemaType: String,
542             outputKeyMapping: MutableMap<String, String>,
543             responseArrayNode: MutableMap<String, JsonNode>,
544             metadata: MutableMap<String, String>?
545         ): ObjectNode {
546             val outputKeyMappingHasOnlyOneElement = checkIfOutputKeyMappingProvideOneElement(outputKeyMapping)
547             if (outputKeyMappingHasOnlyOneElement) {
548                 val outputKeyMap = outputKeyMapping.entries.first()
549                 val returnValue = parseObjectResponseNodeWithOneOutputKeyMapping(
550                     responseArrayNode, outputKeyMap.key, outputKeyMap.value,
551                     entrySchemaType, metadata
552                 )
553                 resourceAssignment.keyIdentifiers.add(KeyIdentifier(outputKeyMap.key, returnValue))
554                 return returnValue
555             } else {
556                 throw BluePrintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType")
557             }
558         }
559
560         private fun parseSingleElementNodeWithOneOutputKeyMapping(
561             resourceAssignment: ResourceAssignment,
562             responseSingleJsonNode: JsonNode,
563             outputKeyMappingKey: String,
564             outputKeyMappingValue: String,
565             type: String,
566             metadata: MutableMap<String, String>?
567         ): ObjectNode {
568             val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
569
570             val responseKeyValue = if (responseSingleJsonNode.has(outputKeyMappingValue)) {
571                 responseSingleJsonNode.get(outputKeyMappingValue)
572             } else {
573                 NullNode.getInstance()
574             }
575
576             logKeyValueResolvedResource(metadata, outputKeyMappingKey, responseKeyValue, type)
577             JacksonUtils.populateJsonNodeValues(outputKeyMappingKey, responseKeyValue, type, arrayChildNode)
578             resourceAssignment.keyIdentifiers.find { it.name == outputKeyMappingKey && it.value.isArray }
579                     .let {
580                         if (it != null)
581                             (it.value as ArrayNode).add(responseKeyValue)
582                         else
583                             resourceAssignment.keyIdentifiers.add(
584                                     KeyIdentifier(outputKeyMappingKey, responseKeyValue))
585                     }
586             return arrayChildNode
587         }
588
589         private fun parseSingleElementNodeWithAllOutputKeyMapping(
590             resourceAssignment: ResourceAssignment,
591             responseSingleJsonNode: JsonNode,
592             outputKeyMapping: MutableMap<String, String>,
593             type: String,
594             metadata: MutableMap<String, String>?
595         ): ObjectNode {
596             val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
597             outputKeyMapping.map {
598                 val responseKeyValue = if (responseSingleJsonNode.has(it.value)) {
599                     responseSingleJsonNode.get(it.value)
600                 } else {
601                     NullNode.getInstance()
602                 }
603
604                 logKeyValueResolvedResource(metadata, it.key, responseKeyValue, type)
605                 JacksonUtils.populateJsonNodeValues(it.key, responseKeyValue, type, arrayChildNode)
606                 resourceAssignment.keyIdentifiers.add(KeyIdentifier(it.key, responseKeyValue))
607             }
608             return arrayChildNode
609         }
610
611         private fun parseObjectResponseNodeWithOneOutputKeyMapping(
612             responseArrayNode: MutableMap<String, JsonNode>,
613             outputKeyMappingKey: String,
614             outputKeyMappingValue: String,
615             type: String,
616             metadata: MutableMap<String, String>?
617         ): ObjectNode {
618             val objectNode = JacksonUtils.objectMapper.createObjectNode()
619             val responseSingleJsonNode = responseArrayNode.filterKeys { key ->
620                 key == outputKeyMappingValue
621             }.entries.firstOrNull()
622
623             if (responseSingleJsonNode == null) {
624                 logKeyValueResolvedResource(metadata, outputKeyMappingKey, NullNode.getInstance(), type)
625                 JacksonUtils.populateJsonNodeValues(outputKeyMappingKey, NullNode.getInstance(), type, objectNode)
626             } else {
627                 logKeyValueResolvedResource(metadata, outputKeyMappingKey, responseSingleJsonNode.value, type)
628                 JacksonUtils.populateJsonNodeValues(outputKeyMappingKey, responseSingleJsonNode.value, type, objectNode)
629             }
630             return objectNode
631         }
632
633         private fun parseResponseNodeForComplexType(
634             responseNode: JsonNode,
635             resourceAssignment: ResourceAssignment,
636             raRuntimeService: ResourceAssignmentRuntimeService,
637             outputKeyMapping: MutableMap<String, String>
638         ): JsonNode {
639             val entrySchemaType = resourceAssignment.property!!.type
640             val dictionaryName = resourceAssignment.dictionaryName!!
641             val metadata = resourceAssignment.property!!.metadata
642             val outputKeyMappingHasOnlyOneElement = checkIfOutputKeyMappingProvideOneElement(outputKeyMapping)
643
644             if (outputKeyMapping.isNotEmpty()) {
645                 return when {
646                     checkOutputKeyMappingAllElementsInDataTypeProperties(
647                         entrySchemaType,
648                         outputKeyMapping,
649                         raRuntimeService
650                     ) -> {
651                         parseSingleElementNodeWithAllOutputKeyMapping(
652                             resourceAssignment,
653                             responseNode,
654                             outputKeyMapping,
655                             entrySchemaType,
656                             metadata
657                         )
658                     }
659                     outputKeyMappingHasOnlyOneElement -> {
660                         val outputKeyMap = outputKeyMapping.entries.first()
661                         parseSingleElementNodeWithOneOutputKeyMapping(
662                             resourceAssignment, responseNode, outputKeyMap.key,
663                             outputKeyMap.value, entrySchemaType, metadata
664                         )
665                     }
666                     else -> {
667                         throw BluePrintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType")
668                     }
669                 }
670             } else {
671                 val childNode = JacksonUtils.objectMapper.createObjectNode()
672                 JacksonUtils.populateJsonNodeValues(dictionaryName, responseNode, entrySchemaType, childNode)
673                 return childNode
674             }
675         }
676
677         private fun checkOutputKeyMappingAllElementsInDataTypeProperties(
678             dataTypeName: String,
679             outputKeyMapping: MutableMap<String, String>,
680             raRuntimeService: ResourceAssignmentRuntimeService
681         ): Boolean {
682             val dataTypeProps = raRuntimeService.bluePrintContext().dataTypeByName(dataTypeName)?.properties
683             val result = outputKeyMapping.filterKeys { !dataTypeProps!!.containsKey(it) }.keys.firstOrNull()
684             return result == null
685         }
686
687         private fun logKeyValueResolvedResource(
688             metadata: MutableMap<String, String>?,
689             key: String,
690             value: JsonNode,
691             type: String
692         ) {
693             val valueToPrint = getValueToLog(metadata, value)
694
695             logger.info(
696                 "For List Type Resource: key ($key), value ($valueToPrint), " +
697                         "type  ({$type})"
698             )
699         }
700
701         private fun checkIfOutputKeyMappingProvideOneElement(outputKeyMapping: MutableMap<String, String>): Boolean {
702             return (outputKeyMapping.size == 1)
703         }
704
705         fun getValueToLog(metadata: MutableMap<String, String>?, value: Any): Any =
706                 if (hasLogProtect(metadata)) LOG_REDACTED else value
707     }
708 }