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.apps.blueprintsprocessor.functions.resource.resolution.processor
20 import com.fasterxml.jackson.databind.node.JsonNodeFactory
21 import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.DBLibGenericService
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.*
25 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
26 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
27 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants
28 import org.slf4j.LoggerFactory
29 import org.springframework.beans.factory.config.ConfigurableBeanFactory
30 import org.springframework.context.annotation.Scope
31 import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
32 import org.springframework.stereotype.Service
36 * DatabaseResourceAssignmentProcessor
38 * @author Kapil Singal
40 @Service("rr-processor-source-primary-db")
41 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
42 open class DatabaseResourceAssignmentProcessor(private val dBLibGenericService: DBLibGenericService)
43 : ResourceAssignmentProcessor() {
45 private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java)
47 override fun getName(): String {
48 return "rr-processor-source-primary-db"
51 override fun process(resourceAssignment: ResourceAssignment) {
53 validate(resourceAssignment)
55 // Check if It has Input
57 val value = raRuntimeService.getInputValue(resourceAssignment.name)
58 logger.info("primary-db source template key (${resourceAssignment.name}) found from input and value is ($value)")
59 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
60 } catch (e: BluePrintProcessorException) {
61 val dName = resourceAssignment.dictionaryName
62 val dSource = resourceAssignment.dictionarySource
63 val resourceDefinition = resourceDictionaries[dName]
64 ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
65 val resourceSource = resourceDefinition.sources[dSource]
66 ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
67 val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
68 val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
70 val sql = checkNotNull(sourceProperties.query) { "failed to get request query for $dName under $dSource properties" }
71 val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
73 logger.info("$dSource dictionary information : ($sql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
74 val jdbcTemplate = blueprintDBLibService(sourceProperties)
76 val rows = jdbcTemplate.queryForList(sql, populateNamedParameter(inputKeyMapping))
77 if (rows.isNullOrEmpty()) {
78 logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)")
80 populateResource(resourceAssignment, sourceProperties, rows)
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)
92 private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): NamedParameterJdbcTemplate {
93 return if (checkNotEmpty(sourceProperties.endpointSelector!!)) {
94 val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
95 dBLibGenericService.remoteJdbcTemplate(dbPropertiesJson)
97 dBLibGenericService.primaryJdbcTemplate()
102 @Throws(BluePrintProcessorException::class)
103 private fun validate(resourceAssignment: ResourceAssignment) {
104 checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined")
105 checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "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}"
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).textValue()
115 logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)")
116 namedParameters[it.key] = expressionValue
118 logger.info("Parameter information : ({})", namedParameters)
119 return namedParameters
122 @Throws(BluePrintProcessorException::class)
123 private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, rows: List<Map<String, Any>>) {
124 val dName = resourceAssignment.dictionaryName
125 val dSource = resourceAssignment.dictionarySource
126 val type = nullToEmpty(resourceAssignment.property?.type)
128 val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" }
129 logger.info("Response processing type($type)")
133 in BluePrintTypes.validPrimitiveTypes() -> {
134 val dbColumnValue = rows[0][outputKeyMapping[dName]]
135 logger.info("For template key (${resourceAssignment.name}) setting value as ($dbColumnValue)")
136 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue)
138 in BluePrintTypes.validCollectionTypes() -> {
139 val entrySchemaType = returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" }
140 var arrayNode = JsonNodeFactory.instance.arrayNode()
142 if (entrySchemaType in BluePrintTypes.validPrimitiveTypes()) {
143 val dbColumnValue = it[outputKeyMapping[dName]]
145 JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode)
147 val arrayChildNode = JsonNodeFactory.instance.objectNode()
148 for (mapping in outputKeyMapping.entries) {
149 val dbColumnValue = checkNotNull(it[mapping.key])
150 val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key)
151 JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode)
153 arrayNode.add(arrayChildNode)
156 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
157 // Set the List of Complex Values
158 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
163 var objectNode = JsonNodeFactory.instance.objectNode()
164 for (mapping in outputKeyMapping.entries) {
165 val dbColumnValue = checkNotNull(row[mapping.key])
166 val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key)
167 JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode)
169 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
170 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
175 override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {