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.ObjectNode
 
  23 import org.apache.commons.collections.MapUtils
 
  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.RestResourceSource
 
  26 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
 
  27 import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
 
  28 import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BlueprintWebClientService
 
  29 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException
 
  30 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintTypes
 
  31 import org.onap.ccsdk.apps.controllerblueprints.core.checkEqualsOrThrow
 
  32 import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmpty
 
  33 import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyOrThrow
 
  34 import org.onap.ccsdk.apps.controllerblueprints.core.nullToEmpty
 
  35 import org.onap.ccsdk.apps.controllerblueprints.core.returnNotEmptyOrThrow
 
  36 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
 
  37 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
 
  38 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants
 
  39 import org.slf4j.LoggerFactory
 
  40 import org.springframework.beans.factory.config.ConfigurableBeanFactory
 
  41 import org.springframework.context.annotation.Scope
 
  42 import org.springframework.stereotype.Service
 
  46  * RestResourceResolutionProcessor
 
  48  * @author Kapil Singal
 
  50 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest")
 
  51 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
 
  52 open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService)
 
  53     : ResourceAssignmentProcessor() {
 
  55     private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java)
 
  57     override fun getName(): String {
 
  58         return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
 
  61     override fun process(resourceAssignment: ResourceAssignment) {
 
  63             validate(resourceAssignment)
 
  65             // Check if It has Input
 
  67                 val value = raRuntimeService.getInputValue(resourceAssignment.name)
 
  68                 logger.info("rest source template key (${resourceAssignment.name}) found from input and value is ($value)")
 
  69                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
 
  70             } catch (e: BluePrintProcessorException) {
 
  71                 val dName = resourceAssignment.dictionaryName
 
  72                 val dSource = resourceAssignment.dictionarySource
 
  73                 val resourceDefinition = resourceDictionaries[dName]
 
  74                     ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName")
 
  75                 val resourceSource = resourceDefinition.sources[dSource]
 
  76                     ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
 
  77                 val resourceSourceProperties =
 
  78                     checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
 
  79                 val sourceProperties =
 
  80                     JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java)
 
  81                 val path = nullToEmpty(sourceProperties.path)
 
  83                     checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
 
  84                 val resolvedInputKeyMapping = populateInputKeyMappingVariables(inputKeyMapping)
 
  86                 // Resolving content Variables
 
  87                 val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
 
  89                     resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
 
  90                 val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
 
  92                 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
 
  93                 // Get the Rest Client Service
 
  94                 val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties)
 
  96                 val response = restClientService.exchangeResource(verb, urlPath, payload)
 
  97                 if (response.isBlank()) {
 
  98                     logger.warn("Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath)")
 
 100                     populateResource(resourceAssignment, sourceProperties, response, path)
 
 103             // Check the value has populated for mandatory case
 
 104             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
 
 105         } catch (e: Exception) {
 
 106             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
 
 107             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}",
 
 112     private fun blueprintWebClientService(resourceAssignment: ResourceAssignment,
 
 113                                           restResourceSource: RestResourceSource): BlueprintWebClientService {
 
 114         return if (checkNotEmpty(restResourceSource.endpointSelector)) {
 
 115             val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!)
 
 116             blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson)
 
 118             blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!)
 
 122     @Throws(BluePrintProcessorException::class)
 
 123     private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
 
 124                                  restResponse: String, path: String) {
 
 125         val dName = resourceAssignment.dictionaryName
 
 126         val dSource = resourceAssignment.dictionarySource
 
 127         val type = nullToEmpty(resourceAssignment.property?.type)
 
 128         lateinit var entrySchemaType: String
 
 130         val outputKeyMapping =
 
 131             checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" }
 
 132         logger.info("Response processing type($type)")
 
 135             checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) { "Failed to find path ($path) in response ($restResponse)" }
 
 136         logger.info("populating value for output mapping ($outputKeyMapping), from json ($responseNode)")
 
 140             in BluePrintTypes.validPrimitiveTypes() -> {
 
 141                 logger.info("For template key (${resourceAssignment.name}) setting value as ($responseNode)")
 
 142                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
 
 144             in BluePrintTypes.validCollectionTypes() -> {
 
 147                     returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" }
 
 148                 val arrayNode = responseNode as ArrayNode
 
 150                 if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
 
 151                     val responseArrayNode = responseNode.toList()
 
 152                     for (responseSingleJsonNode in responseArrayNode) {
 
 153                         val arrayChildNode = JsonNodeFactory.instance.objectNode()
 
 154                         outputKeyMapping.map {
 
 155                             val responseKeyValue = responseSingleJsonNode.get(it.key)
 
 156                             val propertyTypeForDataType =
 
 157                                 ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key)
 
 158                             logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type  ({$propertyTypeForDataType})")
 
 159                             JacksonUtils.populateJsonNodeValues(it.value,
 
 161                                 propertyTypeForDataType,
 
 164                         arrayNode.add(arrayChildNode)
 
 167                 logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)")
 
 168                 // Set the List of Complex Values
 
 169                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
 
 173                 val objectNode = responseNode as ObjectNode
 
 174                 outputKeyMapping.map {
 
 175                     val responseKeyValue = responseNode.get(it.key)
 
 176                     val propertyTypeForDataType =
 
 177                         ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key)
 
 178                     logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type  ({$propertyTypeForDataType})")
 
 179                     JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
 
 182                 logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)")
 
 183                 // Set the List of Complex Values
 
 184                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
 
 189     private fun populateInputKeyMappingVariables(inputKeyMapping: Map<String, String>): Map<String, Any> {
 
 190         val resolvedInputKeyMapping = HashMap<String, Any>()
 
 191         if (MapUtils.isNotEmpty(inputKeyMapping)) {
 
 192             for ((key, value) in inputKeyMapping) {
 
 193                 val expressionValue = raRuntimeService.getResolutionStore(value).asText()
 
 194                 logger.trace("Reference dictionary key ({}), value ({})", key, expressionValue)
 
 195                 resolvedInputKeyMapping[key] = expressionValue
 
 198         return resolvedInputKeyMapping
 
 201     private fun resolveFromInputKeyMapping(valueToResolve: String, keyMapping: Map<String, Any>): String {
 
 202         if (valueToResolve.isEmpty() || !valueToResolve.contains("$")) {
 
 203             return valueToResolve
 
 205         var res = valueToResolve
 
 206         for (entry in keyMapping.entries) {
 
 207             res = res.replace(("\\$" + entry.key).toRegex(), entry.value.toString())
 
 212     @Throws(BluePrintProcessorException::class)
 
 213     private fun validate(resourceAssignment: ResourceAssignment) {
 
 214         checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined")
 
 215         checkNotEmptyOrThrow(resourceAssignment.dictionaryName,
 
 216             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
 
 217         checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA,
 
 218             resourceAssignment.dictionarySource) {
 
 219             "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA} but it is ${resourceAssignment.dictionarySource}"
 
 221         checkNotEmptyOrThrow(resourceAssignment.dictionaryName,
 
 222             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})")
 
 225     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {