Formatting Code base with ktlint
[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("Failed in template resolutionKey ($executionRequest) assignments with: ${e.message}", e)
106         }
107     }
108
109     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ResourceAssignment) {
110         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
111     }
112
113     private fun blueprintWebClientService(resourceAssignment: ResourceAssignment): MockBlueprintWebClientService {
114         return blueprintRestLibPropertyService.mockBlueprintWebClientService(resourceAssignment.dictionarySource!!)
115     }
116
117     @Throws(BluePrintProcessorException::class)
118     private fun populateResource(
119         resourceAssignment: ResourceAssignment,
120         sourceProperties: RestResourceSource,
121         restResponse: String,
122         path: String
123     ) {
124         val type = nullToEmpty(resourceAssignment.property?.type)
125         lateinit var entrySchemaType: String
126
127         val outputKeyMapping = sourceProperties.outputKeyMapping
128
129         val responseNode = JacksonUtils.jsonNode(restResponse).at(path)
130
131         when (type) {
132             in BluePrintTypes.validPrimitiveTypes() -> {
133                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
134             }
135             in BluePrintTypes.validCollectionTypes() -> {
136                 // Array Types
137                 entrySchemaType = resourceAssignment.property!!.entrySchema!!.type
138                 val arrayNode = responseNode as ArrayNode
139
140                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
141                     val responseArrayNode = responseNode.toList()
142                     for (responseSingleJsonNode in responseArrayNode) {
143
144                         val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
145
146                         outputKeyMapping!!.map {
147                             val responseKeyValue = responseSingleJsonNode.get(it.key)
148                             val propertyTypeForDataType = ResourceAssignmentUtils
149                                 .getPropertyType(raRuntimeService, entrySchemaType, it.key)
150
151                             JacksonUtils.populateJsonNodeValues(
152                                 it.value,
153                                 responseKeyValue, propertyTypeForDataType, arrayChildNode
154                             )
155                         }
156                         arrayNode.add(arrayChildNode)
157                     }
158                 }
159                 // Set the List of Complex Values
160                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
161             }
162             else -> {
163                 // Complex Types
164                 entrySchemaType = resourceAssignment.property!!.type
165                 val objectNode = JacksonUtils.objectMapper.createObjectNode()
166                 outputKeyMapping!!.map {
167                     val responseKeyValue = responseNode.get(it.key)
168                     val propertyTypeForDataType = ResourceAssignmentUtils
169                         .getPropertyType(raRuntimeService, entrySchemaType, it.key)
170                     JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
171                 }
172                 // Set the List of Complex Values
173                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
174             }
175         }
176     }
177 }