Fix: Run both sonar and clm scans in parallel
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / resource / resolution / processor / DatabaseResourceAssignmentProcessor.kt
1 /*
2  *  Copyright © 2018 IBM.
3  *  Modifications Copyright © 2017-2018 AT&T Intellectual Property, Bell Canada.
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.cds.blueprintsprocessor.functions.resource.resolution.processor
19
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
41
42 /**
43  * DatabaseResourceAssignmentProcessor
44  *
45  * @author Kapil Singal
46  */
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() {
53
54     private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java)
55
56     override fun getName(): String {
57         return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-db"
58     }
59
60     override suspend fun processNB(resourceAssignment: ResourceAssignment) {
61         try {
62             validate(resourceAssignment)
63             // Check if It has Input
64             if (!setFromInput(resourceAssignment)) {
65                 setValueFromDB(resourceAssignment)
66             }
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."
74             )
75         } catch (e: Exception) {
76             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
77             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
78         }
79     }
80
81     private fun setValueFromDB(resourceAssignment: ResourceAssignment) {
82         val dName = resourceAssignment.dictionaryName!!
83         val dSource = resourceAssignment.dictionarySource!!
84         val resourceDefinition = resourceDefinition(dName)
85
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 "
92         }
93         val sourceProperties =
94             JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
95
96         val sql = checkNotNull(sourceProperties.query) {
97             "failed to get request query for $dName under $dSource properties"
98         }
99         val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) {
100             "failed to get input-key-mappings for $dName under $dSource properties"
101         }
102
103         sourceProperties.inputKeyMapping
104             ?.mapValues { raRuntimeService.getResolutionStore(it.value) }
105             ?.map { KeyIdentifier(it.key, it.value) }
106             ?.let { resourceAssignment.keyIdentifiers.addAll(it) }
107
108         logger.info(
109             "DatabaseResource ($dSource) dictionary information: " +
110                 "Query:($sql), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
111         )
112         val jdbcTemplate = blueprintDBLibService(sourceProperties, dSource)
113
114         val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping))
115         if (rows.isEmpty()) {
116             logger.warn("Emptyset from dictionary-source($dSource) for dictionary name ($dName) the query ($sql).")
117         }
118         logger.debug("Query returned ${rows.size} values")
119         populateResource(resourceAssignment, sourceProperties, rows)
120     }
121
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)
126         } else {
127             bluePrintDBLibPropertyService.JdbcTemplate(selector)
128         }
129     }
130
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})"
136         }
137         check(resourceAssignment.dictionarySource in getListOfDBSources()) {
138             "resource assignment source is not ${ResourceDictionaryConstants.PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}"
139         }
140     }
141
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)
145
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
152         }
153         if (namedParameters.isNotEmpty()) {
154             logger.info("Parameter information : ($namedParameters)")
155         }
156         return namedParameters
157     }
158
159     @Throws(BluePrintProcessorException::class)
160     private fun populateResource(
161         resourceAssignment: ResourceAssignment,
162         sourceProperties: DatabaseResourceSource,
163         rows: List<Map<String, Any>>
164     ) {
165         val dName = resourceAssignment.dictionaryName
166         val dSource = resourceAssignment.dictionarySource
167         val type = nullToEmpty(resourceAssignment.property?.type)
168
169         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
170             "failed to get output-key-mappings for $dName under $dSource properties"
171         }
172         logger.info("Response processing type ($type)")
173
174         val responseNode = checkNotNull(JacksonUtils.getJsonNode(rows)) {
175             "Failed to get database query result into Json node."
176         }
177
178         val parsedResponseNode = ResourceAssignmentUtils.parseResponseNode(
179             responseNode, resourceAssignment,
180             raRuntimeService, outputKeyMapping
181         )
182         ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, parsedResponseNode)
183     }
184
185     override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
186         addError(runtimeException.message!!)
187     }
188 }