2 * Copyright © 2018 IBM.
3 * Modifications Copyright © 2017-2018 AT&T Intellectual Property.
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.JsonNodeFactory
22 import com.fasterxml.jackson.databind.node.MissingNode
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.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants
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
38 * RestResourceResolutionProcessor
40 * @author Kapil Singal
42 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest")
43 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
44 open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService)
45 : ResourceAssignmentProcessor() {
47 private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java)
49 override fun getName(): String {
50 return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
53 override suspend fun processNB(resourceAssignment: ResourceAssignment) {
55 validate(resourceAssignment)
57 // Check if It has Input
58 val value = getFromInput(resourceAssignment)
59 if (value == null || value is MissingNode) {
60 val dName = resourceAssignment.dictionaryName
61 val dSource = resourceAssignment.dictionarySource
62 val resourceDefinition = resourceDictionaries[dName]
63 ?: 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)")
66 val resourceSourceProperties =
67 checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
68 val sourceProperties =
69 JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java)
70 val path = nullToEmpty(sourceProperties.path)
72 checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
73 val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping)
75 // Resolving content Variables
76 val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
78 resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
79 val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
81 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
82 // Get the Rest Client Service
83 val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties)
85 val response = restClientService.exchangeResource(verb, urlPath, payload)
86 if (response.isBlank()) {
87 logger.warn("Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath)")
89 populateResource(resourceAssignment, sourceProperties, response, path)
92 // Check the value has populated for mandatory case
93 ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
94 } catch (e: Exception) {
95 ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
96 throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}",
101 private fun blueprintWebClientService(resourceAssignment: ResourceAssignment,
102 restResourceSource: RestResourceSource): BlueprintWebClientService {
103 return if (isNotEmpty(restResourceSource.endpointSelector)) {
104 val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!)
105 blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson)
107 blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!)
111 @Throws(BluePrintProcessorException::class)
112 private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
113 restResponse: String, path: String) {
114 val dName = resourceAssignment.dictionaryName
115 val dSource = resourceAssignment.dictionarySource
116 val type = nullToEmpty(resourceAssignment.property?.type)
117 lateinit var entrySchemaType: String
119 val outputKeyMapping =
120 checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" }
121 logger.info("Response processing type($type)")
124 checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) { "Failed to find path ($path) in response ($restResponse)" }
125 logger.info("populating value for output mapping ($outputKeyMapping), from json ($responseNode)")
129 in BluePrintTypes.validPrimitiveTypes() -> {
130 logger.info("For template key (${resourceAssignment.name}) setting value as ($responseNode)")
131 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
133 in BluePrintTypes.validCollectionTypes() -> {
136 checkNotEmpty(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" }
137 val arrayNode = responseNode as ArrayNode
139 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
140 val responseArrayNode = responseNode.toList()
141 for (responseSingleJsonNode in responseArrayNode) {
142 val arrayChildNode = JsonNodeFactory.instance.objectNode()
143 outputKeyMapping.map {
144 val responseKeyValue = responseSingleJsonNode.get(it.key)
145 val propertyTypeForDataType =
146 ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key)
147 logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type ({$propertyTypeForDataType})")
148 JacksonUtils.populateJsonNodeValues(it.value,
150 propertyTypeForDataType,
153 arrayNode.add(arrayChildNode)
156 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
157 // Set the List of Complex Values
158 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
163 checkNotEmpty(resourceAssignment.property?.type) { "Entry schema is not defined for dictionary ($dName) info" }
164 val objectNode = JsonNodeFactory.instance.objectNode()
165 outputKeyMapping.map {
166 val responseKeyValue = responseNode.get(it.key)
167 val propertyTypeForDataType =
168 ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key)
169 logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type ({$propertyTypeForDataType})")
170 JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
173 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
174 // Set the List of Complex Values
175 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
180 @Throws(BluePrintProcessorException::class)
181 private fun validate(resourceAssignment: ResourceAssignment) {
182 checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
183 checkNotEmpty(resourceAssignment.dictionaryName) {
184 "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
186 checkEquals(ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA, resourceAssignment.dictionarySource) {
187 "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA} but it is " +
188 "${resourceAssignment.dictionarySource}"
190 checkNotEmpty(resourceAssignment.dictionaryName) {
191 "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
195 override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
196 raRuntimeService.getBluePrintError().addError(runtimeException.message!!)