Merge "Add velocity engine template service"
[ccsdk/cds.git] / components / resource-dict / src / main / kotlin / org / onap / ccsdk / apps / controllerblueprints / resource / dict / utils / ResourceAssignmentUtils.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.controllerblueprints.resource.dict.utils
18
19 import java.util.Date
20 import com.att.eelf.configuration.EELFLogger
21 import com.att.eelf.configuration.EELFManager
22 import com.fasterxml.jackson.databind.JsonNode
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import com.fasterxml.jackson.databind.node.NullNode
25 import com.fasterxml.jackson.databind.node.ObjectNode
26 import org.onap.ccsdk.apps.controllerblueprints.core.*
27 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
28 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
29
30 class ResourceAssignmentUtils {
31     companion object {
32
33         private val logger: EELFLogger = EELFManager.getInstance().getLogger(ResourceAssignmentUtils::class.toString())
34
35         @Synchronized
36         @Throws(BluePrintProcessorException::class)
37         fun setResourceDataValue(resourceAssignment: ResourceAssignment, value: Any?) {
38
39             val resourceProp = checkNotNull(resourceAssignment.property) { "Failed in setting resource value for resource mapping $resourceAssignment" }
40             checkNotEmptyNThrow(resourceAssignment.name, "Failed in setting resource value for resource mapping $resourceAssignment")
41
42             if (checkNotEmpty(resourceAssignment.dictionaryName)) {
43                 resourceAssignment.dictionaryName = resourceAssignment.name
44                 logger.warn("Missing dictionary key, setting with template key (${resourceAssignment.name}) as dictionary key (${resourceAssignment.dictionaryName})")
45             }
46
47             try {
48                 if (checkNotEmpty(resourceProp.type)) {
49                     val convertedValue = convertResourceValue(resourceProp.type, value)
50                     logger.info("Setting Resource Value ($convertedValue) for Resource Name (${resourceAssignment.dictionaryName}) of type (${resourceProp.type})")
51                     resourceProp.value = convertedValue
52                     resourceAssignment.updatedDate = Date()
53                     resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
54                     resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS
55                 }
56             } catch (e: Exception) {
57                 throw BluePrintProcessorException("Failed in setting value for template key (%s) and " +
58                         "dictionary key (${resourceAssignment.name}) of type (${resourceProp.type}) with error message (${e.message})", e)
59             }
60         }
61
62         private fun convertResourceValue(type: String, value: Any?): JsonNode? {
63             var convertedValue: JsonNode?
64
65             if (value == null || value is NullNode) {
66                 logger.info("Returning {} value from convertResourceValue", value)
67                 return null
68             } else if (BluePrintTypes.validPrimitiveTypes().contains(type) && value is String) {
69                 convertedValue = JacksonUtils.convertPrimitiveResourceValue(type, value)
70             } else {
71                 // Case where Resource is non-primitive type
72                 if (value is String) {
73                     convertedValue = JacksonUtils.jsonNode(value)
74                 } else {
75                     convertedValue = JacksonUtils.getJsonNode(value)
76                 }
77             }
78             return convertedValue
79         }
80
81         @Synchronized
82         fun setFailedResourceDataValue(resourceAssignment: ResourceAssignment, message: String?) {
83             if (checkNotEmpty(resourceAssignment.name)) {
84                 resourceAssignment.updatedDate = Date()
85                 resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
86                 resourceAssignment.status = BluePrintConstants.STATUS_FAILURE
87                 resourceAssignment.message = message
88             }
89         }
90
91         @Synchronized
92         @Throws(BluePrintProcessorException::class)
93         fun assertTemplateKeyValueNotNull(resourceAssignment: ResourceAssignment) {
94             val resourceProp = checkNotNull(resourceAssignment.property) { "Failed to populate mandatory resource resource mapping $resourceAssignment" }
95             if (resourceProp.required != null && resourceProp.required!! && (resourceProp.value == null || resourceProp.value !is NullNode)) {
96                 logger.error("failed to populate mandatory resource mapping ($resourceAssignment)")
97                 throw BluePrintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)")
98             }
99         }
100
101         @Synchronized
102         @Throws(BluePrintProcessorException::class)
103         fun generateResourceDataForAssignments(assignments: List<ResourceAssignment>): String {
104             var result = "{}"
105             try {
106                 val mapper = ObjectMapper()
107                 val root = mapper.readTree(result)
108
109                 assignments.forEach {
110                     if (checkNotEmpty(it.name) && it.property != null) {
111
112                         val type = it.property?.type
113                         val value = it.property?.value
114                         logger.info("Generating Resource name ({}), type ({}), value ({})", it.name, type,
115                                 value)
116                         if (value == null) {
117                             (root as ObjectNode).set(it.name, null)
118                         } else if (value is JsonNode) {
119                             (root as ObjectNode).put(it.name, value as JsonNode)
120                         } else if (BluePrintConstants.DATA_TYPE_STRING.equals(type, ignoreCase = true)) {
121                             (root as ObjectNode).put(it.name, value as String)
122                         } else if (BluePrintConstants.DATA_TYPE_BOOLEAN.equals(type, ignoreCase = true)) {
123                             (root as ObjectNode).put(it.name, value as Boolean)
124                         } else if (BluePrintConstants.DATA_TYPE_INTEGER.equals(type, ignoreCase = true)) {
125                             (root as ObjectNode).put(it.name, value as Int)
126                         } else if (BluePrintConstants.DATA_TYPE_FLOAT.equals(type, ignoreCase = true)) {
127                             (root as ObjectNode).put(it.name, value as Float)
128                         } else if (BluePrintConstants.DATA_TYPE_TIMESTAMP.equals(type, ignoreCase = true)) {
129                             (root as ObjectNode).put(it.name, value as String)
130                         } else {
131                             val jsonNode = JacksonUtils.getJsonNode(value)
132                             if (jsonNode != null) {
133                                 (root as ObjectNode).put(it.name, jsonNode)
134                             } else {
135                                 (root as ObjectNode).set(it.name, null)
136                             }
137                         }
138                     }
139                 }
140                 result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root)
141                 logger.info("Generated Resource Param Data ({})", result)
142             } catch (e: Exception) {
143                 throw BluePrintProcessorException("kapil is failing with $e.message", e)
144             }
145
146             return result
147         }
148
149         fun <T> transformResourceSource(properties: MutableMap<String, JsonNode>, classType: Class<T>): T {
150             val content = JacksonUtils.getJson(properties)
151             return JacksonUtils.readValue(content, classType)
152                     ?: throw BluePrintProcessorException("failed to transform content($content) to type($classType)")
153         }
154
155     }
156 }