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