Refactoring ResourceAssignmentUtils
[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.BluePrintDBLibPropertySevice
22 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.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.*
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 bluePrintDBLibPropertySevice: BluePrintDBLibPropertySevice,
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("$dSource dictionary information : ($sql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
95         val jdbcTemplate = blueprintDBLibService(sourceProperties)
96
97         val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping))
98         if (rows.isNullOrEmpty()) {
99             logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)")
100         } else {
101             populateResource(resourceAssignment, sourceProperties, rows)
102         }
103     }
104
105     private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): BluePrintDBLibGenericService {
106         return if (isNotEmpty(sourceProperties.endpointSelector)) {
107             val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
108             bluePrintDBLibPropertySevice.JdbcTemplate(dbPropertiesJson)
109         } else {
110             primaryDBLibGenericService
111         }
112
113     }
114
115     @Throws(BluePrintProcessorException::class)
116     private fun validate(resourceAssignment: ResourceAssignment) {
117         checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
118         checkNotEmpty(resourceAssignment.dictionaryName) {
119             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
120         }
121         check(resourceAssignment.dictionarySource in getListOfDBSources())
122         {
123             "resource assignment source is not ${ResourceDictionaryConstants.PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}"
124         }
125     }
126
127     //placeholder to get the list of DB sources.
128     //TODO: This will be replaced with a DB
129     private fun getListOfDBSources(): Array<String> = arrayOf(ResourceDictionaryConstants.PROCESSOR_DB)
130
131     private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
132         val namedParameters = HashMap<String, Any>()
133         inputKeyMapping.forEach {
134             val expressionValue = raRuntimeService.getDictionaryStore(it.value).textValue()
135             logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)")
136             namedParameters[it.key] = expressionValue
137         }
138         if (namedParameters.isNotEmpty()) {
139             logger.info("Parameter information : ($namedParameters)")
140         }
141         return namedParameters
142     }
143
144     @Throws(BluePrintProcessorException::class)
145     private fun populateResource(
146         resourceAssignment: ResourceAssignment,
147         sourceProperties: DatabaseResourceSource,
148         rows: List<Map<String, Any>>
149     ) {
150         val dName = resourceAssignment.dictionaryName
151         val dSource = resourceAssignment.dictionarySource
152         val type = nullToEmpty(resourceAssignment.property?.type)
153
154         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
155             "failed to get output-key-mappings for $dName under $dSource properties"
156         }
157         logger.info("Response processing type ($type)")
158
159         val responseNode = checkNotNull(JacksonUtils.getJsonNode(rows)) {
160             "Failed to get database query result into Json node."
161         }
162
163         val parsedResponseNode = ResourceAssignmentUtils.parseResponseNode(
164             responseNode, resourceAssignment,
165             raRuntimeService, outputKeyMapping
166         )
167         ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, parsedResponseNode)
168     }
169
170     override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
171         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
172     }
173 }