Refactoring ResourceAssignmentUtils
[ccsdk/cds.git] / ms / controllerblueprints / modules / blueprint-core / src / main / kotlin / org / onap / ccsdk / cds / controllerblueprints / core / CustomFunctions.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.controllerblueprints.core
19
20 import com.fasterxml.jackson.databind.JsonNode
21 import com.fasterxml.jackson.databind.node.*
22 import org.apache.commons.lang3.ObjectUtils
23 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
24 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JsonParserUtils
25 import org.slf4j.LoggerFactory
26 import org.slf4j.helpers.MessageFormatter
27 import kotlin.reflect.KClass
28
29 /**
30  *
31  *
32  * @author Brinda Santh
33  */
34
35 fun <T : Any> logger(clazz: T) = LoggerFactory.getLogger(clazz.javaClass)!!
36
37 fun <T : KClass<*>> logger(clazz: T) = LoggerFactory.getLogger(clazz.java)!!
38
39
40 fun <T : Any> T.bpClone(): T {
41     return ObjectUtils.clone(this)
42 }
43
44 fun String.isJson(): Boolean {
45     return ((this.trim().startsWith("{") && this.trim().endsWith("}"))
46             || (this.trim().startsWith("[") && this.trim().endsWith("]")))
47 }
48
49 fun Any.asJsonString(intend: Boolean? = false): String {
50     return JacksonUtils.getJson(this, intend!!)
51 }
52
53 fun String.asJsonPrimitive(): TextNode {
54     return TextNode(this)
55 }
56
57 inline fun <reified T : Any> String.jsonAsType(): T {
58     return JacksonUtils.readValue<T>(this.trim())
59 }
60
61 // If you know the string is json content, then use the function directly
62 fun String.jsonAsJsonType(): JsonNode {
63     return JacksonUtils.jsonNode(this.trim())
64 }
65
66 fun Boolean.asJsonPrimitive(): BooleanNode {
67     return BooleanNode.valueOf(this)
68 }
69
70 fun Int.asJsonPrimitive(): IntNode {
71     return IntNode.valueOf(this)
72 }
73
74 fun Double.asJsonPrimitive(): DoubleNode {
75     return DoubleNode.valueOf(this)
76 }
77
78 /**
79  * Utility to convert Primitive object to Json Type Primitive.
80  */
81 fun <T : Any?> T.asJsonPrimitive(): JsonNode {
82     return if (this == null || this is MissingNode || this is NullNode) {
83         NullNode.instance
84     } else {
85         when (this) {
86             is String ->
87                 this.asJsonPrimitive()
88             is Boolean ->
89                 this.asJsonPrimitive()
90             is Int ->
91                 this.asJsonPrimitive()
92             is Double ->
93                 this.asJsonPrimitive()
94             else ->
95                 throw BluePrintException("$this type is not supported")
96         }
97     }
98 }
99
100 /** Based on Blueprint DataType Convert string value to JsonNode Type **/
101 fun String.asJsonType(bpDataType: String): JsonNode {
102     return when (bpDataType.toLowerCase()) {
103         BluePrintConstants.DATA_TYPE_STRING -> this.asJsonPrimitive()
104         BluePrintConstants.DATA_TYPE_BOOLEAN -> this.toBoolean().asJsonPrimitive()
105         BluePrintConstants.DATA_TYPE_INTEGER -> this.toInt().asJsonPrimitive()
106         BluePrintConstants.DATA_TYPE_FLOAT -> this.toFloat().asJsonPrimitive()
107         BluePrintConstants.DATA_TYPE_DOUBLE -> this.toDouble().asJsonPrimitive()
108         // For List, Map and Complex Types.
109         else -> this.jsonAsJsonType()
110     }
111 }
112
113 /**
114  * Utility to convert Complex or Primitive object to Json Type.
115  */
116 fun <T : Any?> T.asJsonType(): JsonNode {
117     return if (this == null || this is MissingNode || this is NullNode) {
118         NullNode.instance
119     } else {
120         when (this) {
121             is JsonNode ->
122                 this
123             is String -> {
124                 if (this.isJson())
125                     this.jsonAsJsonType()
126                 else
127                     TextNode(this)
128             }
129             is Boolean ->
130                 BooleanNode.valueOf(this)
131             is Int ->
132                 IntNode.valueOf(this.toInt())
133             is Double ->
134                 DoubleNode.valueOf(this.toDouble())
135             else ->
136                 JacksonUtils.jsonNodeFromObject(this)
137         }
138     }
139 }
140
141 fun Map<String, *>.asJsonNode(): JsonNode {
142     return JacksonUtils.jsonNodeFromObject(this)
143 }
144
145 fun Map<String, *>.asObjectNode(): ObjectNode {
146     return JacksonUtils.objectNodeFromObject(this)
147 }
148
149 fun format(message: String, vararg args: Any?): String {
150     if (args != null && args.isNotEmpty()) {
151         return MessageFormatter.arrayFormat(message, args).message
152     }
153     return message
154 }
155
156 fun <T : Any> Map<String, *>.castOptionalValue(key: String, valueType: KClass<T>): T? {
157     return if (containsKey(key)) {
158         get(key) as? T
159     } else {
160         null
161     }
162 }
163
164 fun <T : Any> Map<String, *>.castValue(key: String, valueType: KClass<T>): T {
165     if (containsKey(key)) {
166         return get(key) as T
167     } else {
168         throw BluePrintException("couldn't find the key $key")
169     }
170 }
171
172 fun ArrayNode.asListOfString(): List<String> {
173     return JacksonUtils.getListFromJsonNode(this, String::class.java)
174 }
175
176 fun <T> JsonNode.asType(clazzType: Class<T>): T {
177     return JacksonUtils.readValue(this, clazzType)
178         ?: throw BluePrintException("couldn't convert JsonNode of type $clazzType")
179 }
180
181 fun JsonNode.asListOfString(): List<String> {
182     check(this is ArrayNode) { "JsonNode is not of type ArrayNode" }
183     return this.asListOfString()
184 }
185
186 fun <T : JsonNode> T?.returnNullIfMissing(): JsonNode? {
187     return if (this == null || this is NullNode || this is MissingNode) {
188         null
189     }
190     else this
191 }
192
193 fun <T : JsonNode> T?.isNullOrMissing(): Boolean {
194     return this == null || this is NullNode || this is MissingNode
195 }
196
197 /**
198  * Convert Json to map of json node, the root fields will be map keys
199  */
200 fun JsonNode.rootFieldsToMap(): MutableMap<String, JsonNode> {
201     if (this is ObjectNode) {
202         val propertyMap: MutableMap<String, JsonNode> = linkedMapOf()
203         this.fields().forEach {
204             propertyMap[it.key] = it.value
205         }
206         return propertyMap
207     } else {
208         throw BluePrintException("json node should be Object Node Type")
209     }
210 }
211
212 fun JsonNode.removeNullNode() {
213     val it = this.iterator()
214     while (it.hasNext()) {
215         val child = it.next()
216         if (child.isNull) {
217             it.remove()
218         } else {
219             child.removeNullNode()
220         }
221     }
222 }
223
224
225 fun MutableMap<String, JsonNode>.putJsonElement(key: String, value: Any) {
226     val convertedValue = value.asJsonType()
227     this[key] = convertedValue
228 }
229
230 fun Map<String, JsonNode>.getAsString(key: String): String {
231     return this[key]?.asText() ?: throw BluePrintException("couldn't find value for key($key)")
232 }
233
234 fun Map<String, JsonNode>.getAsBoolean(key: String): Boolean {
235     return this[key]?.asBoolean() ?: throw BluePrintException("couldn't find value for key($key)")
236 }
237
238 fun Map<String, JsonNode>.getAsInt(key: String): Int {
239     return this[key]?.asInt() ?: throw BluePrintException("couldn't find value for key($key)")
240 }
241
242 fun Map<String, JsonNode>.getAsDouble(key: String): Double {
243     return this[key]?.asDouble() ?: throw BluePrintException("couldn't find value for key($key)")
244 }
245
246 fun Map<String, JsonNode>.getOptionalAsString(key: String): String? {
247     return if (this.containsKey(key)) this[key]!!.asText() else null
248 }
249
250 fun Map<String, JsonNode>.getOptionalAsBoolean(key: String): Boolean? {
251     return if (this.containsKey(key)) this[key]!!.asBoolean() else null
252 }
253
254 fun Map<String, JsonNode>.getOptionalAsInt(key: String): Int? {
255     return if (this.containsKey(key)) this[key]!!.asInt() else null
256 }
257
258 fun Map<String, JsonNode>.getOptionalAsDouble(key: String): Double? {
259     return if (this.containsKey(key)) this[key]!!.asDouble() else null
260 }
261
262 // Checks
263
264 inline fun checkEquals(value1: String?, value2: String?, lazyMessage: () -> Any): Boolean {
265     if (value1.equals(value2, ignoreCase = true)) {
266         return true
267     } else {
268         throw BluePrintException(lazyMessage().toString())
269     }
270 }
271
272 inline fun checkNotEmpty(value: String?, lazyMessage: () -> Any): String {
273     if (value == null || value.isEmpty()) {
274         val message = lazyMessage()
275         throw IllegalStateException(message.toString())
276     } else {
277         return value
278     }
279 }
280
281 inline fun checkNotBlank(value: String?, lazyMessage: () -> Any): String {
282     if (value == null || value.isBlank()) {
283         val message = lazyMessage()
284         throw IllegalStateException(message.toString())
285     } else {
286         return value
287     }
288 }
289
290 fun isNotEmpty(value: String?): Boolean {
291     return value != null && value.isNotEmpty()
292 }
293
294 fun isNotBlank(value: String?): Boolean {
295     return value != null && value.isNotBlank()
296 }
297
298 fun <T : String> T?.emptyTONull(): String? {
299     return if (this == null || this.isEmpty()) null else this
300 }
301
302 fun nullToEmpty(value: String?): String {
303     return if (isNotEmpty(value)) value!! else ""
304 }
305
306 inline fun <reified T : JsonNode> T.isComplexType(): Boolean {
307     return this is ObjectNode || this is ArrayNode
308 }
309
310 // Json Parsing Extensions
311 fun JsonNode.jsonPathParse(expression: String): JsonNode {
312     check(this.isComplexType()) { "$this is not complex or array node to apply expression" }
313     return JsonParserUtils.parse(this, expression)
314 }
315
316 // Json Path Extensions
317 fun JsonNode.jsonPaths(expression: String): List<String> {
318     check(this.isComplexType()) { "$this is not complex or array node to apply expression" }
319     return JsonParserUtils.paths(this, expression)
320 }
321
322