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