DB resolutions are picking inputKeyMapping values from DD
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / resource / resolution / processor / DatabaseResourceAssignmentProcessor.kt
1 /*
2  *  Copyright © 2018 IBM.
3  *  Modifications Copyright © 2017-2018 AT&T Intellectual Property, Bell Canada.
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.cds.blueprintsprocessor.functions.resource.resolution.processor
19
20 import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService
21 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService
22 import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDBLibGenericService
23 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
26 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
27 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
28 import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
29 import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
30 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
31 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
32 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants
33 import org.slf4j.LoggerFactory
34 import org.springframework.beans.factory.config.ConfigurableBeanFactory
35 import org.springframework.context.annotation.Scope
36 import org.springframework.stereotype.Service
37 import java.util.HashMap
38
39 /**
40  * DatabaseResourceAssignmentProcessor
41  *
42  * @author Kapil Singal
43  */
44 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-db")
45 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
46 open class DatabaseResourceAssignmentProcessor(
47     private val bluePrintDBLibPropertyService: BluePrintDBLibPropertyService,
48     private val primaryDBLibGenericService: PrimaryDBLibGenericService
49 ) : ResourceAssignmentProcessor() {
50
51     private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java)
52
53     override fun getName(): String {
54         return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-db"
55     }
56
57     override suspend fun processNB(resourceAssignment: ResourceAssignment) {
58         try {
59             validate(resourceAssignment)
60             // Check if It has Input
61             if (!setFromInput(resourceAssignment)) {
62                 setValueFromDB(resourceAssignment)
63             }
64             // Check the value has populated for mandatory case
65             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
66         } catch (e: Exception) {
67             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
68             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
69         }
70     }
71
72     private fun setValueFromDB(resourceAssignment: ResourceAssignment) {
73         val dName = resourceAssignment.dictionaryName!!
74         val dSource = resourceAssignment.dictionarySource!!
75         val resourceDefinition = resourceDefinition(dName)
76
77         /** Check Resource Assignment has the source definitions, If not get from Resource Definition **/
78         val resourceSource = resourceAssignment.dictionarySourceDefinition
79             ?: resourceDefinition?.sources?.get(dSource)
80             ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
81         val resourceSourceProperties = checkNotNull(resourceSource.properties) {
82             "failed to get source properties for $dName "
83         }
84         val sourceProperties =
85             JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
86
87         val sql = checkNotNull(sourceProperties.query) {
88             "failed to get request query for $dName under $dSource properties"
89         }
90         val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) {
91             "failed to get input-key-mappings for $dName under $dSource properties"
92         }
93
94         logger.info(
95             "DatabaseResource ($dSource) dictionary information: " +
96                     "Query:($sql), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
97         )
98         val jdbcTemplate = blueprintDBLibService(sourceProperties)
99
100         val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping))
101         if (rows.isNullOrEmpty()) {
102             logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)")
103         } else {
104             populateResource(resourceAssignment, sourceProperties, rows)
105         }
106     }
107
108     private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): BluePrintDBLibGenericService {
109         return if (isNotEmpty(sourceProperties.endpointSelector)) {
110             val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
111             bluePrintDBLibPropertyService.JdbcTemplate(dbPropertiesJson)
112         } else {
113             primaryDBLibGenericService
114         }
115     }
116
117     @Throws(BluePrintProcessorException::class)
118     private fun validate(resourceAssignment: ResourceAssignment) {
119         checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
120         checkNotEmpty(resourceAssignment.dictionaryName) {
121             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
122         }
123         check(resourceAssignment.dictionarySource in getListOfDBSources()) {
124             "resource assignment source is not ${ResourceDictionaryConstants.PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}"
125         }
126     }
127
128     // placeholder to get the list of DB sources.
129     // TODO: This will be replaced with a DB
130     private fun getListOfDBSources(): Array<String> = arrayOf(ResourceDictionaryConstants.PROCESSOR_DB)
131
132     private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
133         val namedParameters = HashMap<String, Any>()
134         inputKeyMapping.forEach {
135             val expressionValue = raRuntimeService.getResolutionStore(it.value).textValue()
136             logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)")
137             namedParameters[it.key] = expressionValue
138         }
139         if (namedParameters.isNotEmpty()) {
140             logger.info("Parameter information : ($namedParameters)")
141         }
142         return namedParameters
143     }
144
145     @Throws(BluePrintProcessorException::class)
146     private fun populateResource(
147         resourceAssignment: ResourceAssignment,
148         sourceProperties: DatabaseResourceSource,
149         rows: List<Map<String, Any>>
150     ) {
151         val dName = resourceAssignment.dictionaryName
152         val dSource = resourceAssignment.dictionarySource
153         val type = nullToEmpty(resourceAssignment.property?.type)
154
155         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
156             "failed to get output-key-mappings for $dName under $dSource properties"
157         }
158         logger.info("Response processing type ($type)")
159
160         val responseNode = checkNotNull(JacksonUtils.getJsonNode(rows)) {
161             "Failed to get database query result into Json node."
162         }
163
164         val parsedResponseNode = ResourceAssignmentUtils.parseResponseNode(
165             responseNode, resourceAssignment,
166             raRuntimeService, outputKeyMapping
167         )
168         ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, parsedResponseNode)
169     }
170
171     override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
172         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
173     }
174 }