Migrate "ms/controllerblueprints" from ccsdk/apps
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / apps / blueprintsprocessor / functions / resource / resolution / processor / RestResourceResolutionProcessor.kt
1 /*
2  *  Copyright © 2018 IBM.
3  *  Modifications Copyright © 2017-2018 AT&T Intellectual Property.
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.apps.blueprintsprocessor.functions.resource.resolution.processor
19
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.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
24 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.RestResourceSource
25 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
26 import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
27 import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BlueprintWebClientService
28 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException
29 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintTypes
30 import org.onap.ccsdk.apps.controllerblueprints.core.checkEqualsOrThrow
31 import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmpty
32 import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyOrThrow
33 import org.onap.ccsdk.apps.controllerblueprints.core.nullToEmpty
34 import org.onap.ccsdk.apps.controllerblueprints.core.returnNotEmptyOrThrow
35 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
36 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
37 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants
38 import org.slf4j.LoggerFactory
39 import org.springframework.beans.factory.config.ConfigurableBeanFactory
40 import org.springframework.context.annotation.Scope
41 import org.springframework.stereotype.Service
42
43 /**
44  * RestResourceResolutionProcessor
45  *
46  * @author Kapil Singal
47  */
48 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest")
49 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
50 open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService)
51     : ResourceAssignmentProcessor() {
52
53     private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java)
54
55     override fun getName(): String {
56         return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
57     }
58
59     override fun process(resourceAssignment: ResourceAssignment) {
60         try {
61             validate(resourceAssignment)
62
63             // Check if It has Input
64             val value = getFromInput(resourceAssignment)
65             if (value == null || value is MissingNode) {
66                 val dName = resourceAssignment.dictionaryName
67                 val dSource = resourceAssignment.dictionarySource
68                 val resourceDefinition = resourceDictionaries[dName]
69                     ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
70                 val resourceSource = resourceDefinition.sources[dSource]
71                     ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
72                 val resourceSourceProperties =
73                     checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
74                 val sourceProperties =
75                     JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java)
76                 val path = nullToEmpty(sourceProperties.path)
77                 val inputKeyMapping =
78                     checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
79                 val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping)
80
81                 // Resolving content Variables
82                 val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
83                 val urlPath =
84                     resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
85                 val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
86
87                 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
88                 // Get the Rest Client Service
89                 val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties)
90
91                 val response = restClientService.exchangeResource(verb, urlPath, payload)
92                 if (response.isBlank()) {
93                     logger.warn("Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath)")
94                 } else {
95                     populateResource(resourceAssignment, sourceProperties, response, path)
96                 }
97             }
98             // Check the value has populated for mandatory case
99             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
100         } catch (e: Exception) {
101             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
102             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}",
103                 e)
104         }
105     }
106
107     private fun blueprintWebClientService(resourceAssignment: ResourceAssignment,
108                                           restResourceSource: RestResourceSource): BlueprintWebClientService {
109         return if (checkNotEmpty(restResourceSource.endpointSelector)) {
110             val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!)
111             blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson)
112         } else {
113             blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!)
114         }
115     }
116
117     @Throws(BluePrintProcessorException::class)
118     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
119                                  restResponse: String, path: String) {
120         val dName = resourceAssignment.dictionaryName
121         val dSource = resourceAssignment.dictionarySource
122         val type = nullToEmpty(resourceAssignment.property?.type)
123         lateinit var entrySchemaType: String
124
125         val outputKeyMapping =
126             checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" }
127         logger.info("Response processing type($type)")
128
129         val responseNode =
130             checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) { "Failed to find path ($path) in response ($restResponse)" }
131         logger.info("populating value for output mapping ($outputKeyMapping), from json ($responseNode)")
132
133
134         when (type) {
135             in BluePrintTypes.validPrimitiveTypes() -> {
136                 logger.info("For template key (${resourceAssignment.name}) setting value as ($responseNode)")
137                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
138             }
139             in BluePrintTypes.validCollectionTypes() -> {
140                 // Array Types
141                 entrySchemaType =
142                     returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" }
143                 val arrayNode = responseNode as ArrayNode
144
145                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
146                     val responseArrayNode = responseNode.toList()
147                     for (responseSingleJsonNode in responseArrayNode) {
148                         val arrayChildNode = JsonNodeFactory.instance.objectNode()
149                         outputKeyMapping.map {
150                             val responseKeyValue = responseSingleJsonNode.get(it.key)
151                             val propertyTypeForDataType =
152                                 ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key)
153                             logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type  ({$propertyTypeForDataType})")
154                             JacksonUtils.populateJsonNodeValues(it.value,
155                                 responseKeyValue,
156                                 propertyTypeForDataType,
157                                 arrayChildNode)
158                         }
159                         arrayNode.add(arrayChildNode)
160                     }
161                 }
162                 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
163                 // Set the List of Complex Values
164                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
165             }
166             else -> {
167                 // Complex Types
168                 entrySchemaType =
169                     returnNotEmptyOrThrow(resourceAssignment.property?.type) { "Entry schema is not defined for dictionary ($dName) info" }
170                 val objectNode = JsonNodeFactory.instance.objectNode()
171                 outputKeyMapping.map {
172                     val responseKeyValue = responseNode.get(it.key)
173                     val propertyTypeForDataType =
174                         ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key)
175                     logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type  ({$propertyTypeForDataType})")
176                     JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
177                 }
178
179                 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
180                 // Set the List of Complex Values
181                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
182             }
183         }
184     }
185
186     @Throws(BluePrintProcessorException::class)
187     private fun validate(resourceAssignment: ResourceAssignment) {
188         checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined")
189         checkNotEmptyOrThrow(resourceAssignment.dictionaryName,
190             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
191         checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA,
192             resourceAssignment.dictionarySource) {
193             "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA} but it is ${resourceAssignment.dictionarySource}"
194         }
195         checkNotEmptyOrThrow(resourceAssignment.dictionaryName,
196             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
197     }
198
199     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
200         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
201     }
202
203
204 }