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