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 com.fasterxml.jackson.databind.node.MissingNode
 
  22 import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.DBLibGenericService
 
  23 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource
 
  24 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
 
  25 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
 
  26 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException
 
  27 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintTypes
 
  28 import org.onap.ccsdk.apps.controllerblueprints.core.checkEqualsOrThrow
 
  29 import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmpty
 
  30 import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyOrThrow
 
  31 import org.onap.ccsdk.apps.controllerblueprints.core.nullToEmpty
 
  32 import org.onap.ccsdk.apps.controllerblueprints.core.returnNotEmptyOrThrow
 
  33 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
 
  34 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
 
  35 import org.onap.ccsdk.apps.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.jdbc.core.namedparam.NamedParameterJdbcTemplate
 
  40 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
 
  63             val value = getFromInput(resourceAssignment)
 
  64             if (value == null || value is MissingNode) {
 
  65                 val dName = resourceAssignment.dictionaryName
 
  66                 val dSource = resourceAssignment.dictionarySource
 
  67                 val resourceDefinition = resourceDictionaries[dName]
 
  68                         ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
 
  69                 val resourceSource = resourceDefinition.sources[dSource]
 
  70                         ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
 
  71                 val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
 
  72                 val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
 
  74                 val sql = checkNotNull(sourceProperties.query) { "failed to get request query for $dName under $dSource properties" }
 
  75                 val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
 
  77                 val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping)
 
  79                 val resolvedSql = resolveFromInputKeyMapping(sql, resolvedInputKeyMapping)
 
  81                 logger.info("$dSource dictionary information : ($resolvedSql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
 
  82                 val jdbcTemplate = blueprintDBLibService(sourceProperties)
 
  84                 val rows = jdbcTemplate.queryForList(resolvedSql, resolvedInputKeyMapping)
 
  85                 if (rows.isNullOrEmpty()) {
 
  86                     logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($resolvedSql)")
 
  88                     populateResource(resourceAssignment, sourceProperties, rows)
 
  92             // Check the value has populated for mandatory case
 
  93             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
 
  94         } catch (e: Exception) {
 
  95             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
 
  96             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
 
 100     private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): NamedParameterJdbcTemplate {
 
 101         return if (checkNotEmpty(sourceProperties.endpointSelector)) {
 
 102             val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
 
 103             dBLibGenericService.remoteJdbcTemplate(dbPropertiesJson)
 
 105             dBLibGenericService.primaryJdbcTemplate()
 
 110     @Throws(BluePrintProcessorException::class)
 
 111     private fun validate(resourceAssignment: ResourceAssignment) {
 
 112         checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined")
 
 113         checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
 
 114         checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_DB, resourceAssignment.dictionarySource) {
 
 115             "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_DB} but it is ${resourceAssignment.dictionarySource}"
 
 119     @Throws(BluePrintProcessorException::class)
 
 120     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, rows: List<Map<String, Any>>) {
 
 121         val dName = resourceAssignment.dictionaryName
 
 122         val dSource = resourceAssignment.dictionarySource
 
 123         val type = nullToEmpty(resourceAssignment.property?.type)
 
 125         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" }
 
 126         logger.info("Response processing type($type)")
 
 130             in BluePrintTypes.validPrimitiveTypes() -> {
 
 131                 val dbColumnValue = rows[0][outputKeyMapping[dName]]
 
 132                 logger.info("For template key (${resourceAssignment.name}) setting value as ($dbColumnValue)")
 
 133                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue)
 
 135             in BluePrintTypes.validCollectionTypes() -> {
 
 136                 val entrySchemaType = returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" }
 
 137                 var arrayNode = JsonNodeFactory.instance.arrayNode()
 
 139                     if (entrySchemaType in BluePrintTypes.validPrimitiveTypes()) {
 
 140                         val dbColumnValue = it[outputKeyMapping[dName]]
 
 142                         JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode)
 
 144                         val arrayChildNode = JsonNodeFactory.instance.objectNode()
 
 145                         for (mapping in outputKeyMapping.entries) {
 
 146                             val dbColumnValue = checkNotNull(it[mapping.key])
 
 147                             val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key)
 
 148                             JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode)
 
 150                         arrayNode.add(arrayChildNode)
 
 153                 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
 
 154                 // Set the List of Complex Values
 
 155                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
 
 160                 var objectNode = JsonNodeFactory.instance.objectNode()
 
 161                 for (mapping in outputKeyMapping.entries) {
 
 162                     val dbColumnValue = checkNotNull(row[mapping.key])
 
 163                     val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key)
 
 164                     JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode)
 
 166                 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
 
 167                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
 
 172     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
 
 173         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)