Resource resolution should return a string
[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.slf4j.LoggerFactory
25 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JsonParserUtils
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 // If you know the string is json content, then use the function directly
58 fun String.jsonAsJsonType(): JsonNode {
59     return JacksonUtils.jsonNode(this.trim())
60 }
61
62 fun Boolean.asJsonPrimitive(): BooleanNode {
63     return BooleanNode.valueOf(this)
64 }
65
66 fun Int.asJsonPrimitive(): IntNode {
67     return IntNode.valueOf(this)
68 }
69
70 fun Double.asJsonPrimitive(): DoubleNode {
71     return DoubleNode.valueOf(this)
72 }
73
74 /**
75  * Utility to convert Primitive object to Json Type Primitive.
76  */
77 fun <T : Any?> T.asJsonPrimitive(): JsonNode {
78     return if (this == null || this is MissingNode || this is NullNode) {
79         NullNode.instance
80     } else {
81         when (this) {
82             is String ->
83                 this.asJsonPrimitive()
84             is Boolean ->
85                 this.asJsonPrimitive()
86             is Int ->
87                 this.asJsonPrimitive()
88             is Double ->
89                 this.asJsonPrimitive()
90             else ->
91                 throw BluePrintException("$this type is not supported")
92         }
93     }
94 }
95
96 /**
97  * Utility to convert Complex or Primitive object to Json Type.
98  */
99 fun <T : Any?> T.asJsonType(): JsonNode {
100     return if (this == null || this is MissingNode || this is NullNode) {
101         NullNode.instance
102     } else {
103         when (this) {
104             is JsonNode ->
105                 this
106             is String -> {
107                 if (this.isJson())
108                     this.jsonAsJsonType()
109                 else
110                     TextNode(this)
111             }
112             is Boolean ->
113                 BooleanNode.valueOf(this)
114             is Int ->
115                 IntNode.valueOf(this.toInt())
116             is Double ->
117                 DoubleNode.valueOf(this.toDouble())
118             else ->
119                 JacksonUtils.jsonNodeFromObject(this)
120         }
121     }
122 }
123
124 fun Map<String, *>.asJsonNode(): JsonNode {
125     return JacksonUtils.jsonNodeFromObject(this)
126 }
127
128 fun Map<String, *>.asObjectNode(): ObjectNode {
129     return JacksonUtils.objectNodeFromObject(this)
130 }
131
132 fun format(message: String, vararg args: Any?): String {
133     if (args != null && args.isNotEmpty()) {
134         return MessageFormatter.arrayFormat(message, args).message
135     }
136     return message
137 }
138
139 fun <T : Any> Map<String, *>.castOptionalValue(key: String, valueType: KClass<T>): T? {
140     return if (containsKey(key)) {
141         get(key) as? T
142     } else {
143         null
144     }
145 }
146
147 fun <T : Any> Map<String, *>.castValue(key: String, valueType: KClass<T>): T {
148     if (containsKey(key)) {
149         return get(key) as T
150     } else {
151         throw BluePrintException("couldn't find the key $key")
152     }
153 }
154
155 fun ArrayNode.asListOfString(): List<String> {
156     return JacksonUtils.getListFromJsonNode(this, String::class.java)
157 }
158
159 fun JsonNode.returnNullIfMissing(): JsonNode? {
160     return if (this is NullNode || this is MissingNode) {
161         null
162     } else this
163 }
164
165 fun <T : JsonNode> T?.isNull(): Boolean {
166     return this == null || this is NullNode || this is MissingNode
167 }
168
169 fun <T : JsonNode> T?.isNotNull(): Boolean {
170     return !(this == null || this is NullNode || this is MissingNode)
171 }
172
173 /**
174  * Convert Json to map of json node, the root fields will be map keys
175  */
176 fun JsonNode.rootFieldsToMap(): MutableMap<String, JsonNode> {
177     if (this is ObjectNode) {
178         val propertyMap: MutableMap<String, JsonNode> = linkedMapOf()
179         this.fields().forEach {
180             propertyMap[it.key] = it.value
181         }
182         return propertyMap
183     } else {
184         throw BluePrintException("json node should be Object Node Type")
185     }
186 }
187
188 fun JsonNode.removeNullNode() {
189     val it = this.iterator()
190     while (it.hasNext()) {
191         val child = it.next()
192         if (child.isNull) {
193             it.remove()
194         } else {
195             child.removeNullNode()
196         }
197     }
198 }
199
200
201 fun MutableMap<String, JsonNode>.putJsonElement(key: String, value: Any) {
202     val convertedValue = value.asJsonType()
203     this[key] = convertedValue
204 }
205
206 fun Map<String, JsonNode>.getAsString(key: String): String {
207     return this[key]?.asText() ?: throw BluePrintException("couldn't find value for key($key)")
208 }
209
210 fun Map<String, JsonNode>.getAsBoolean(key: String): Boolean {
211     return this[key]?.asBoolean() ?: throw BluePrintException("couldn't find value for key($key)")
212 }
213
214 fun Map<String, JsonNode>.getAsInt(key: String): Int {
215     return this[key]?.asInt() ?: throw BluePrintException("couldn't find value for key($key)")
216 }
217
218 fun Map<String, JsonNode>.getAsDouble(key: String): Double {
219     return this[key]?.asDouble() ?: throw BluePrintException("couldn't find value for key($key)")
220 }
221
222 // Checks
223
224 inline fun checkEquals(value1: String?, value2: String?, lazyMessage: () -> Any): Boolean {
225     if (value1.equals(value2, ignoreCase = true)) {
226         return true
227     } else {
228         throw BluePrintException(lazyMessage().toString())
229     }
230 }
231
232 inline fun checkNotEmpty(value: String?, lazyMessage: () -> Any): String {
233     if (value == null || value.isEmpty()) {
234         val message = lazyMessage()
235         throw IllegalStateException(message.toString())
236     } else {
237         return value
238     }
239 }
240
241 inline fun checkNotBlank(value: String?, lazyMessage: () -> Any): String {
242     if (value == null || value.isBlank()) {
243         val message = lazyMessage()
244         throw IllegalStateException(message.toString())
245     } else {
246         return value
247     }
248 }
249
250 fun isNotEmpty(value: String?): Boolean {
251     return value != null && value.isNotEmpty()
252 }
253
254 fun isNotBlank(value: String?): Boolean {
255     return value != null && value.isNotBlank()
256 }
257
258
259 fun nullToEmpty(value: String?): String {
260     return if (isNotEmpty(value)) value!! else ""
261 }
262
263 inline fun <reified T : JsonNode> T.isComplexType(): Boolean {
264     return this is ObjectNode || this is ArrayNode
265 }
266
267 // Json Parsing Extensions
268 fun JsonNode.jsonPathParse(expression: String): JsonNode {
269     check(this.isComplexType()) { "$this is not complex or array node to apply expression" }
270     return JsonParserUtils.parse(this, expression)
271 }
272
273 // Json Path Extensions
274 fun JsonNode.jsonPaths(expression: String): List<String> {
275     check(this.isComplexType()) { "$this is not complex or array node to apply expression" }
276     return JsonParserUtils.paths(this, expression)
277 }
278
279