eb2a7a7ed0e6535e8535614c3d49ec6a1b204284
[ccsdk/cds.git] /
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                 val responseStatusCode = response.status
84                 val responseBody = response.body
85                 if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
86                     populateResource(executionRequest, sourceProperties, responseBody, path)
87                     restClientService.tearDown()
88                 } else {
89                     val errMsg = "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
90                     logger.warn(errMsg)
91                     throw BluePrintProcessorException(errMsg)
92                 }
93             }
94         } catch (e: Exception) {
95             ResourceAssignmentUtils.setFailedResourceDataValue(executionRequest, e.message)
96             throw BluePrintProcessorException("Failed in template key ($executionRequest) assignments with: ${e.message}",
97                     e)
98         }
99     }
100
101     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ResourceAssignment) {
102         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
103     }
104
105     private fun blueprintWebClientService(resourceAssignment: ResourceAssignment): MockBlueprintWebClientService {
106         return blueprintRestLibPropertyService.mockBlueprintWebClientService(resourceAssignment.dictionarySource!!)
107     }
108
109     @Throws(BluePrintProcessorException::class)
110     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
111                                  restResponse: String, path: String) {
112         val type = nullToEmpty(resourceAssignment.property?.type)
113         lateinit var entrySchemaType: String
114
115         val outputKeyMapping = sourceProperties.outputKeyMapping
116
117         val responseNode = JacksonUtils.jsonNode(restResponse).at(path)
118
119         when (type) {
120             in BluePrintTypes.validPrimitiveTypes() -> {
121                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
122             }
123             in BluePrintTypes.validCollectionTypes() -> {
124                 // Array Types
125                 entrySchemaType = resourceAssignment.property!!.entrySchema!!.type
126                 val arrayNode = responseNode as ArrayNode
127
128                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
129                     val responseArrayNode = responseNode.toList()
130                     for (responseSingleJsonNode in responseArrayNode) {
131
132                         val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
133
134                         outputKeyMapping!!.map {
135                             val responseKeyValue = responseSingleJsonNode.get(it.key)
136                             val propertyTypeForDataType = ResourceAssignmentUtils
137                                     .getPropertyType(raRuntimeService, entrySchemaType, it.key)
138
139                             JacksonUtils.populateJsonNodeValues(it.value,
140                                     responseKeyValue, propertyTypeForDataType, arrayChildNode)
141                         }
142                         arrayNode.add(arrayChildNode)
143                     }
144                 }
145                 // Set the List of Complex Values
146                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
147             }
148             else -> {
149                 // Complex Types
150                 entrySchemaType = resourceAssignment.property!!.type
151                 val objectNode = JacksonUtils.objectMapper.createObjectNode()
152                 outputKeyMapping!!.map {
153                     val responseKeyValue = responseNode.get(it.key)
154                     val propertyTypeForDataType = ResourceAssignmentUtils
155                             .getPropertyType(raRuntimeService, entrySchemaType, it.key)
156                     JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
157                 }
158                 // Set the List of Complex Values
159                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
160             }
161         }
162     }
163 }