2 * Copyright © 2018 IBM.
3 * Modifications Copyright © 2017-2019 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 com.fasterxml.jackson.databind.node.ArrayNode
21 import com.fasterxml.jackson.databind.node.MissingNode
22 import com.fasterxml.jackson.databind.node.NullNode
23 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.RestResourceSource
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
26 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
27 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
28 import org.onap.ccsdk.cds.controllerblueprints.core.*
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
37 * RestResourceResolutionProcessor
39 * @author Kapil Singal
41 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest")
42 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
43 open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService)
44 : ResourceAssignmentProcessor() {
46 private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java)
48 override fun getName(): String {
49 return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
52 override suspend fun processNB(resourceAssignment: ResourceAssignment) {
54 validate(resourceAssignment)
56 // Check if It has Input
57 val value = getFromInput(resourceAssignment)
58 if (value == null || value is MissingNode || value is NullNode) {
59 val dName = resourceAssignment.dictionaryName
60 val dSource = resourceAssignment.dictionarySource
61 val resourceDefinition = resourceDictionaries[dName]
62 ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
64 val resourceSource = resourceDefinition.sources[dSource]
65 ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
67 val resourceSourceProperties =
68 checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
70 val sourceProperties =
71 JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java)
73 val path = nullToEmpty(sourceProperties.path)
75 checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
76 val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping).toMutableMap()
78 // Resolving content Variables
79 val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
81 resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
82 val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
84 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
85 // Get the Rest Client Service
86 val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties)
88 val response = restClientService.exchangeResource(verb, urlPath, payload)
89 val responseStatusCode = response.status
90 val responseBody = response.body
91 if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
92 populateResource(resourceAssignment, sourceProperties, responseBody, path)
95 "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
97 throw BluePrintProcessorException(errMsg)
100 // Check the value has populated for mandatory case
101 ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
102 } catch (e: Exception) {
103 ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
104 throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}",
109 fun blueprintWebClientService(resourceAssignment: ResourceAssignment,
110 restResourceSource: RestResourceSource): BlueprintWebClientService {
111 return if (isNotEmpty(restResourceSource.endpointSelector)) {
112 val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!)
113 blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson)
115 blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!)
119 @Throws(BluePrintProcessorException::class)
120 private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
121 restResponse: String, path: String) {
122 val dName = resourceAssignment.dictionaryName
123 val dSource = resourceAssignment.dictionarySource
124 val type = nullToEmpty(resourceAssignment.property?.type)
125 lateinit var entrySchemaType: String
127 val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
128 "failed to get output-key-mappings for $dName under $dSource properties"
130 logger.info("Response processing type($type)")
132 val responseNode = checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) {
133 "Failed to find path ($path) in response ($restResponse)"
135 logger.info("populating value for output mapping ($outputKeyMapping), from json ($responseNode)")
139 in BluePrintTypes.validPrimitiveTypes() -> {
140 logger.info("For template key (${resourceAssignment.name}) setting value as ($responseNode)")
141 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
143 in BluePrintTypes.validCollectionTypes() -> {
145 entrySchemaType = checkNotEmpty(resourceAssignment.property?.entrySchema?.type) {
146 "Entry schema is not defined for dictionary ($dName) info"
148 val arrayNode = JacksonUtils.objectMapper.createArrayNode()
150 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
152 val responseArrayNode = responseNode.toList()
153 for (responseSingleJsonNode in responseArrayNode) {
155 val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
157 outputKeyMapping.map {
158 val responseKeyValue = responseSingleJsonNode.get(it.key)
159 val propertyTypeForDataType = ResourceAssignmentUtils
160 .getPropertyType(raRuntimeService, entrySchemaType, it.key)
162 logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), " +
163 "type ({$propertyTypeForDataType})")
165 JacksonUtils.populateJsonNodeValues(it.value,
166 responseKeyValue, propertyTypeForDataType, arrayChildNode)
168 arrayNode.add(arrayChildNode)
171 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
172 // Set the List of Complex Values
173 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
177 entrySchemaType = checkNotEmpty(resourceAssignment.property?.type) {
178 "Entry schema is not defined for dictionary ($dName) info"
180 val objectNode = JacksonUtils.objectMapper.createObjectNode()
181 outputKeyMapping.map {
182 val responseKeyValue = responseNode.get(it.key)
183 val propertyTypeForDataType = ResourceAssignmentUtils
184 .getPropertyType(raRuntimeService, entrySchemaType, it.key)
186 logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type ({$propertyTypeForDataType})")
187 JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
190 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
191 // Set the List of Complex Values
192 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
197 @Throws(BluePrintProcessorException::class)
198 private fun validate(resourceAssignment: ResourceAssignment) {
199 checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
200 checkNotEmpty(resourceAssignment.dictionaryName) {
201 "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
203 checkNotEmpty(resourceAssignment.dictionarySource) {
204 "resource assignment dictionary source is not defined for template key (${resourceAssignment.name})"
208 override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
209 raRuntimeService.getBluePrintError().addError(runtimeException.message!!)