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