e8b61a8fe8d86ff087ee5789d938865e722d0621
[ccsdk/cds.git] /
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.cds.blueprintsprocessor.functions.resource.resolution.processor
19
20 import com.fasterxml.jackson.databind.node.JsonNodeFactory
21 import com.fasterxml.jackson.databind.node.MissingNode
22 import com.fasterxml.jackson.databind.node.NullNode
23 import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService
24 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertySevice
25 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDBLibGenericService
26 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource
27 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
28 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
29 import org.onap.ccsdk.cds.controllerblueprints.core.*
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-processor-db")
45 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
46 open class DatabaseResourceAssignmentProcessor(private val bluePrintDBLibPropertySevice: BluePrintDBLibPropertySevice,
47                                                private val primaryDBLibGenericService: PrimaryDBLibGenericService)
48     : ResourceAssignmentProcessor() {
49
50     private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java)
51
52     override fun getName(): String {
53         return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-processor-db"
54     }
55
56     override suspend fun processNB(resourceAssignment: ResourceAssignment) {
57         try {
58             validate(resourceAssignment)
59
60             // Check if It has Input
61             try {
62                 val value = raRuntimeService.getInputValue(resourceAssignment.name)
63                 if (value !is NullNode && value !is MissingNode) {
64                     logger.info("processor-db source template key (${resourceAssignment.name}) found from input and value is ($value)")
65                     ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
66                 } else {
67                     setValueFromDB(resourceAssignment)
68                 }
69             } catch (e: BluePrintProcessorException) {
70                 setValueFromDB(resourceAssignment)
71             }
72
73             // Check the value has populated for mandatory case
74             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
75         } catch (e: Exception) {
76             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
77             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
78         }
79     }
80
81     private fun setValueFromDB(resourceAssignment: ResourceAssignment) {
82         val dName = resourceAssignment.dictionaryName
83         val dSource = resourceAssignment.dictionarySource
84         val resourceDefinition = resourceDictionaries[dName]
85                 ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
86         val resourceSource = resourceDefinition.sources[dSource]
87                 ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
88         val resourceSourceProperties = checkNotNull(resourceSource.properties) {
89             "failed to get source properties for $dName "
90         }
91         val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
92
93         val sql = checkNotNull(sourceProperties.query) {
94             "failed to get request query for $dName under $dSource properties"
95         }
96         val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) {
97             "failed to get input-key-mappings for $dName under $dSource properties"
98         }
99
100         logger.info("$dSource dictionary information : ($sql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
101         val jdbcTemplate = blueprintDBLibService(sourceProperties)
102
103         val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping))
104         if (rows.isNullOrEmpty()) {
105             logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)")
106         } else {
107             populateResource(resourceAssignment, sourceProperties, rows)
108         }
109     }
110
111     private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): BluePrintDBLibGenericService {
112         return if (isNotEmpty(sourceProperties.endpointSelector)) {
113             val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
114             bluePrintDBLibPropertySevice.JdbcTemplate(dbPropertiesJson)
115         } else {
116             primaryDBLibGenericService
117         }
118
119     }
120
121     @Throws(BluePrintProcessorException::class)
122     private fun validate(resourceAssignment: ResourceAssignment) {
123         checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
124         checkNotEmpty(resourceAssignment.dictionaryName) {
125             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
126         }
127         checkEquals(ResourceDictionaryConstants.SOURCE_PROCESSOR_DB, resourceAssignment.dictionarySource) {
128             "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}"
129         }
130     }
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.getDictionaryStore(it.value).textValue()
136             logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)")
137             namedParameters[it.key] = expressionValue
138         }
139         logger.info("Parameter information : ($namedParameters)")
140         return namedParameters
141     }
142
143     @Throws(BluePrintProcessorException::class)
144     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, rows: List<Map<String, Any>>) {
145         val dName = resourceAssignment.dictionaryName
146         val dSource = resourceAssignment.dictionarySource
147         val type = nullToEmpty(resourceAssignment.property?.type)
148
149         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
150             "failed to get output-key-mappings for $dName under $dSource properties"
151         }
152         logger.info("Response processing type($type)")
153
154         // Primitive Types
155         when (type) {
156             in BluePrintTypes.validPrimitiveTypes() -> {
157                 val dbColumnValue = rows[0][outputKeyMapping[dName]]
158                 logger.info("For template key (${resourceAssignment.name}) setting value as ($dbColumnValue)")
159                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue)
160             }
161             in BluePrintTypes.validCollectionTypes() -> {
162                 val entrySchemaType = checkNotEmpty(resourceAssignment.property?.entrySchema?.type) {
163                     "Entry schema is not defined for dictionary ($dName) info"
164                 }
165                 val arrayNode = JacksonUtils.objectMapper.createArrayNode()
166                 rows.forEach {
167                     if (entrySchemaType in BluePrintTypes.validPrimitiveTypes()) {
168                         val dbColumnValue = it[outputKeyMapping[dName]]
169                         // Add Array JSON
170                         JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode)
171                     } else {
172                         val arrayChildNode = JsonNodeFactory.instance.objectNode()
173                         for (mapping in outputKeyMapping.entries) {
174                             val dbColumnValue = checkNotNull(it[mapping.key])
175                             val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key)
176                             JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode)
177                         }
178                         arrayNode.add(arrayChildNode)
179                     }
180                 }
181                 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
182                 // Set the List of Complex Values
183                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
184             }
185             else -> {
186                 // Custom Simple Complex Types
187                 val row = rows[0]
188                 val objectNode = JacksonUtils.objectMapper.createObjectNode()
189                 for (mapping in outputKeyMapping.entries) {
190                     val dbColumnValue = checkNotNull(row[mapping.key])
191                     val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key)
192                     JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode)
193                 }
194                 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
195                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
196             }
197         }
198     }
199
200     override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
201         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
202     }
203 }