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