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