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