2 * Copyright © 2018 IBM.
3 * Modifications Copyright © 2017-2018 AT&T Intellectual Property, Bell Canada.
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 org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService
21 import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDBLibGenericService
22 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService
23 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
26 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceDomains
27 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
28 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
29 import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
30 import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
31 import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage
32 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
33 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.KeyIdentifier
34 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
35 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants
36 import org.slf4j.LoggerFactory
37 import org.springframework.beans.factory.config.ConfigurableBeanFactory
38 import org.springframework.context.annotation.Scope
39 import org.springframework.stereotype.Service
40 import java.util.HashMap
43 * DatabaseResourceAssignmentProcessor
45 * @author Kapil Singal
47 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-db")
48 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
49 open class DatabaseResourceAssignmentProcessor(
50 private val bluePrintDBLibPropertyService: BluePrintDBLibPropertyService,
51 private val primaryDBLibGenericService: PrimaryDBLibGenericService
52 ) : ResourceAssignmentProcessor() {
54 private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java)
56 override fun getName(): String {
57 return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-db"
60 override suspend fun processNB(resourceAssignment: ResourceAssignment) {
62 validate(resourceAssignment)
63 // Check if It has Input
64 if (!setFromInput(resourceAssignment)) {
65 setValueFromDB(resourceAssignment)
67 // Check the value has populated for mandatory case
68 ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
69 } catch (e: BluePrintProcessorException) {
70 val errorMsg = "Failed to process Database resource resolution in template key ($resourceAssignment) assignments."
71 throw e.updateErrorMessage(
72 ExecutionServiceDomains.RESOURCE_RESOLUTION, errorMsg,
73 "Wrong resource definition or DB resolution failed."
75 } catch (e: Exception) {
76 ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
77 throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
81 private fun setValueFromDB(resourceAssignment: ResourceAssignment) {
82 val dName = resourceAssignment.dictionaryName!!
83 val dSource = resourceAssignment.dictionarySource!!
84 val resourceDefinition = resourceDefinition(dName)
86 /** Check Resource Assignment has the source definitions, If not get from Resource Definition **/
87 val resourceSource = resourceAssignment.dictionarySourceDefinition
88 ?: resourceDefinition?.sources?.get(dSource)
89 ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
90 val resourceSourceProperties = checkNotNull(resourceSource.properties) {
91 "failed to get source properties for $dName "
93 val sourceProperties =
94 JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
96 val sql = checkNotNull(sourceProperties.query) {
97 "failed to get request query for $dName under $dSource properties"
99 val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) {
100 "failed to get input-key-mappings for $dName under $dSource properties"
103 sourceProperties.inputKeyMapping
104 ?.mapValues { raRuntimeService.getResolutionStore(it.value) }
105 ?.map { KeyIdentifier(it.key, it.value) }
106 ?.let { resourceAssignment.keyIdentifiers.addAll(it) }
109 "DatabaseResource ($dSource) dictionary information: " +
110 "Query:($sql), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
112 val jdbcTemplate = blueprintDBLibService(sourceProperties, dSource)
114 val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping))
115 if (rows.isNullOrEmpty()) {
116 logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)")
118 populateResource(resourceAssignment, sourceProperties, rows)
122 private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource, selector: String): BluePrintDBLibGenericService {
123 return if (isNotEmpty(sourceProperties.endpointSelector)) {
124 val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
125 bluePrintDBLibPropertyService.JdbcTemplate(dbPropertiesJson)
127 bluePrintDBLibPropertyService.JdbcTemplate(selector)
131 @Throws(BluePrintProcessorException::class)
132 private fun validate(resourceAssignment: ResourceAssignment) {
133 checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
134 checkNotEmpty(resourceAssignment.dictionaryName) {
135 "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
137 check(resourceAssignment.dictionarySource in getListOfDBSources()) {
138 "resource assignment source is not ${ResourceDictionaryConstants.PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}"
142 // placeholder to get the list of DB sources.
143 // TODO: This will be replaced with a DB
144 private fun getListOfDBSources(): Array<String> = arrayOf(ResourceDictionaryConstants.PROCESSOR_DB)
146 private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
147 val namedParameters = HashMap<String, Any>()
148 inputKeyMapping.forEach {
149 val expressionValue = raRuntimeService.getResolutionStore(it.value).textValue()
150 logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)")
151 namedParameters[it.key] = expressionValue
153 if (namedParameters.isNotEmpty()) {
154 logger.info("Parameter information : ($namedParameters)")
156 return namedParameters
159 @Throws(BluePrintProcessorException::class)
160 private fun populateResource(
161 resourceAssignment: ResourceAssignment,
162 sourceProperties: DatabaseResourceSource,
163 rows: List<Map<String, Any>>
165 val dName = resourceAssignment.dictionaryName
166 val dSource = resourceAssignment.dictionarySource
167 val type = nullToEmpty(resourceAssignment.property?.type)
169 val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
170 "failed to get output-key-mappings for $dName under $dSource properties"
172 logger.info("Response processing type ($type)")
174 val responseNode = checkNotNull(JacksonUtils.getJsonNode(rows)) {
175 "Failed to get database query result into Json node."
178 val parsedResponseNode = ResourceAssignmentUtils.parseResponseNode(
179 responseNode, resourceAssignment,
180 raRuntimeService, outputKeyMapping
182 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, parsedResponseNode)
185 override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
186 raRuntimeService.getBluePrintError().addError(runtimeException.message!!)