Eliminate Template Requirement
[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 org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
21 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.RestResourceSource
22 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
23 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
24 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
25 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
26 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
27 import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
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.KeyIdentifier
31 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
32 import org.slf4j.LoggerFactory
33 import org.springframework.beans.factory.config.ConfigurableBeanFactory
34 import org.springframework.context.annotation.Scope
35 import org.springframework.stereotype.Service
36
37 /**
38  * RestResourceResolutionProcessor
39  *
40  * @author Kapil Singal
41  */
42 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest")
43 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
44 open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService) :
45     ResourceAssignmentProcessor() {
46
47     private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java)
48
49     override fun getName(): String {
50         return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
51     }
52
53     override suspend fun processNB(resourceAssignment: ResourceAssignment) {
54         try {
55             validate(resourceAssignment)
56
57             // Check if It has Input
58             if (!setFromInput(resourceAssignment)) {
59                 val dName = resourceAssignment.dictionaryName!!
60                 val dSource = resourceAssignment.dictionarySource!!
61                 val resourceDefinition = resourceDefinition(dName)
62
63                 /** Check Resource Assignment has the source definitions, If not get from Resource Definitions **/
64                 val resourceSource = resourceAssignment.dictionarySourceDefinition
65                     ?: resourceDefinition?.sources?.get(dSource)
66                     ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
67
68                 val resourceSourceProperties =
69                     checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
70
71                 val sourceProperties =
72                     JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java)
73
74                 val path = nullToEmpty(sourceProperties.path)
75                 val inputKeyMapping =
76                     checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
77                 val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping).toMutableMap()
78
79                 sourceProperties.inputKeyMapping
80                         ?.mapValues { raRuntimeService.getDictionaryStore(it.value) }
81                         ?.map { KeyIdentifier(it.key, it.value) }
82                         ?.let { resourceAssignment.keyIdentifiers.addAll(it) }
83
84                 // Resolving content Variables
85                 val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
86                 val urlPath =
87                     resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
88                 val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
89
90                 logger.info(
91                     "RestResource ($dSource) dictionary information: " +
92                             "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
93                 )
94                 val requestHeaders = sourceProperties.headers
95                 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
96                 // Get the Rest Client Service
97                 val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties)
98
99                 val response = restClientService.exchangeResource(verb, urlPath, payload, requestHeaders.toMap())
100                 val responseStatusCode = response.status
101                 val responseBody = response.body
102                 val outputKeyMapping = sourceProperties.outputKeyMapping
103                 if (responseStatusCode in 200..299 && outputKeyMapping.isNullOrEmpty()) {
104                     logger.info("AS>> outputKeyMapping==null, will not populateResource")
105                 } else if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
106                     populateResource(resourceAssignment, sourceProperties, responseBody, path)
107                 } else {
108                     val errMsg =
109                         "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
110                     logger.warn(errMsg)
111                     throw BluePrintProcessorException(errMsg)
112                 }
113             }
114             // Check the value has populated for mandatory case
115             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
116         } catch (e: Exception) {
117             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
118             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
119         }
120     }
121
122     fun blueprintWebClientService(
123         resourceAssignment: ResourceAssignment,
124         restResourceSource: RestResourceSource
125     ): BlueprintWebClientService {
126         return if (isNotEmpty(restResourceSource.endpointSelector)) {
127             val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!)
128             blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson)
129         } else {
130             blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!)
131         }
132     }
133
134     @Throws(BluePrintProcessorException::class)
135     private fun populateResource(
136         resourceAssignment: ResourceAssignment,
137         sourceProperties: RestResourceSource,
138         restResponse: String,
139         path: String
140     ) {
141         val dName = resourceAssignment.dictionaryName
142         val dSource = resourceAssignment.dictionarySource
143         val type = nullToEmpty(resourceAssignment.property?.type)
144         val metadata = resourceAssignment.property!!.metadata
145
146         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
147             "failed to get output-key-mappings for $dName under $dSource properties"
148         }
149         logger.info("Response processing type ($type)")
150
151         val responseNode = checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) {
152             "Failed to find path ($path) in response ($restResponse)"
153         }
154
155         val valueToPrint = ResourceAssignmentUtils.getValueToLog(metadata, responseNode)
156         logger.info("populating value for output mapping ($outputKeyMapping), from json ($valueToPrint)")
157
158         val parsedResponseNode = ResourceAssignmentUtils.parseResponseNode(
159             responseNode, resourceAssignment,
160             raRuntimeService, outputKeyMapping
161         )
162
163         // Set the List of Complex Values
164         ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, parsedResponseNode)
165     }
166
167     @Throws(BluePrintProcessorException::class)
168     private fun validate(resourceAssignment: ResourceAssignment) {
169         checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
170         checkNotEmpty(resourceAssignment.dictionaryName) {
171             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
172         }
173         checkNotEmpty(resourceAssignment.dictionarySource) {
174             "resource assignment dictionary source is not defined for template key (${resourceAssignment.name})"
175         }
176     }
177
178     override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
179         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
180     }
181 }