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
index 2640b5b..6072a92 100644 (file)
 
 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor
 
+import com.fasterxml.jackson.databind.JsonNode
 import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService
-import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService
 import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDBLibGenericService
+import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceDomains
 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
-import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
+import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
 import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
 import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage
 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.KeyIdentifier
 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
-import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.factory.ResourceSourceMappingFactory
 import org.slf4j.LoggerFactory
 import org.springframework.beans.factory.config.ConfigurableBeanFactory
 import org.springframework.context.annotation.Scope
@@ -68,15 +69,17 @@ open class DatabaseResourceAssignmentProcessor(
             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
         } catch (e: BluePrintProcessorException) {
             val errorMsg = "Failed to process Database resource resolution in template key ($resourceAssignment) assignments."
-            throw e.updateErrorMessage(ExecutionServiceDomains.RESOURCE_RESOLUTION, errorMsg,
-                    "Wrong resource definition or DB resolution failed.")
+            throw e.updateErrorMessage(
+                ExecutionServiceDomains.RESOURCE_RESOLUTION, errorMsg,
+                "Wrong resource definition or DB resolution failed."
+            )
         } catch (e: Exception) {
             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
         }
     }
 
-    private fun setValueFromDB(resourceAssignment: ResourceAssignment) {
+    open fun setValueFromDB(resourceAssignment: ResourceAssignment) {
         val dName = resourceAssignment.dictionaryName!!
         val dSource = resourceAssignment.dictionarySource!!
         val resourceDefinition = resourceDefinition(dName)
@@ -98,26 +101,31 @@ open class DatabaseResourceAssignmentProcessor(
             "failed to get input-key-mappings for $dName under $dSource properties"
         }
 
-        sourceProperties.inputKeyMapping
-                ?.mapValues { raRuntimeService.getDictionaryStore(it.value) }
-                ?.map { KeyIdentifier(it.key, it.value) }
-                ?.let { resourceAssignment.keyIdentifiers.addAll(it) }
+        val resolvedInputKeyMapping = resolveInputKeyMappingVariables(
+            inputKeyMapping,
+            resourceAssignment.templatingConstants
+        ).toMutableMap()
+        logger.info("\nResolved Input Key mappings: \n$resolvedInputKeyMapping")
+
+        resolvedInputKeyMapping.map { KeyIdentifier(it.key, it.value) }.let {
+            resourceAssignment.keyIdentifiers.addAll(it)
+        }
 
         logger.info(
             "DatabaseResource ($dSource) dictionary information: " +
-                    "Query:($sql), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
+                "Query:($sql), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
         )
         val jdbcTemplate = blueprintDBLibService(sourceProperties, dSource)
 
-        val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping))
-        if (rows.isNullOrEmpty()) {
-            logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)")
-        } else {
-            populateResource(resourceAssignment, sourceProperties, rows)
+        val rows = jdbcTemplate.query(sql, populateNamedParameter(resolvedInputKeyMapping))
+        if (rows.isEmpty()) {
+            logger.warn("Emptyset from dictionary-source($dSource) for dictionary name ($dName) the query ($sql).")
         }
+        logger.debug("Query returned ${rows.size} values")
+        populateResource(resourceAssignment, sourceProperties, rows)
     }
 
-    private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource, selector: String): BluePrintDBLibGenericService {
+    open fun blueprintDBLibService(sourceProperties: DatabaseResourceSource, selector: String): BluePrintDBLibGenericService {
         return if (isNotEmpty(sourceProperties.endpointSelector)) {
             val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
             bluePrintDBLibPropertyService.JdbcTemplate(dbPropertiesJson)
@@ -127,24 +135,26 @@ open class DatabaseResourceAssignmentProcessor(
     }
 
     @Throws(BluePrintProcessorException::class)
-    private fun validate(resourceAssignment: ResourceAssignment) {
+    open fun validate(resourceAssignment: ResourceAssignment) {
         checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
         checkNotEmpty(resourceAssignment.dictionaryName) {
             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
         }
         check(resourceAssignment.dictionarySource in getListOfDBSources()) {
-            "resource assignment source is not ${ResourceDictionaryConstants.PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}"
+            "resource assignment source ${resourceAssignment.dictionarySource} is not registered in \"resourceSourceMappings\""
         }
     }
 
     // placeholder to get the list of DB sources.
-    // TODO: This will be replaced with a DB
-    private fun getListOfDBSources(): Array<String> = arrayOf(ResourceDictionaryConstants.PROCESSOR_DB)
+    open fun getListOfDBSources(): Array<String> {
+        return ResourceSourceMappingFactory.getRegisterSourceMapping()
+            .resourceSourceMappings.filterValues { it == "source-db" }.keys.toTypedArray()
+    }
 
-    private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
+    open fun populateNamedParameter(inputKeyMapping: Map<String, JsonNode>): Map<String, Any> {
         val namedParameters = HashMap<String, Any>()
         inputKeyMapping.forEach {
-            val expressionValue = raRuntimeService.getResolutionStore(it.value).textValue()
+            val expressionValue = it.value.textValue()
             logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)")
             namedParameters[it.key] = expressionValue
         }
@@ -155,7 +165,7 @@ open class DatabaseResourceAssignmentProcessor(
     }
 
     @Throws(BluePrintProcessorException::class)
-    private fun populateResource(
+    open fun populateResource(
         resourceAssignment: ResourceAssignment,
         sourceProperties: DatabaseResourceSource,
         rows: List<Map<String, Any>>
@@ -181,6 +191,6 @@ open class DatabaseResourceAssignmentProcessor(
     }
 
     override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
-        raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
+        addError(runtimeException.message!!)
     }
 }