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