2 * Copyright © 2018 IBM.
3 * Modifications Copyright © 2017-2018 AT&T Intellectual Property.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor
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.cds.blueprintsprocessor.db.BluePrintDBLibGenericService
24 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertySevice
25 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDBLibGenericService
26 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource
27 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
28 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
29 import org.onap.ccsdk.cds.controllerblueprints.core.*
30 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
31 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
32 import org.onap.ccsdk.cds.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
40 * DatabaseResourceAssignmentProcessor
42 * @author Kapil Singal
44 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-processor-db")
45 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
46 open class DatabaseResourceAssignmentProcessor(private val bluePrintDBLibPropertySevice: BluePrintDBLibPropertySevice, private val primaryDBLibGenericService: PrimaryDBLibGenericService)
47 : ResourceAssignmentProcessor() {
49 private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java)
51 override fun getName(): String {
52 return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-processor-db"
55 override suspend fun processNB(resourceAssignment: ResourceAssignment) {
57 validate(resourceAssignment)
59 // Check if It has Input
61 val value = raRuntimeService.getInputValue(resourceAssignment.name)
62 if (value !is NullNode && value !is MissingNode) {
63 logger.info("processor-db source template key (${resourceAssignment.name}) found from input and value is ($value)")
64 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
66 setValueFromDB(resourceAssignment)
68 } catch (e: BluePrintProcessorException) {
69 setValueFromDB(resourceAssignment)
72 // Check the value has populated for mandatory case
73 ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
74 } catch (e: Exception) {
75 ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
76 throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
80 private fun setValueFromDB(resourceAssignment: ResourceAssignment) {
81 val dName = resourceAssignment.dictionaryName
82 val dSource = resourceAssignment.dictionarySource
83 val resourceDefinition = resourceDictionaries[dName]
84 ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
85 val resourceSource = resourceDefinition.sources[dSource]
86 ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
87 val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
88 val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
90 val sql = checkNotNull(sourceProperties.query) { "failed to get request query for $dName under $dSource properties" }
91 val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
93 logger.info("$dSource dictionary information : ($sql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
94 val jdbcTemplate = blueprintDBLibService(sourceProperties)
96 val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping))
97 if (rows.isNullOrEmpty()) {
98 logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)")
100 populateResource(resourceAssignment, sourceProperties, rows)
104 private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): BluePrintDBLibGenericService {
105 return if (isNotEmpty(sourceProperties.endpointSelector)) {
106 val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
107 bluePrintDBLibPropertySevice.JdbcTemplate(dbPropertiesJson)
109 primaryDBLibGenericService
114 @Throws(BluePrintProcessorException::class)
115 private fun validate(resourceAssignment: ResourceAssignment) {
116 checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
117 checkNotEmpty(resourceAssignment.dictionaryName) {
118 "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
120 checkEquals(ResourceDictionaryConstants.SOURCE_PROCESSOR_DB, resourceAssignment.dictionarySource) {
121 "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}"
125 private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
126 val namedParameters = HashMap<String, Any>()
127 inputKeyMapping.forEach {
128 val expressionValue = raRuntimeService.getDictionaryStore(it.value).textValue()
129 logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)")
130 namedParameters[it.key] = expressionValue
132 logger.info("Parameter information : ({})", namedParameters)
133 return namedParameters
136 @Throws(BluePrintProcessorException::class)
137 private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, rows: List<Map<String, Any>>) {
138 val dName = resourceAssignment.dictionaryName
139 val dSource = resourceAssignment.dictionarySource
140 val type = nullToEmpty(resourceAssignment.property?.type)
142 val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" }
143 logger.info("Response processing type($type)")
147 in BluePrintTypes.validPrimitiveTypes() -> {
148 val dbColumnValue = rows[0][outputKeyMapping[dName]]
149 logger.info("For template key (${resourceAssignment.name}) setting value as ($dbColumnValue)")
150 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue)
152 in BluePrintTypes.validCollectionTypes() -> {
153 val entrySchemaType = checkNotEmpty(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" }
154 val arrayNode = JsonNodeFactory.instance.arrayNode()
156 if (entrySchemaType in BluePrintTypes.validPrimitiveTypes()) {
157 val dbColumnValue = it[outputKeyMapping[dName]]
159 JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode)
161 val arrayChildNode = JsonNodeFactory.instance.objectNode()
162 for (mapping in outputKeyMapping.entries) {
163 val dbColumnValue = checkNotNull(it[mapping.key])
164 val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key)
165 JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode)
167 arrayNode.add(arrayChildNode)
170 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
171 // Set the List of Complex Values
172 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
177 val objectNode = JsonNodeFactory.instance.objectNode()
178 for (mapping in outputKeyMapping.entries) {
179 val dbColumnValue = checkNotNull(row[mapping.key])
180 val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key)
181 JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode)
183 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
184 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
189 override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
190 raRuntimeService.getBluePrintError().addError(runtimeException.message!!)