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