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