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