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 org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService
22 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertySevice
23 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDBLibGenericService
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
26 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
27 import org.onap.ccsdk.cds.controllerblueprints.core.*
28 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
29 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
30 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants
31 import org.slf4j.LoggerFactory
32 import org.springframework.beans.factory.config.ConfigurableBeanFactory
33 import org.springframework.context.annotation.Scope
34 import org.springframework.stereotype.Service
38 * DatabaseResourceAssignmentProcessor
40 * @author Kapil Singal
42 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-db")
43 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
44 open class DatabaseResourceAssignmentProcessor(private val bluePrintDBLibPropertySevice: BluePrintDBLibPropertySevice,
45 private val primaryDBLibGenericService: PrimaryDBLibGenericService)
46 : ResourceAssignmentProcessor() {
48 private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java)
50 override fun getName(): String {
51 return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-db"
54 override suspend fun processNB(resourceAssignment: ResourceAssignment) {
56 validate(resourceAssignment)
58 // Check if It has Input
60 val value = raRuntimeService.getInputValue(resourceAssignment.name)
61 if (value.returnNullIfMissing() != null) {
62 logger.info("processor-db source template key (${resourceAssignment.name}) found from input and value is ($value)")
63 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
65 setValueFromDB(resourceAssignment)
67 } catch (e: BluePrintProcessorException) {
68 setValueFromDB(resourceAssignment)
71 // Check the value has populated for mandatory case
72 ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
73 } catch (e: Exception) {
74 ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
75 throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
79 private fun setValueFromDB(resourceAssignment: ResourceAssignment) {
80 val dName = resourceAssignment.dictionaryName!!
81 val dSource = resourceAssignment.dictionarySource!!
82 val resourceDefinition = resourceDefinition(dName)
84 /** Check Resource Assignment has the source definitions, If not get from Resource Definition **/
85 val resourceSource = resourceAssignment.dictionarySourceDefinition
86 ?: resourceDefinition?.sources?.get(dSource)
87 ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
88 val resourceSourceProperties = checkNotNull(resourceSource.properties) {
89 "failed to get source properties for $dName "
91 val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
93 val sql = checkNotNull(sourceProperties.query) {
94 "failed to get request query for $dName under $dSource properties"
96 val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) {
97 "failed to get input-key-mappings for $dName under $dSource properties"
100 logger.info("$dSource dictionary information : ($sql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
101 val jdbcTemplate = blueprintDBLibService(sourceProperties)
103 val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping))
104 if (rows.isNullOrEmpty()) {
105 logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)")
107 populateResource(resourceAssignment, sourceProperties, rows)
111 private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): BluePrintDBLibGenericService {
112 return if (isNotEmpty(sourceProperties.endpointSelector)) {
113 val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
114 bluePrintDBLibPropertySevice.JdbcTemplate(dbPropertiesJson)
116 primaryDBLibGenericService
121 @Throws(BluePrintProcessorException::class)
122 private fun validate(resourceAssignment: ResourceAssignment) {
123 checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
124 checkNotEmpty(resourceAssignment.dictionaryName) {
125 "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
127 check(resourceAssignment.dictionarySource in arrayOf(ResourceDictionaryConstants.SOURCE_PROCESSOR_DB, ResourceDictionaryConstants.SOURCE_PRIMARY_DB))
129 "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}"
133 private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
134 val namedParameters = HashMap<String, Any>()
135 inputKeyMapping.forEach {
136 val expressionValue = raRuntimeService.getDictionaryStore(it.value).textValue()
137 logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)")
138 namedParameters[it.key] = expressionValue
140 logger.info("Parameter information : ($namedParameters)")
141 return namedParameters
144 @Throws(BluePrintProcessorException::class)
145 private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, rows: List<Map<String, Any>>) {
146 val dName = resourceAssignment.dictionaryName
147 val dSource = resourceAssignment.dictionarySource
148 val type = nullToEmpty(resourceAssignment.property?.type)
150 val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
151 "failed to get output-key-mappings for $dName under $dSource properties"
153 logger.info("Response processing type($type)")
157 in BluePrintTypes.validPrimitiveTypes() -> {
158 val dbColumnValue = rows[0][outputKeyMapping[dName]]
159 logger.info("For template key (${resourceAssignment.name}) setting value as ($dbColumnValue)")
160 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue)
162 in BluePrintTypes.validCollectionTypes() -> {
163 val entrySchemaType = checkNotEmpty(resourceAssignment.property?.entrySchema?.type) {
164 "Entry schema is not defined for dictionary ($dName) info"
166 val arrayNode = JacksonUtils.objectMapper.createArrayNode()
168 if (entrySchemaType in BluePrintTypes.validPrimitiveTypes()) {
169 val dbColumnValue = it[outputKeyMapping[dName]]
171 JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode)
173 val arrayChildNode = JsonNodeFactory.instance.objectNode()
174 for (mapping in outputKeyMapping.entries) {
175 val dbColumnValue = checkNotNull(it[mapping.key])
176 val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key)
177 JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode)
179 arrayNode.add(arrayChildNode)
182 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
183 // Set the List of Complex Values
184 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
187 // Custom Simple Complex Types
189 val objectNode = JacksonUtils.objectMapper.createObjectNode()
190 for (mapping in outputKeyMapping.entries) {
191 val dbColumnValue = checkNotNull(row[mapping.value])
192 val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key)
193 JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode)
195 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
196 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
201 override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
202 raRuntimeService.getBluePrintError().addError(runtimeException.message!!)