93b93fecbb86decf64ce1cca00b8fd0dce05580b
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / apps / blueprintsprocessor / functions / resource / resolution / 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.blueprintsprocessor.functions.resource.resolution.utils
18
19 import com.att.eelf.configuration.EELFLogger
20 import com.att.eelf.configuration.EELFManager
21 import com.fasterxml.jackson.databind.JsonNode
22 import com.fasterxml.jackson.databind.ObjectMapper
23 import com.fasterxml.jackson.databind.node.NullNode
24 import com.fasterxml.jackson.databind.node.ObjectNode
25 import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
26 import org.onap.ccsdk.apps.controllerblueprints.core.*
27 import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService
28 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
29 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment
30 import java.util.*
31
32 class ResourceAssignmentUtils {
33     companion object {
34
35         private val logger: EELFLogger = EELFManager.getInstance().getLogger(ResourceAssignmentUtils::class.toString())
36
37         @Synchronized
38         @Throws(BluePrintProcessorException::class)
39         fun setResourceDataValue(resourceAssignment: ResourceAssignment, raRuntimeService: ResourceAssignmentRuntimeService, value: Any?) {
40
41             val resourceProp = checkNotNull(resourceAssignment.property) { "Failed in setting resource value for resource mapping $resourceAssignment" }
42             checkNotEmptyOrThrow(resourceAssignment.name, "Failed in setting resource value for resource mapping $resourceAssignment")
43
44             if (checkNotEmpty(resourceAssignment.dictionaryName)) {
45                 resourceAssignment.dictionaryName = resourceAssignment.name
46                 logger.warn("Missing dictionary key, setting with template key (${resourceAssignment.name}) as dictionary key (${resourceAssignment.dictionaryName})")
47             }
48
49             try {
50                 if (checkNotEmpty(resourceProp.type)) {
51                     val convertedValue = convertResourceValue(resourceProp.type, value)
52                     logger.info("Setting Resource Value ($convertedValue) for Resource Name (${resourceAssignment.dictionaryName}) of type (${resourceProp.type})")
53                     setResourceValue(resourceAssignment, raRuntimeService, convertedValue)
54                     resourceAssignment.updatedDate = Date()
55                     resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
56                     resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS
57                 }
58             } catch (e: Exception) {
59                 throw BluePrintProcessorException("Failed in setting value for template key (${resourceAssignment.name}) and " +
60                         "dictionary key (${resourceAssignment.dictionaryName}) of type (${resourceProp.type}) with error message (${e.message})", e)
61             }
62         }
63
64         private fun setResourceValue(resourceAssignment: ResourceAssignment, raRuntimeService: ResourceAssignmentRuntimeService, value: JsonNode) {
65             raRuntimeService.putResolutionStore(resourceAssignment.name, value)
66             raRuntimeService.putDictionaryStore(resourceAssignment.dictionaryName!!, value)
67             resourceAssignment.property!!.value = value
68         }
69
70         private fun convertResourceValue(type: String, value: Any?): JsonNode {
71
72             return if (value == null || value is NullNode) {
73                 logger.info("Returning {} value from convertResourceValue", value)
74                 NullNode.instance
75             } else if (BluePrintTypes.validPrimitiveTypes().contains(type) && value is String) {
76                 JacksonUtils.convertPrimitiveResourceValue(type, value)
77             } else if (value is String) {
78                 JacksonUtils.jsonNode(value)
79             } else {
80                 JacksonUtils.getJsonNode(value)
81             }
82
83         }
84
85         @Synchronized
86         fun setFailedResourceDataValue(resourceAssignment: ResourceAssignment, message: String?) {
87             if (checkNotEmpty(resourceAssignment.name)) {
88                 resourceAssignment.updatedDate = Date()
89                 resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
90                 resourceAssignment.status = BluePrintConstants.STATUS_FAILURE
91                 resourceAssignment.message = message
92             }
93         }
94
95         @Synchronized
96         @Throws(BluePrintProcessorException::class)
97         fun assertTemplateKeyValueNotNull(resourceAssignment: ResourceAssignment) {
98             val resourceProp = checkNotNull(resourceAssignment.property) { "Failed to populate mandatory resource resource mapping $resourceAssignment" }
99             if (resourceProp.required != null && resourceProp.required!! && (resourceProp.value == null || resourceProp.value !is NullNode)) {
100                 logger.error("failed to populate mandatory resource mapping ($resourceAssignment)")
101                 throw BluePrintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)")
102             }
103         }
104
105         @Synchronized
106         @Throws(BluePrintProcessorException::class)
107         fun generateResourceDataForAssignments(assignments: List<ResourceAssignment>): String {
108             var result = "{}"
109             try {
110                 val mapper = ObjectMapper()
111                 val root = mapper.readTree(result)
112
113                 assignments.forEach {
114                     if (checkNotEmpty(it.name) && it.property != null) {
115                         val rName = it.name
116                         val type = nullToEmpty(it.property?.type).toLowerCase()
117                         val value = it.property?.value
118                         logger.info("Generating Resource name ($rName), type ($type), value ($value)")
119
120                         when (value) {
121                             null -> (root as ObjectNode).set(rName, null)
122                             is JsonNode -> (root as ObjectNode).set(rName, value)
123                             else -> {
124                                 when (type) {
125                                     BluePrintConstants.DATA_TYPE_TIMESTAMP -> (root as ObjectNode).put(rName, value as String)
126                                     BluePrintConstants.DATA_TYPE_STRING -> (root as ObjectNode).put(rName, value as String)
127                                     BluePrintConstants.DATA_TYPE_BOOLEAN -> (root as ObjectNode).put(rName, value as Boolean)
128                                     BluePrintConstants.DATA_TYPE_INTEGER -> (root as ObjectNode).put(rName, value as Int)
129                                     BluePrintConstants.DATA_TYPE_FLOAT -> (root as ObjectNode).put(rName, value as Float)
130                                     else -> {
131                                         (root as ObjectNode).set(rName, JacksonUtils.getJsonNode(value))
132                                     }
133                                 }
134                             }
135                         }
136                     }
137                 }
138                 result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root)
139                 logger.info("Generated Resource Param Data ($result)")
140             } catch (e: Exception) {
141                 throw BluePrintProcessorException("Resource Assignment is failed with $e.message", e)
142             }
143
144             return result
145         }
146
147         fun transformToRARuntimeService(blueprintRuntimeService: BluePrintRuntimeService<*>, templateArtifactName: String): ResourceAssignmentRuntimeService {
148             val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService(blueprintRuntimeService.id(), blueprintRuntimeService.bluePrintContext())
149             resourceAssignmentRuntimeService.createUniqueId(templateArtifactName)
150             resourceAssignmentRuntimeService.setExecutionContext(blueprintRuntimeService.getExecutionContext() as MutableMap<String, JsonNode>)
151
152             return resourceAssignmentRuntimeService
153         }
154
155         /*
156          * Populate the Field property type for the Data type
157          */
158         @Synchronized
159         @Throws(BluePrintProcessorException::class)
160         fun getPropertyType(raRuntimeService: ResourceAssignmentRuntimeService, dataTypeName: String, propertyName: String): String {
161             lateinit var type: String
162             try {
163                 val dataTypeProps = checkNotNull(raRuntimeService.bluePrintContext().dataTypeByName(dataTypeName)?.properties)
164                 val propertyDefinition = checkNotNull(dataTypeProps[propertyName])
165                 type = returnNotEmptyOrThrow(propertyDefinition.type) { "Couldn't get data type ($dataTypeName)" }
166                 logger.trace("Data type({})'s property ({}) is ({})", dataTypeName, propertyName, type)
167             } catch (e: Exception) {
168                 logger.error("couldn't get data type($dataTypeName)'s property ($propertyName), error message $e")
169                 throw BluePrintProcessorException("${e.message}", e)
170             }
171             return type
172         }
173     }
174 }