Fixing distribution and properties
[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("MockRestResource ($dSource) dictionary information: " +
81                         "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})")
82
83                 // Get the Rest Client Service
84                 val restClientService = blueprintWebClientService(executionRequest)
85
86                 val response = restClientService.exchangeResource(verb, urlPath, payload)
87                 val responseStatusCode = response.status
88                 val responseBody = response.body
89                 if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
90                     populateResource(executionRequest, sourceProperties, responseBody, path)
91                     restClientService.tearDown()
92                 } else {
93                     val errMsg = "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
94                     logger.warn(errMsg)
95                     throw BluePrintProcessorException(errMsg)
96                 }
97             }
98         } catch (e: Exception) {
99             ResourceAssignmentUtils.setFailedResourceDataValue(executionRequest, e.message)
100             throw BluePrintProcessorException("Failed in template resolutionKey ($executionRequest) assignments with: ${e.message}", e)
101         }
102     }
103
104     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ResourceAssignment) {
105         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
106     }
107
108     private fun blueprintWebClientService(resourceAssignment: ResourceAssignment): MockBlueprintWebClientService {
109         return blueprintRestLibPropertyService.mockBlueprintWebClientService(resourceAssignment.dictionarySource!!)
110     }
111
112     @Throws(BluePrintProcessorException::class)
113     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
114                                  restResponse: String, path: String) {
115         val type = nullToEmpty(resourceAssignment.property?.type)
116         lateinit var entrySchemaType: String
117
118         val outputKeyMapping = sourceProperties.outputKeyMapping
119
120         val responseNode = JacksonUtils.jsonNode(restResponse).at(path)
121
122         when (type) {
123             in BluePrintTypes.validPrimitiveTypes() -> {
124                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
125             }
126             in BluePrintTypes.validCollectionTypes() -> {
127                 // Array Types
128                 entrySchemaType = resourceAssignment.property!!.entrySchema!!.type
129                 val arrayNode = responseNode as ArrayNode
130
131                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
132                     val responseArrayNode = responseNode.toList()
133                     for (responseSingleJsonNode in responseArrayNode) {
134
135                         val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
136
137                         outputKeyMapping!!.map {
138                             val responseKeyValue = responseSingleJsonNode.get(it.key)
139                             val propertyTypeForDataType = ResourceAssignmentUtils
140                                 .getPropertyType(raRuntimeService, entrySchemaType, it.key)
141
142                             JacksonUtils.populateJsonNodeValues(
143                                 it.value,
144                                 responseKeyValue, propertyTypeForDataType, arrayChildNode
145                             )
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 }