2b3270e65084a6a4060c6f924f828a771986840f
[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.NullNode
22 import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.service.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 Brinda Santh
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                 return
58             }
59
60             val dName = resourceAssignment.dictionaryName
61             val dSource = resourceAssignment.dictionarySource
62             val resourceDefinition = resourceDictionaries[dName]
63                     ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
64             val resourceSource = resourceDefinition.sources[dSource]
65                     ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
66             val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
67             val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
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                 processDBResults(resourceAssignment, sourceProperties, rows)
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 processDBResults(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         if (BluePrintTypes.validPrimitiveTypes().contains(type)) {
119             val dbColumnValue = rows[0][outputKeyMapping[dName]]
120             ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue)
121         }
122         // Array Types
123         else if (BluePrintTypes.validCollectionTypes().contains(type)) {
124             lateinit var entrySchemaType: String
125             if (resourceAssignment.property?.entrySchema != null) {
126                 entrySchemaType = nullToEmpty(resourceAssignment.property?.entrySchema?.type)
127             }
128
129             if (checkNotEmptyOrThrow(entrySchemaType, "Entry schema is not defined for dictionary ($dName) info")) {
130                 val arrayNode = JsonNodeFactory.instance.arrayNode()
131                 rows.forEach {
132                     if (BluePrintTypes.validPrimitiveTypes().contains(entrySchemaType)) {
133                         val dbColumnValue = it[outputKeyMapping[dName]]
134                         // Add Array JSON
135                         JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode)
136                     } else {
137                         val arrayChildNode = JsonNodeFactory.instance.objectNode()
138                         for (mapping in outputKeyMapping.entries) {
139                             val dbColumnValue = checkNotNull(it[mapping.key])
140                             val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key)
141                             JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode)
142                         }
143                         arrayNode.add(arrayChildNode)
144                     }
145                 }
146                 // Set the List of Complex Values
147                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
148             }
149         } else {
150             // Complex Types
151             val row = rows[0]
152             val objectNode = JsonNodeFactory.instance.objectNode()
153             for (mapping in outputKeyMapping.entries) {
154                 val dbColumnValue = checkNotNull(row[mapping.key])
155                 val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key)
156                 JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode)
157             }
158             ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
159         }
160     }
161
162     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
163     }
164 }