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.ArrayNode
 
  21 import com.fasterxml.jackson.databind.node.JsonNodeFactory
 
  22 import com.fasterxml.jackson.databind.node.NullNode
 
  23 import com.fasterxml.jackson.databind.node.ObjectNode
 
  24 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.RestResourceSource
 
  25 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
 
  26 import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
 
  27 import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BlueprintWebClientService
 
  28 import org.onap.ccsdk.apps.controllerblueprints.core.*
 
  29 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
 
  30 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
 
  31 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants
 
  32 import org.slf4j.LoggerFactory
 
  33 import org.springframework.beans.factory.config.ConfigurableBeanFactory
 
  34 import org.springframework.context.annotation.Scope
 
  35 import org.springframework.stereotype.Service
 
  38  * RestResourceResolutionProcessor
 
  40  * @author Kapil Singal
 
  42 @Service("rr-processor-source-rest")
 
  43 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
 
  44 open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService)
 
  45     : ResourceAssignmentProcessor() {
 
  47     private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java)
 
  49     override fun getName(): String {
 
  50         return "rr-processor-source-rest"
 
  53     override fun process(resourceAssignment: ResourceAssignment) {
 
  55             validate(resourceAssignment)
 
  57             // Check if It has Input
 
  58             val value = raRuntimeService.getInputValue(resourceAssignment.name)
 
  59             if (value != null && value !is NullNode) {
 
  60                 logger.info("primary-db source template key (${resourceAssignment.name}) found from input and value is ($value)")
 
  61                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
 
  63                 val dName = resourceAssignment.dictionaryName
 
  64                 val dSource = resourceAssignment.dictionarySource
 
  65                 val resourceDefinition = resourceDictionaries[dName]
 
  66                         ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
 
  67                 val resourceSource = resourceDefinition.sources[dSource]
 
  68                         ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
 
  69                 val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
 
  70                 val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java)
 
  72                 val urlPath = checkNotNull(sourceProperties.urlPath) { "failed to get request urlPath for $dName under $dSource properties" }
 
  73                 val path = nullToEmpty(sourceProperties.path)
 
  74                 val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
 
  76                 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
 
  77                 // Get the Rest Client Service
 
  78                 val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties)
 
  79                 val response = restClientService.getResource(urlPath, String::class.java)
 
  80                 if (response.isNotBlank()) {
 
  81                     logger.warn("Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath)")
 
  83                     populateResource(resourceAssignment, sourceProperties, response, path)
 
  86             // Check the value has populated for mandatory case
 
  87             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
 
  88         } catch (e: Exception) {
 
  89             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
 
  90             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
 
  94     open fun blueprintWebClientService(resourceAssignment: ResourceAssignment,
 
  95                                        restResourceSource: RestResourceSource): BlueprintWebClientService {
 
  96         return if (checkNotEmpty(restResourceSource.endpointSelector)) {
 
  97             val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!)
 
  98             blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson)
 
 100             blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!)
 
 104     @Throws(BluePrintProcessorException::class)
 
 105     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource, restResponse: String, path: String) {
 
 106         val dName = resourceAssignment.dictionaryName
 
 107         val dSource = resourceAssignment.dictionarySource
 
 108         val type = nullToEmpty(resourceAssignment.property?.type)
 
 109         lateinit var entrySchemaType: String
 
 111         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" }
 
 112         logger.info("Response processing type($type)")
 
 114         val responseNode = checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) { "Failed to find path ($path) in response ($restResponse)" }
 
 115         logger.info("populating value for output mapping ($outputKeyMapping), from json ($responseNode)")
 
 119             in BluePrintTypes.validPrimitiveTypes() -> {
 
 120                 logger.info("For template key (${resourceAssignment.name}) setting value as ($responseNode)")
 
 121                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
 
 123             in BluePrintTypes.validCollectionTypes() -> {
 
 125                 entrySchemaType = returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" }
 
 126                 val arrayNode = responseNode as ArrayNode
 
 128                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
 
 129                     val responseArrayNode = responseNode.toList()
 
 130                     for (responseSingleJsonNode in responseArrayNode) {
 
 131                         val arrayChildNode = JsonNodeFactory.instance.objectNode()
 
 132                         outputKeyMapping.map {
 
 133                             val responseKeyValue = responseSingleJsonNode.get(it.key)
 
 134                             val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key)
 
 135                             logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type  ({$propertyTypeForDataType})")
 
 136                             JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, arrayChildNode)
 
 138                         arrayNode.add(arrayChildNode)
 
 141                 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
 
 142                 // Set the List of Complex Values
 
 143                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
 
 147                 val objectNode = responseNode as ObjectNode
 
 148                 outputKeyMapping.map {
 
 149                     val responseKeyValue = responseNode.get(it.key)
 
 150                     val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key)
 
 151                     logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type  ({$propertyTypeForDataType})")
 
 152                     JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
 
 155                 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
 
 156                 // Set the List of Complex Values
 
 157                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
 
 162     @Throws(BluePrintProcessorException::class)
 
 163     private fun validate(resourceAssignment: ResourceAssignment) {
 
 164         checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined")
 
 165         checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
 
 166         checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA, resourceAssignment.dictionarySource) {
 
 167             "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA} but it is ${resourceAssignment.dictionarySource}"
 
 169         checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
 
 172     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {