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