Merge "BlueprintWebClientService: added return status"
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / resource / resolution / processor / RestResourceResolutionProcessor.kt
1 /*
2  *  Copyright © 2018 IBM.
3  *  Modifications Copyright © 2017-2019 AT&T, Bell Canada
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  */
17
18 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor
19
20 import com.fasterxml.jackson.databind.node.ArrayNode
21 import com.fasterxml.jackson.databind.node.MissingNode
22 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
23 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.RestResourceSource
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
25 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
26 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
27 import org.onap.ccsdk.cds.controllerblueprints.core.*
28 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
29 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
30 import org.slf4j.LoggerFactory
31 import org.springframework.beans.factory.config.ConfigurableBeanFactory
32 import org.springframework.context.annotation.Scope
33 import org.springframework.stereotype.Service
34
35 /**
36  * RestResourceResolutionProcessor
37  *
38  * @author Kapil Singal
39  */
40 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest")
41 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
42 open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService)
43     : ResourceAssignmentProcessor() {
44
45     private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java)
46
47     override fun getName(): String {
48         return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
49     }
50
51     override suspend fun processNB(resourceAssignment: ResourceAssignment) {
52         try {
53             validate(resourceAssignment)
54
55             // Check if It has Input
56             val value = getFromInput(resourceAssignment)
57             if (value == null || value is MissingNode) {
58                 val dName = resourceAssignment.dictionaryName
59                 val dSource = resourceAssignment.dictionarySource
60                 val resourceDefinition = resourceDictionaries[dName]
61                         ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
62
63                 val resourceSource = resourceDefinition.sources[dSource]
64                         ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
65
66                 val resourceSourceProperties =
67                         checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
68
69                 val sourceProperties =
70                         JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java)
71
72                 val path = nullToEmpty(sourceProperties.path)
73                 val inputKeyMapping =
74                     checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
75                 val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping).toMutableMap()
76
77                 // Resolving content Variables
78                 val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
79                 val urlPath =
80                         resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
81                 val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
82
83                 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
84                 // Get the Rest Client Service
85                 val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties)
86
87                 val response = restClientService.exchangeResource(verb, urlPath, payload)
88                 val responseStatusCode = response.status
89                 val responseBody = response.body
90                 if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
91                     populateResource(resourceAssignment, sourceProperties, responseBody, path)
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             // Check the value has populated for mandatory case
99             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
100         } catch (e: Exception) {
101             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
102             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}",
103                     e)
104         }
105     }
106
107     fun blueprintWebClientService(resourceAssignment: ResourceAssignment,
108                                           restResourceSource: RestResourceSource): BlueprintWebClientService {
109         return if (isNotEmpty(restResourceSource.endpointSelector)) {
110             val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!)
111             blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson)
112         } else {
113             blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!)
114         }
115     }
116
117     @Throws(BluePrintProcessorException::class)
118     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
119                                  restResponse: String, path: String) {
120         val dName = resourceAssignment.dictionaryName
121         val dSource = resourceAssignment.dictionarySource
122         val type = nullToEmpty(resourceAssignment.property?.type)
123         lateinit var entrySchemaType: String
124
125         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
126             "failed to get output-key-mappings for $dName under $dSource properties"
127         }
128         logger.info("Response processing type($type)")
129
130         val responseNode = checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) {
131             "Failed to find path ($path) in response ($restResponse)"
132         }
133         logger.info("populating value for output mapping ($outputKeyMapping), from json ($responseNode)")
134
135
136         when (type) {
137             in BluePrintTypes.validPrimitiveTypes() -> {
138                 logger.info("For template key (${resourceAssignment.name}) setting value as ($responseNode)")
139                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
140             }
141             in BluePrintTypes.validCollectionTypes() -> {
142                 // Array Types
143                 entrySchemaType = checkNotEmpty(resourceAssignment.property?.entrySchema?.type) {
144                     "Entry schema is not defined for dictionary ($dName) info"
145                 }
146                 val arrayNode = responseNode as ArrayNode
147
148                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
149
150                     val responseArrayNode = responseNode.toList()
151                     for (responseSingleJsonNode in responseArrayNode) {
152
153                         val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
154
155                         outputKeyMapping.map {
156                             val responseKeyValue = responseSingleJsonNode.get(it.key)
157                             val propertyTypeForDataType = ResourceAssignmentUtils
158                                     .getPropertyType(raRuntimeService, entrySchemaType, it.key)
159
160                             logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), " +
161                                     "type  ({$propertyTypeForDataType})")
162
163                             JacksonUtils.populateJsonNodeValues(it.value,
164                                     responseKeyValue, propertyTypeForDataType, arrayChildNode)
165                         }
166                         arrayNode.add(arrayChildNode)
167                     }
168                 }
169                 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
170                 // Set the List of Complex Values
171                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
172             }
173             else -> {
174                 // Complex Types
175                 entrySchemaType = checkNotEmpty(resourceAssignment.property?.type) {
176                     "Entry schema is not defined for dictionary ($dName) info"
177                 }
178                 val objectNode = JacksonUtils.objectMapper.createObjectNode()
179                 outputKeyMapping.map {
180                     val responseKeyValue = responseNode.get(it.key)
181                     val propertyTypeForDataType = ResourceAssignmentUtils
182                             .getPropertyType(raRuntimeService, entrySchemaType, it.key)
183
184                     logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type  ({$propertyTypeForDataType})")
185                     JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
186                 }
187
188                 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
189                 // Set the List of Complex Values
190                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
191             }
192         }
193     }
194
195     @Throws(BluePrintProcessorException::class)
196     private fun validate(resourceAssignment: ResourceAssignment) {
197         checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
198         checkNotEmpty(resourceAssignment.dictionaryName) {
199             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
200         }
201         checkNotEmpty(resourceAssignment.dictionarySource) {
202             "resource assignment dictionary source is not defined for template key (${resourceAssignment.name})"
203         }
204     }
205
206     override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
207         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
208     }
209
210 }