Resource Resolution Service: Source Rest
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / apps / blueprintsprocessor / functions / resource / resolution / processor / SimpleRestResourceAssignmentProcessor.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.NullNode
23 import com.fasterxml.jackson.databind.node.ObjectNode
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.controllerblueprints.core.*
28 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
29 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
30 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants
31 import org.slf4j.LoggerFactory
32 import org.springframework.stereotype.Service
33
34 /**
35  * SimpleRestResourceAssignmentProcessor
36  *
37  * @author Kapil Singal
38  */
39 @Service("resource-assignment-processor-primary-config-data")
40 open class SimpleRestResourceAssignmentProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService)
41     : ResourceAssignmentProcessor() {
42
43     private val logger = LoggerFactory.getLogger(SimpleRestResourceAssignmentProcessor::class.java)
44
45     override fun getName(): String {
46         return "resource-assignment-processor-primary-config-data"
47     }
48
49     override fun process(resourceAssignment: ResourceAssignment) {
50         try {
51             validate(resourceAssignment)
52
53             // Check if It has Input
54             val value = raRuntimeService.getInputValue(resourceAssignment.name)
55             if (value != null && value !is NullNode) {
56                 logger.info("primary-db source template key (${resourceAssignment.name}) found from input and value is ($value)")
57                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
58             } else {
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")
63                 val resourceSource = resourceDefinition.sources[dSource]
64                         ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
65                 val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
66                 val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java)
67
68                 val urlPath = checkNotNull(sourceProperties.urlPath) { "failed to get request urlPath for $dName under $dSource properties" }
69                 val path = nullToEmpty(sourceProperties.path)
70                 val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
71
72                 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
73
74                 val restClientService = blueprintRestLibPropertyService.blueprintWebClientService("primary-config-data")
75                 val response = restClientService.getResource(urlPath, String::class.java)
76                 if (response.isNotBlank()) {
77                     logger.warn("Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath)")
78                 } else {
79                     populateResource(resourceAssignment, sourceProperties, response, path)
80                 }
81             }
82             // Check the value has populated for mandatory case
83             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
84         } catch (e: Exception) {
85             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
86             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
87         }
88     }
89
90     @Throws(BluePrintProcessorException::class)
91     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource, restResponse: String, path: String) {
92         val dName = resourceAssignment.dictionaryName
93         val dSource = resourceAssignment.dictionarySource
94         val type = nullToEmpty(resourceAssignment.property?.type)
95         lateinit var entrySchemaType: String
96
97         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" }
98         logger.info("Response processing type($type)")
99
100         val responseNode = checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) { "Failed to find path ($path) in response ($restResponse)" }
101         logger.info("populating value for output mapping ($outputKeyMapping), from json ($responseNode)")
102
103
104         when (type) {
105             in BluePrintTypes.validPrimitiveTypes() -> {
106                 logger.info("For template key (${resourceAssignment.name}) setting value as ($responseNode)")
107                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
108             }
109             in BluePrintTypes.validCollectionTypes() -> {
110                 // Array Types
111                 entrySchemaType = returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" }
112                 val arrayNode = responseNode as ArrayNode
113
114                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
115                     val responseArrayNode = responseNode.toList()
116                     for (responseSingleJsonNode in responseArrayNode) {
117                         val arrayChildNode = JsonNodeFactory.instance.objectNode()
118                         outputKeyMapping.map {
119                             val responseKeyValue = responseSingleJsonNode.get(it.key)
120                             val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key)
121                             logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type  ({$propertyTypeForDataType})")
122                             JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, arrayChildNode)
123                         }
124                         arrayNode.add(arrayChildNode)
125                     }
126                 }
127                 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
128                 // Set the List of Complex Values
129                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
130             }
131             else -> {
132                 // Complex Types
133                 val objectNode = responseNode as ObjectNode
134                 outputKeyMapping.map {
135                     val responseKeyValue = responseNode.get(it.key)
136                     val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key)
137                     logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type  ({$propertyTypeForDataType})")
138                     JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
139                 }
140
141                 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
142                 // Set the List of Complex Values
143                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
144             }
145         }
146     }
147
148     @Throws(BluePrintProcessorException::class)
149     private fun validate(resourceAssignment: ResourceAssignment) {
150         checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined")
151         checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
152         checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA, resourceAssignment.dictionarySource) {
153             "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA} but it is ${resourceAssignment.dictionarySource}"
154         }
155         checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
156     }
157
158     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
159     }
160
161
162 }