203b7ea30b10d56c8c81ca5c0d848e874b867bd4
[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.*
33
34 class MockRestResourceResolutionProcessor(private val blueprintRestLibPropertyService:
35                                           MockBluePrintRestLibPropertyService) : ResourceAssignmentProcessor() {
36
37     private val logger = LoggerFactory.getLogger(MockRestResourceResolutionProcessor::class.java)
38
39     override fun resolveInputKeyMappingVariables(inputKeyMapping: Map<String, String>): Map<String, JsonNode> {
40         val resolvedInputKeyMapping = HashMap<String, JsonNode>()
41         if (MapUtils.isNotEmpty(inputKeyMapping)) {
42
43             resolvedInputKeyMapping["service-instance-id"] = "10".asJsonPrimitive()
44             resolvedInputKeyMapping["vnf_name"] = "vnf1".asJsonPrimitive()
45             resolvedInputKeyMapping["vnf-id"] = "123456".asJsonPrimitive()
46         }
47         return resolvedInputKeyMapping
48     }
49
50     override fun getName(): String {
51         return "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
52     }
53
54     override suspend fun processNB(executionRequest: ResourceAssignment) {
55         try {
56             // Check if It has Input
57             if (!setFromInput(executionRequest)) {
58                 val dName = executionRequest.dictionaryName
59                 val dSource = executionRequest.dictionarySource
60                 val resourceDefinition = resourceDictionaries[dName]
61
62                 val resourceSource = resourceDefinition!!.sources[dSource]
63
64                 val resourceSourceProperties = resourceSource!!.properties
65
66                 val sourceProperties =
67                     JacksonUtils.getInstanceFromMap(resourceSourceProperties!!, RestResourceSource::class.java)
68
69                 val path = nullToEmpty(sourceProperties.path)
70                 val inputKeyMapping = sourceProperties.inputKeyMapping
71
72                 val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping!!).toMutableMap()
73
74                 // Resolving content Variables
75                 val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
76                 val urlPath =
77                     resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
78                 val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
79
80                 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
81
82                 // Get the Rest Client Service
83                 val restClientService = blueprintWebClientService(executionRequest)
84
85                 val response = restClientService.exchangeResource(verb, urlPath, payload)
86                 val responseStatusCode = response.status
87                 val responseBody = response.body
88                 if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
89                     populateResource(executionRequest, sourceProperties, responseBody, path)
90                     restClientService.tearDown()
91                 } else {
92                     val errMsg = "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
93                     logger.warn(errMsg)
94                     throw BluePrintProcessorException(errMsg)
95                 }
96             }
97         } catch (e: Exception) {
98             ResourceAssignmentUtils.setFailedResourceDataValue(executionRequest, e.message)
99             throw BluePrintProcessorException("Failed in template resolutionKey ($executionRequest) assignments with: ${e.message}", e)
100         }
101     }
102
103     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ResourceAssignment) {
104         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
105     }
106
107     private fun blueprintWebClientService(resourceAssignment: ResourceAssignment): MockBlueprintWebClientService {
108         return blueprintRestLibPropertyService.mockBlueprintWebClientService(resourceAssignment.dictionarySource!!)
109     }
110
111     @Throws(BluePrintProcessorException::class)
112     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
113                                  restResponse: String, path: String) {
114         val type = nullToEmpty(resourceAssignment.property?.type)
115         lateinit var entrySchemaType: String
116
117         val outputKeyMapping = sourceProperties.outputKeyMapping
118
119         val responseNode = JacksonUtils.jsonNode(restResponse).at(path)
120
121         when (type) {
122             in BluePrintTypes.validPrimitiveTypes() -> {
123                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
124             }
125             in BluePrintTypes.validCollectionTypes() -> {
126                 // Array Types
127                 entrySchemaType = resourceAssignment.property!!.entrySchema!!.type
128                 val arrayNode = responseNode as ArrayNode
129
130                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
131                     val responseArrayNode = responseNode.toList()
132                     for (responseSingleJsonNode in responseArrayNode) {
133
134                         val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
135
136                         outputKeyMapping!!.map {
137                             val responseKeyValue = responseSingleJsonNode.get(it.key)
138                             val propertyTypeForDataType = ResourceAssignmentUtils
139                                 .getPropertyType(raRuntimeService, entrySchemaType, it.key)
140
141                             JacksonUtils.populateJsonNodeValues(
142                                 it.value,
143                                 responseKeyValue, propertyTypeForDataType, arrayChildNode
144                             )
145                         }
146                         arrayNode.add(arrayChildNode)
147                     }
148                 }
149                 // Set the List of Complex Values
150                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
151             }
152             else -> {
153                 // Complex Types
154                 entrySchemaType = resourceAssignment.property!!.type
155                 val objectNode = JacksonUtils.objectMapper.createObjectNode()
156                 outputKeyMapping!!.map {
157                     val responseKeyValue = responseNode.get(it.key)
158                     val propertyTypeForDataType = ResourceAssignmentUtils
159                         .getPropertyType(raRuntimeService, entrySchemaType, it.key)
160                     JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
161                 }
162                 // Set the List of Complex Values
163                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
164             }
165         }
166     }
167 }