7c590883f59c8c47e6125c939d8fda18f098caa4
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / apps / blueprintsprocessor / functions / resource / resolution / utils / ResourceResolutionUtils.kt
1 /*
2  * Copyright © 2017-2018 AT&T Intellectual Property.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils
18
19 import java.util.Date
20 import org.apache.commons.lang3.StringUtils
21 import com.att.eelf.configuration.EELFLogger
22 import com.att.eelf.configuration.EELFManager
23 import com.fasterxml.jackson.databind.JsonNode
24 import com.fasterxml.jackson.databind.ObjectMapper
25 import com.fasterxml.jackson.databind.node.NullNode
26 import com.fasterxml.jackson.databind.node.ObjectNode
27 import org.onap.ccsdk.apps.controllerblueprints.core.*
28 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
29 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
30
31 class ResourceResolutionUtils {
32     companion object {
33
34         private val logger: EELFLogger = EELFManager.getInstance().getLogger(ResourceResolutionUtils::class.toString())
35
36         @Synchronized
37         @Throws(BluePrintProcessorException::class)
38         fun setResourceDataValue(resourceAssignment: ResourceAssignment, value: Any?) {
39
40             val resourceProp = checkNotNull(resourceAssignment.property) { "Failed in setting resource value for resource mapping $resourceAssignment" }
41             checkNotEmptyNThrow(resourceAssignment.name, "Failed in setting resource value for resource mapping $resourceAssignment")
42
43             if (checkNotEmpty(resourceAssignment.dictionaryName)) {
44                 resourceAssignment.dictionaryName = resourceAssignment.name
45                 logger.warn("Missing dictionary key, setting with template key (${resourceAssignment.name}) as dictionary key (${resourceAssignment.dictionaryName})")
46             }
47
48             try {
49                 if (checkNotEmpty(resourceProp.type)) {
50                     val convertedValue = convertResourceValue(resourceProp.type, value)
51                     logger.info("Setting Resource Value ($convertedValue) for Resource Name (${resourceAssignment.dictionaryName}) of type (${resourceProp.type})")
52                     resourceProp.value = convertedValue
53                     resourceAssignment.updatedDate = Date()
54                     resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
55                     resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS
56                 }
57             } catch (e: Exception) {
58                 throw BluePrintProcessorException("Failed in setting value for template key (%s) and " +
59                         "dictionary key (${resourceAssignment.name}) of type (${resourceProp.type}) with error message (${e.message})", e)
60             }
61         }
62
63         private fun convertResourceValue(type: String, value: Any?): JsonNode? {
64             var convertedValue: JsonNode?
65
66             if (value == null || value is NullNode) {
67                 logger.info("Returning {} value from convertResourceValue", value)
68                 return null
69             } else if (BluePrintTypes.validPrimitiveTypes().contains(type) && value is String) {
70                 convertedValue = JacksonUtils.convertPrimitiveResourceValue(type, value)
71             } else {
72                 // Case where Resource is non-primitive type
73                 if (value is String) {
74                     convertedValue = JacksonUtils.jsonNode(value)
75                 } else {
76                     convertedValue = JacksonUtils.getJsonNode(value)
77                 }
78             }
79             return convertedValue
80         }
81
82         @Synchronized
83         fun setFailedResourceDataValue(resourceAssignment: ResourceAssignment, message: String?) {
84             if (checkNotEmpty(resourceAssignment.name)) {
85                 resourceAssignment.updatedDate = Date()
86                 resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
87                 resourceAssignment.status = BluePrintConstants.STATUS_FAILURE
88                 resourceAssignment.message = message
89             }
90         }
91
92         @Synchronized
93         @Throws(BluePrintProcessorException::class)
94         fun assertTemplateKeyValueNotNull(resourceAssignment: ResourceAssignment) {
95             val resourceProp = checkNotNull(resourceAssignment.property) { "Failed to populate mandatory resource resource mapping $resourceAssignment" }
96             if (resourceProp.required != null && resourceProp.required!! && (resourceProp.value == null || resourceProp.value !is NullNode)) {
97                 logger.error("failed to populate mandatory resource mapping ($resourceAssignment)")
98                 throw BluePrintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)")
99             }
100         }
101
102         @Synchronized
103         @Throws(BluePrintProcessorException::class)
104         fun generateResourceDataForAssignments(assignments: List<ResourceAssignment>): String {
105             var result = "{}"
106             try {
107                 val mapper = ObjectMapper()
108                 val root = mapper.readTree(result)
109
110                 assignments.forEach {
111                     if (checkNotEmpty(it.name) && it.property != null) {
112
113                         val type = it.property?.type
114                         val value = it.property?.value
115                         logger.info("Generating Resource name ({}), type ({}), value ({})", it.name, type,
116                                 value)
117                         if (value == null) {
118                             (root as ObjectNode).set(it.name, null)
119                         } else if (value is JsonNode) {
120                             (root as ObjectNode).put(it.name, value as JsonNode)
121                         } else if (BluePrintConstants.DATA_TYPE_STRING.equals(type, ignoreCase = true)) {
122                             (root as ObjectNode).put(it.name, value as String)
123                         } else if (BluePrintConstants.DATA_TYPE_BOOLEAN.equals(type, ignoreCase = true)) {
124                             (root as ObjectNode).put(it.name, value as Boolean)
125                         } else if (BluePrintConstants.DATA_TYPE_INTEGER.equals(type, ignoreCase = true)) {
126                             (root as ObjectNode).put(it.name, value as Int)
127                         } else if (BluePrintConstants.DATA_TYPE_FLOAT.equals(type, ignoreCase = true)) {
128                             (root as ObjectNode).put(it.name, value as Float)
129                         } else if (BluePrintConstants.DATA_TYPE_TIMESTAMP.equals(type, ignoreCase = true)) {
130                             (root as ObjectNode).put(it.name, value as String)
131                         } else {
132                             val jsonNode = JacksonUtils.getJsonNode(value)
133                             if (jsonNode != null) {
134                                 (root as ObjectNode).put(it.name, jsonNode)
135                             } else {
136                                 (root as ObjectNode).set(it.name, null)
137                             }
138                         }
139                     }
140                 }
141                 result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root)
142                 logger.info("Generated Resource Param Data ({})", result)
143             } catch (e: Exception) {
144                 throw BluePrintProcessorException("kapil is failing with $e.message", e)
145             }
146
147             return result
148         }
149
150         fun <T> transformResourceSource(properties: MutableMap<String, JsonNode>, classType: Class<T>): T {
151             val content = JacksonUtils.getJson(properties)
152             return JacksonUtils.readValue(content, classType)
153                     ?: throw BluePrintProcessorException("failed to transform content($content) to type($classType)")
154         }
155
156     }
157 }