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.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
 
  24 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
 
  25 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException
 
  26 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintTypes
 
  27 import org.onap.ccsdk.apps.controllerblueprints.core.checkEqualsOrThrow
 
  28 import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmpty
 
  29 import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyOrThrow
 
  30 import org.onap.ccsdk.apps.controllerblueprints.core.nullToEmpty
 
  31 import org.onap.ccsdk.apps.controllerblueprints.core.returnNotEmptyOrThrow
 
  32 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
 
  33 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
 
  34 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants
 
  35 import org.slf4j.LoggerFactory
 
  36 import org.springframework.beans.factory.config.ConfigurableBeanFactory
 
  37 import org.springframework.context.annotation.Scope
 
  38 import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
 
  39 import org.springframework.stereotype.Service
 
  43  * DatabaseResourceAssignmentProcessor
 
  45  * @author Kapil Singal
 
  47 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-primary-db")
 
  48 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
 
  49 open class DatabaseResourceAssignmentProcessor(private val dBLibGenericService: DBLibGenericService)
 
  50     : ResourceAssignmentProcessor() {
 
  52     private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java)
 
  54     override fun getName(): String {
 
  55         return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-primary-db"
 
  58     override fun process(resourceAssignment: ResourceAssignment) {
 
  60             validate(resourceAssignment)
 
  62             // Check if It has Input
 
  64                 val value = raRuntimeService.getInputValue(resourceAssignment.name)
 
  65                 logger.info("primary-db source template key (${resourceAssignment.name}) found from input and value is ($value)")
 
  66                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
 
  67             } catch (e: BluePrintProcessorException) {
 
  68                 val dName = resourceAssignment.dictionaryName
 
  69                 val dSource = resourceAssignment.dictionarySource
 
  70                 val resourceDefinition = resourceDictionaries[dName]
 
  71                         ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
 
  72                 val resourceSource = resourceDefinition.sources[dSource]
 
  73                         ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
 
  74                 val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
 
  75                 val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
 
  77                 val sql = checkNotNull(sourceProperties.query) { "failed to get request query for $dName under $dSource properties" }
 
  78                 val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
 
  80                 logger.info("$dSource dictionary information : ($sql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
 
  81                 val jdbcTemplate = blueprintDBLibService(sourceProperties)
 
  83                 val rows = jdbcTemplate.queryForList(sql, populateNamedParameter(inputKeyMapping))
 
  84                 if (rows.isNullOrEmpty()) {
 
  85                     logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)")
 
  87                     populateResource(resourceAssignment, sourceProperties, rows)
 
  91             // Check the value has populated for mandatory case
 
  92             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
 
  93         } catch (e: Exception) {
 
  94             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
 
  95             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
 
  99     private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): NamedParameterJdbcTemplate {
 
 100         return if (checkNotEmpty(sourceProperties.endpointSelector)) {
 
 101             val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
 
 102             dBLibGenericService.remoteJdbcTemplate(dbPropertiesJson)
 
 104             dBLibGenericService.primaryJdbcTemplate()
 
 109     @Throws(BluePrintProcessorException::class)
 
 110     private fun validate(resourceAssignment: ResourceAssignment) {
 
 111         checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined")
 
 112         checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
 
 113         checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_DB, resourceAssignment.dictionarySource) {
 
 114             "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_DB} but it is ${resourceAssignment.dictionarySource}"
 
 118     private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
 
 119         val namedParameters = HashMap<String, Any>()
 
 120         inputKeyMapping.forEach {
 
 121             val expressionValue = raRuntimeService.getDictionaryStore(it.value).textValue()
 
 122             logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)")
 
 123             namedParameters[it.key] = expressionValue
 
 125         logger.info("Parameter information : ({})", namedParameters)
 
 126         return namedParameters
 
 129     @Throws(BluePrintProcessorException::class)
 
 130     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, rows: List<Map<String, Any>>) {
 
 131         val dName = resourceAssignment.dictionaryName
 
 132         val dSource = resourceAssignment.dictionarySource
 
 133         val type = nullToEmpty(resourceAssignment.property?.type)
 
 135         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" }
 
 136         logger.info("Response processing type($type)")
 
 140             in BluePrintTypes.validPrimitiveTypes() -> {
 
 141                 val dbColumnValue = rows[0][outputKeyMapping[dName]]
 
 142                 logger.info("For template key (${resourceAssignment.name}) setting value as ($dbColumnValue)")
 
 143                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue)
 
 145             in BluePrintTypes.validCollectionTypes() -> {
 
 146                 val entrySchemaType = returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" }
 
 147                 var arrayNode = JsonNodeFactory.instance.arrayNode()
 
 149                     if (entrySchemaType in BluePrintTypes.validPrimitiveTypes()) {
 
 150                         val dbColumnValue = it[outputKeyMapping[dName]]
 
 152                         JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode)
 
 154                         val arrayChildNode = JsonNodeFactory.instance.objectNode()
 
 155                         for (mapping in outputKeyMapping.entries) {
 
 156                             val dbColumnValue = checkNotNull(it[mapping.key])
 
 157                             val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key)
 
 158                             JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode)
 
 160                         arrayNode.add(arrayChildNode)
 
 163                 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
 
 164                 // Set the List of Complex Values
 
 165                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
 
 170                 var objectNode = JsonNodeFactory.instance.objectNode()
 
 171                 for (mapping in outputKeyMapping.entries) {
 
 172                     val dbColumnValue = checkNotNull(row[mapping.key])
 
 173                     val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key)
 
 174                     JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode)
 
 176                 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
 
 177                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
 
 182     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {