Merge "Ressource resolution using configurable database"
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / apps / blueprintsprocessor / functions / resource / resolution / processor / DatabaseResourceAssignmentProcessor.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.JsonNodeFactory
21 import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.DBLibGenericService
22 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource
23 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
24 import org.onap.ccsdk.apps.controllerblueprints.core.*
25 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
26 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
27 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants
28 import org.slf4j.LoggerFactory
29 import org.springframework.beans.factory.config.ConfigurableBeanFactory
30 import org.springframework.context.annotation.Scope
31 import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
32 import org.springframework.stereotype.Service
33 import java.util.*
34
35 /**
36  * DatabaseResourceAssignmentProcessor
37  *
38  * @author Kapil Singal
39  */
40 @Service("rr-processor-source-primary-db")
41 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
42 open class DatabaseResourceAssignmentProcessor(private val dBLibGenericService: DBLibGenericService)
43     : ResourceAssignmentProcessor() {
44
45     private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java)
46
47     override fun getName(): String {
48         return "rr-processor-source-primary-db"
49     }
50
51     override fun process(resourceAssignment: ResourceAssignment) {
52         try {
53             validate(resourceAssignment)
54
55             // Check if It has Input
56             try {
57                 val value = raRuntimeService.getInputValue(resourceAssignment.name)
58                 logger.info("primary-db source template key (${resourceAssignment.name}) found from input and value is ($value)")
59                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
60             } catch (e: BluePrintProcessorException) {
61                 val dName = resourceAssignment.dictionaryName
62                 val dSource = resourceAssignment.dictionarySource
63                 val resourceDefinition = resourceDictionaries[dName]
64                         ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
65                 val resourceSource = resourceDefinition.sources[dSource]
66                         ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
67                 val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
68                 val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
69
70                 val sql = checkNotNull(sourceProperties.query) { "failed to get request query for $dName under $dSource properties" }
71                 val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
72
73                 logger.info("$dSource dictionary information : ($sql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
74                 val jdbcTemplate = blueprintDBLibService(sourceProperties)
75
76                 val rows = jdbcTemplate.queryForList(sql, populateNamedParameter(inputKeyMapping))
77                 if (rows.isNullOrEmpty()) {
78                     logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)")
79                 } else {
80                     populateResource(resourceAssignment, sourceProperties, rows)
81                 }
82             }
83
84             // Check the value has populated for mandatory case
85             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
86         } catch (e: Exception) {
87             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
88             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
89         }
90     }
91
92     private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): NamedParameterJdbcTemplate {
93         return if (checkNotEmpty(sourceProperties.endpointSelector!!)) {
94             val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
95             dBLibGenericService.remoteJdbcTemplate(dbPropertiesJson)
96         } else {
97             dBLibGenericService.primaryJdbcTemplate()
98         }
99
100     }
101
102     @Throws(BluePrintProcessorException::class)
103     private fun validate(resourceAssignment: ResourceAssignment) {
104         checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined")
105         checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
106         checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_DB, resourceAssignment.dictionarySource) {
107             "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_DB} but it is ${resourceAssignment.dictionarySource}"
108         }
109     }
110
111     private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
112         val namedParameters = HashMap<String, Any>()
113         inputKeyMapping.forEach {
114             val expressionValue = raRuntimeService.getDictionaryStore(it.value).textValue()
115             logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)")
116             namedParameters[it.key] = expressionValue
117         }
118         logger.info("Parameter information : ({})", namedParameters)
119         return namedParameters
120     }
121
122     @Throws(BluePrintProcessorException::class)
123     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, rows: List<Map<String, Any>>) {
124         val dName = resourceAssignment.dictionaryName
125         val dSource = resourceAssignment.dictionarySource
126         val type = nullToEmpty(resourceAssignment.property?.type)
127
128         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" }
129         logger.info("Response processing type($type)")
130
131         // Primitive Types
132         when(type) {
133             in BluePrintTypes.validPrimitiveTypes() -> {
134                 val dbColumnValue = rows[0][outputKeyMapping[dName]]
135                 logger.info("For template key (${resourceAssignment.name}) setting value as ($dbColumnValue)")
136                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue)
137             }
138             in BluePrintTypes.validCollectionTypes() -> {
139                 val entrySchemaType = returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" }
140                 var arrayNode = JsonNodeFactory.instance.arrayNode()
141                 rows.forEach {
142                     if (entrySchemaType in BluePrintTypes.validPrimitiveTypes()) {
143                         val dbColumnValue = it[outputKeyMapping[dName]]
144                         // Add Array JSON
145                         JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode)
146                     } else {
147                         val arrayChildNode = JsonNodeFactory.instance.objectNode()
148                         for (mapping in outputKeyMapping.entries) {
149                             val dbColumnValue = checkNotNull(it[mapping.key])
150                             val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key)
151                             JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode)
152                         }
153                         arrayNode.add(arrayChildNode)
154                     }
155                 }
156                 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
157                 // Set the List of Complex Values
158                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
159             }
160             else -> {
161                 // Complex Types
162                 val row = rows[0]
163                 var objectNode = JsonNodeFactory.instance.objectNode()
164                 for (mapping in outputKeyMapping.entries) {
165                     val dbColumnValue = checkNotNull(row[mapping.key])
166                     val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key)
167                     JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode)
168                 }
169                 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
170                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
171             }
172         }
173     }
174
175     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
176     }
177 }