2 * Copyright © 2018 - 2020 IBM.
3 * Modifications Copyright © 2017-2020 AT&T, Bell Canada
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor
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.blueprintsprocessor.services.execution.ExecutionServiceDomains
26 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
27 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
28 import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
29 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
30 import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
31 import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage
32 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
33 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.KeyIdentifier
34 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
35 import org.slf4j.LoggerFactory
36 import org.springframework.beans.factory.config.ConfigurableBeanFactory
37 import org.springframework.context.annotation.Scope
38 import org.springframework.stereotype.Service
41 * RestResourceResolutionProcessor
43 * @author Kapil Singal
45 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest")
46 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
47 open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService) :
48 ResourceAssignmentProcessor() {
50 private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java)
52 override fun getName(): String {
53 return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
56 override suspend fun processNB(resourceAssignment: ResourceAssignment) {
58 validate(resourceAssignment)
60 // Check if It has Input
61 if (!setFromInput(resourceAssignment)) {
62 val dName = resourceAssignment.dictionaryName!!
63 val dSource = resourceAssignment.dictionarySource!!
64 val resourceDefinition = resourceDefinition(dName)
66 /** Check Resource Assignment has the source definitions, If not get from Resource Definitions **/
67 val resourceSource = resourceAssignment.dictionarySourceDefinition
68 ?: resourceDefinition?.sources?.get(dSource)
69 ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
71 val resourceSourceProperties =
72 checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
74 val sourceProperties =
75 JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java)
77 val path = nullToEmpty(sourceProperties.path)
79 checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
80 val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping).toMutableMap()
82 inputKeyMapping?.mapValues { raRuntimeService.getDictionaryStore(it.value) }
83 ?.map { KeyIdentifier(it.key, it.value) }
84 ?.let { resourceAssignment.keyIdentifiers.addAll(it) }
86 // Resolving content Variables
87 val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
88 resourceSourceProperties["resolved-payload"] = JacksonUtils.jsonNode(payload)
90 resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
91 val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
94 "RestResource ($dSource) dictionary information: " +
95 "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
97 val requestHeaders = sourceProperties.headers
98 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
99 // Get the Rest Client Service
100 val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties)
102 val response = restClientService.exchangeResource(verb, urlPath, payload, requestHeaders.toMap())
103 val responseStatusCode = response.status
104 val responseBody = response.body
105 val outputKeyMapping = sourceProperties.outputKeyMapping
106 if (responseStatusCode in 200..299 && outputKeyMapping.isNullOrEmpty()) {
107 resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS
108 logger.info("AS>> outputKeyMapping==null, will not populateResource")
109 } else if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
110 populateResource(resourceAssignment, sourceProperties, responseBody, path)
113 "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
115 throw BluePrintProcessorException(errMsg)
118 // Check the value has populated for mandatory case
119 ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
120 } catch (e: BluePrintProcessorException) {
121 val errorMsg = "Failed to process REST resource resolution in template key ($resourceAssignment) assignments."
122 ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, errorMsg)
123 throw e.updateErrorMessage(ExecutionServiceDomains.RESOURCE_RESOLUTION, errorMsg,
124 "Wrong resource definition or resolution failed.")
125 } catch (e: Exception) {
126 ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
127 throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
131 fun blueprintWebClientService(
132 resourceAssignment: ResourceAssignment,
133 restResourceSource: RestResourceSource
134 ): BlueprintWebClientService {
135 return if (isNotEmpty(restResourceSource.endpointSelector)) {
136 val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!)
137 blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson)
139 blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!)
143 @Throws(BluePrintProcessorException::class)
144 private fun populateResource(
145 resourceAssignment: ResourceAssignment,
146 sourceProperties: RestResourceSource,
147 restResponse: String,
150 val dName = resourceAssignment.dictionaryName
151 val dSource = resourceAssignment.dictionarySource
152 val type = nullToEmpty(resourceAssignment.property?.type)
153 val metadata = resourceAssignment.property!!.metadata
155 val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
156 "failed to get output-key-mappings for $dName under $dSource properties"
158 logger.info("Response processing type ($type)")
160 val responseNode = checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) {
161 "Failed to find path ($path) in response ($restResponse)"
164 val valueToPrint = ResourceAssignmentUtils.getValueToLog(metadata, responseNode)
165 logger.info("populating value for output mapping ($outputKeyMapping), from json ($valueToPrint)")
167 val parsedResponseNode = ResourceAssignmentUtils.parseResponseNode(
168 responseNode, resourceAssignment,
169 raRuntimeService, outputKeyMapping
172 // Set the List of Complex Values
173 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, parsedResponseNode)
176 @Throws(BluePrintProcessorException::class)
177 private fun validate(resourceAssignment: ResourceAssignment) {
178 checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
179 checkNotEmpty(resourceAssignment.dictionaryName) {
180 "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
182 checkNotEmpty(resourceAssignment.dictionarySource) {
183 "resource assignment dictionary source is not defined for template key (${resourceAssignment.name})"
187 override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
188 raRuntimeService.getBluePrintError().addError(runtimeException.message!!)