make templating service support JsonNode instead of any.
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / test / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / resource / resolution / mock / MockRestResourceResolutionProcessor.kt
1 /*
2  * Copyright © 2019 IBM, Bell Canada.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock
17
18 import com.fasterxml.jackson.databind.JsonNode
19 import com.fasterxml.jackson.databind.node.ArrayNode
20 import com.fasterxml.jackson.databind.node.MissingNode
21 import org.apache.commons.collections.MapUtils
22 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
23 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.RestResourceSource
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
26 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
27 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
28 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
29 import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
30 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
31 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
32 import org.slf4j.LoggerFactory
33 import java.util.*
34
35 class MockRestResourceResolutionProcessor(private val blueprintRestLibPropertyService:
36                                           MockBluePrintRestLibPropertyService) : ResourceAssignmentProcessor() {
37
38     private val logger = LoggerFactory.getLogger(MockRestResourceResolutionProcessor::class.java)
39
40     override fun resolveInputKeyMappingVariables(inputKeyMapping: Map<String, String>): Map<String, JsonNode> {
41         val resolvedInputKeyMapping = HashMap<String, JsonNode>()
42         if (MapUtils.isNotEmpty(inputKeyMapping)) {
43
44             resolvedInputKeyMapping["service-instance-id"] = "10".asJsonPrimitive()
45             resolvedInputKeyMapping["vnf_name"] = "vnf1".asJsonPrimitive()
46             resolvedInputKeyMapping["vnf-id"] = "123456".asJsonPrimitive()
47         }
48         return resolvedInputKeyMapping
49     }
50
51     override fun getName(): String {
52         return "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
53     }
54
55     override suspend fun processNB(executionRequest: ResourceAssignment) {
56         try {
57             // Check if It has Input
58             val value = getFromInput(executionRequest)
59             if (value == null || value is MissingNode) {
60                 val dName = executionRequest.dictionaryName
61                 val dSource = executionRequest.dictionarySource
62                 val resourceDefinition = resourceDictionaries[dName]
63
64                 val resourceSource = resourceDefinition!!.sources[dSource]
65
66                 val resourceSourceProperties = resourceSource!!.properties
67
68                 val sourceProperties =
69                         JacksonUtils.getInstanceFromMap(resourceSourceProperties!!, RestResourceSource::class.java)
70
71                 val path = nullToEmpty(sourceProperties.path)
72                 val inputKeyMapping = sourceProperties.inputKeyMapping
73
74                 val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping!!).toMutableMap()
75
76                 // Resolving content Variables
77                 val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
78                 val urlPath =
79                         resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
80                 val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
81
82                 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
83
84                 // Get the Rest Client Service
85                 val restClientService = blueprintWebClientService(executionRequest)
86
87                 val response = restClientService.exchangeResource(verb, urlPath, payload)
88                 val responseStatusCode = response.status
89                 val responseBody = response.body
90                 if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
91                     populateResource(executionRequest, sourceProperties, responseBody, path)
92                     restClientService.tearDown()
93                 } else {
94                     val errMsg = "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
95                     logger.warn(errMsg)
96                     throw BluePrintProcessorException(errMsg)
97                 }
98             }
99         } catch (e: Exception) {
100             ResourceAssignmentUtils.setFailedResourceDataValue(executionRequest, e.message)
101             throw BluePrintProcessorException("Failed in template key ($executionRequest) assignments with: ${e.message}",
102                     e)
103         }
104     }
105
106     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ResourceAssignment) {
107         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
108     }
109
110     private fun blueprintWebClientService(resourceAssignment: ResourceAssignment): MockBlueprintWebClientService {
111         return blueprintRestLibPropertyService.mockBlueprintWebClientService(resourceAssignment.dictionarySource!!)
112     }
113
114     @Throws(BluePrintProcessorException::class)
115     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
116                                  restResponse: String, path: String) {
117         val type = nullToEmpty(resourceAssignment.property?.type)
118         lateinit var entrySchemaType: String
119
120         val outputKeyMapping = sourceProperties.outputKeyMapping
121
122         val responseNode = JacksonUtils.jsonNode(restResponse).at(path)
123
124         when (type) {
125             in BluePrintTypes.validPrimitiveTypes() -> {
126                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
127             }
128             in BluePrintTypes.validCollectionTypes() -> {
129                 // Array Types
130                 entrySchemaType = resourceAssignment.property!!.entrySchema!!.type
131                 val arrayNode = responseNode as ArrayNode
132
133                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
134                     val responseArrayNode = responseNode.toList()
135                     for (responseSingleJsonNode in responseArrayNode) {
136
137                         val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
138
139                         outputKeyMapping!!.map {
140                             val responseKeyValue = responseSingleJsonNode.get(it.key)
141                             val propertyTypeForDataType = ResourceAssignmentUtils
142                                     .getPropertyType(raRuntimeService, entrySchemaType, it.key)
143
144                             JacksonUtils.populateJsonNodeValues(it.value,
145                                     responseKeyValue, propertyTypeForDataType, arrayChildNode)
146                         }
147                         arrayNode.add(arrayChildNode)
148                     }
149                 }
150                 // Set the List of Complex Values
151                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
152             }
153             else -> {
154                 // Complex Types
155                 entrySchemaType = resourceAssignment.property!!.type
156                 val objectNode = JacksonUtils.objectMapper.createObjectNode()
157                 outputKeyMapping!!.map {
158                     val responseKeyValue = responseNode.get(it.key)
159                     val propertyTypeForDataType = ResourceAssignmentUtils
160                             .getPropertyType(raRuntimeService, entrySchemaType, it.key)
161                     JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
162                 }
163                 // Set the List of Complex Values
164                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
165             }
166         }
167     }
168 }