Revert "Renaming Files having BluePrint to have Blueprint"
[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 org.apache.commons.collections.MapUtils
21 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
22 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.RestResourceSource
23 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
25 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
26 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
27 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
28 import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
29 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
30 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
31 import org.slf4j.LoggerFactory
32 import java.util.HashMap
33
34 class MockRestResourceResolutionProcessor(
35     private val blueprintRestLibPropertyService:
36         MockBluePrintRestLibPropertyService
37 ) : ResourceAssignmentProcessor() {
38
39     private val logger = LoggerFactory.getLogger(MockRestResourceResolutionProcessor::class.java)
40
41     override fun resolveInputKeyMappingVariables(inputKeyMapping: Map<String, String>): Map<String, JsonNode> {
42         val resolvedInputKeyMapping = HashMap<String, JsonNode>()
43         if (MapUtils.isNotEmpty(inputKeyMapping)) {
44
45             resolvedInputKeyMapping["service-instance-id"] = "10".asJsonPrimitive()
46             resolvedInputKeyMapping["vnf_name"] = "vnf1".asJsonPrimitive()
47             resolvedInputKeyMapping["vnf-id"] = "123456".asJsonPrimitive()
48         }
49         return resolvedInputKeyMapping
50     }
51
52     override fun getName(): String {
53         return "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
54     }
55
56     override suspend fun processNB(executionRequest: ResourceAssignment) {
57         try {
58             // Check if It has Input
59             if (!setFromInput(executionRequest)) {
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(
83                     "MockRestResource ($dSource) dictionary information: " +
84                         "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
85                 )
86
87                 // Get the Rest Client Service
88                 val restClientService = blueprintWebClientService(executionRequest)
89
90                 val response = restClientService.exchangeResource(verb, urlPath, payload)
91                 val responseStatusCode = response.status
92                 val responseBody = response.body
93                 if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
94                     populateResource(executionRequest, sourceProperties, responseBody, path)
95                     restClientService.tearDown()
96                 } else {
97                     val errMsg =
98                         "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
99                     logger.warn(errMsg)
100                     throw BluePrintProcessorException(errMsg)
101                 }
102             }
103         } catch (e: Exception) {
104             ResourceAssignmentUtils.setFailedResourceDataValue(executionRequest, e.message)
105             throw BluePrintProcessorException(
106                 "Failed in template resolutionKey ($executionRequest) assignments with: ${e.message}",
107                 e
108             )
109         }
110     }
111
112     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ResourceAssignment) {
113         addError(runtimeException.message!!)
114     }
115
116     private fun blueprintWebClientService(resourceAssignment: ResourceAssignment): MockBlueprintWebClientService {
117         return blueprintRestLibPropertyService.mockBlueprintWebClientService(resourceAssignment.dictionarySource!!)
118     }
119
120     @Throws(BluePrintProcessorException::class)
121     private fun populateResource(
122         resourceAssignment: ResourceAssignment,
123         sourceProperties: RestResourceSource,
124         restResponse: String,
125         path: String
126     ) {
127         val type = nullToEmpty(resourceAssignment.property?.type)
128         lateinit var entrySchemaType: String
129
130         val outputKeyMapping = sourceProperties.outputKeyMapping
131
132         val responseNode = JacksonUtils.jsonNode(restResponse).at(path)
133
134         when (type) {
135             in BluePrintTypes.validPrimitiveTypes() -> {
136                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
137             }
138             in BluePrintTypes.validCollectionTypes() -> {
139                 // Array Types
140                 entrySchemaType = resourceAssignment.property!!.entrySchema!!.type
141                 val arrayNode = responseNode as ArrayNode
142
143                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
144                     val responseArrayNode = responseNode.toList()
145                     for (responseSingleJsonNode in responseArrayNode) {
146
147                         val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
148
149                         outputKeyMapping!!.map {
150                             val responseKeyValue = responseSingleJsonNode.get(it.key)
151                             val propertyTypeForDataType = ResourceAssignmentUtils
152                                 .getPropertyType(raRuntimeService, entrySchemaType, it.key)
153
154                             JacksonUtils.populateJsonNodeValues(
155                                 it.value,
156                                 responseKeyValue, propertyTypeForDataType, arrayChildNode
157                             )
158                         }
159                         arrayNode.add(arrayChildNode)
160                     }
161                 }
162                 // Set the List of Complex Values
163                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
164             }
165             else -> {
166                 // Complex Types
167                 entrySchemaType = resourceAssignment.property!!.type
168                 val objectNode = JacksonUtils.objectMapper.createObjectNode()
169                 outputKeyMapping!!.map {
170                     val responseKeyValue = responseNode.get(it.key)
171                     val propertyTypeForDataType = ResourceAssignmentUtils
172                         .getPropertyType(raRuntimeService, entrySchemaType, it.key)
173                     JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
174                 }
175                 // Set the List of Complex Values
176                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
177             }
178         }
179     }
180 }