Merge "Passing Option from Search DB to metadata"
[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 // 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 /** Based on Blueprint DataType Convert string value to JsonNode Type **/
97 fun String.asJsonType(bpDataType: String): JsonNode {
98     return when (bpDataType.toLowerCase()) {
99         BluePrintConstants.DATA_TYPE_STRING -> this.asJsonPrimitive()
100         BluePrintConstants.DATA_TYPE_BOOLEAN -> this.toBoolean().asJsonPrimitive()
101         BluePrintConstants.DATA_TYPE_INTEGER -> this.toInt().asJsonPrimitive()
102         BluePrintConstants.DATA_TYPE_FLOAT -> this.toFloat().asJsonPrimitive()
103         BluePrintConstants.DATA_TYPE_DOUBLE -> this.toDouble().asJsonPrimitive()
104         // For List, Map and Complex Types.
105         else -> this.jsonAsJsonType()
106     }
107 }
108
109 /**
110  * Utility to convert Complex or Primitive object to Json Type.
111  */
112 fun <T : Any?> T.asJsonType(): JsonNode {
113     return if (this == null || this is MissingNode || this is NullNode) {
114         NullNode.instance
115     } else {
116         when (this) {
117             is JsonNode ->
118                 this
119             is String -> {
120                 if (this.isJson())
121                     this.jsonAsJsonType()
122                 else
123                     TextNode(this)
124             }
125             is Boolean ->
126                 BooleanNode.valueOf(this)
127             is Int ->
128                 IntNode.valueOf(this.toInt())
129             is Double ->
130                 DoubleNode.valueOf(this.toDouble())
131             else ->
132                 JacksonUtils.jsonNodeFromObject(this)
133         }
134     }
135 }
136
137 fun Map<String, *>.asJsonNode(): JsonNode {
138     return JacksonUtils.jsonNodeFromObject(this)
139 }
140
141 fun Map<String, *>.asObjectNode(): ObjectNode {
142     return JacksonUtils.objectNodeFromObject(this)
143 }
144
145 fun format(message: String, vararg args: Any?): String {
146     if (args != null && args.isNotEmpty()) {
147         return MessageFormatter.arrayFormat(message, args).message
148     }
149     return message
150 }
151
152 fun <T : Any> Map<String, *>.castOptionalValue(key: String, valueType: KClass<T>): T? {
153     return if (containsKey(key)) {
154         get(key) as? T
155     } else {
156         null
157     }
158 }
159
160 fun <T : Any> Map<String, *>.castValue(key: String, valueType: KClass<T>): T {
161     if (containsKey(key)) {
162         return get(key) as T
163     } else {
164         throw BluePrintException("couldn't find the key $key")
165     }
166 }
167
168 fun ArrayNode.asListOfString(): List<String> {
169     return JacksonUtils.getListFromJsonNode(this, String::class.java)
170 }
171
172 fun <T> JsonNode.asType(clazzType: Class<T>): T {
173     return JacksonUtils.readValue(this, clazzType)
174             ?: throw BluePrintException("couldn't convert JsonNode of type $clazzType")
175 }
176
177 fun JsonNode.asListOfString(): List<String> {
178     check(this is ArrayNode) { "JsonNode is not of type ArrayNode" }
179     return this.asListOfString()
180 }
181
182 fun JsonNode.returnNullIfMissing(): JsonNode? {
183     return if (this is NullNode || this is MissingNode) {
184         null
185     } else this
186 }
187
188 fun <T : JsonNode> T?.isNull(): Boolean {
189     return this == null || this is NullNode || this is MissingNode
190 }
191
192 fun <T : JsonNode> T?.isNotNull(): Boolean {
193     return !(this == null || this is NullNode || this is MissingNode)
194 }
195
196 /**
197  * Convert Json to map of json node, the root fields will be map keys
198  */
199 fun JsonNode.rootFieldsToMap(): MutableMap<String, JsonNode> {
200     if (this is ObjectNode) {
201         val propertyMap: MutableMap<String, JsonNode> = linkedMapOf()
202         this.fields().forEach {
203             propertyMap[it.key] = it.value
204         }
205         return propertyMap
206     } else {
207         throw BluePrintException("json node should be Object Node Type")
208     }
209 }
210
211 fun JsonNode.removeNullNode() {
212     val it = this.iterator()
213     while (it.hasNext()) {
214         val child = it.next()
215         if (child.isNull) {
216             it.remove()
217         } else {
218             child.removeNullNode()
219         }
220     }
221 }
222
223
224 fun MutableMap<String, JsonNode>.putJsonElement(key: String, value: Any) {
225     val convertedValue = value.asJsonType()
226     this[key] = convertedValue
227 }
228
229 fun Map<String, JsonNode>.getAsString(key: String): String {
230     return this[key]?.asText() ?: throw BluePrintException("couldn't find value for key($key)")
231 }
232
233 fun Map<String, JsonNode>.getAsBoolean(key: String): Boolean {
234     return this[key]?.asBoolean() ?: throw BluePrintException("couldn't find value for key($key)")
235 }
236
237 fun Map<String, JsonNode>.getAsInt(key: String): Int {
238     return this[key]?.asInt() ?: throw BluePrintException("couldn't find value for key($key)")
239 }
240
241 fun Map<String, JsonNode>.getAsDouble(key: String): Double {
242     return this[key]?.asDouble() ?: throw BluePrintException("couldn't find value for key($key)")
243 }
244
245 fun Map<String, JsonNode>.getOptionalAsString(key: String): String? {
246     return if (this.containsKey(key)) this[key]!!.asText() else null
247 }
248
249 fun Map<String, JsonNode>.getOptionalAsBoolean(key: String): Boolean? {
250     return if (this.containsKey(key)) this[key]!!.asBoolean() else null
251 }
252
253 fun Map<String, JsonNode>.getOptionalAsInt(key: String): Int? {
254     return if (this.containsKey(key)) this[key]!!.asInt() else null
255 }
256
257 fun Map<String, JsonNode>.getOptionalAsDouble(key: String): Double? {
258     return if (this.containsKey(key)) this[key]!!.asDouble() else null
259 }
260
261 // Checks
262
263 inline fun checkEquals(value1: String?, value2: String?, lazyMessage: () -> Any): Boolean {
264     if (value1.equals(value2, ignoreCase = true)) {
265         return true
266     } else {
267         throw BluePrintException(lazyMessage().toString())
268     }
269 }
270
271 inline fun checkNotEmpty(value: String?, lazyMessage: () -> Any): String {
272     if (value == null || value.isEmpty()) {
273         val message = lazyMessage()
274         throw IllegalStateException(message.toString())
275     } else {
276         return value
277     }
278 }
279
280 inline fun checkNotBlank(value: String?, lazyMessage: () -> Any): String {
281     if (value == null || value.isBlank()) {
282         val message = lazyMessage()
283         throw IllegalStateException(message.toString())
284     } else {
285         return value
286     }
287 }
288
289 fun isNotEmpty(value: String?): Boolean {
290     return value != null && value.isNotEmpty()
291 }
292
293 fun isNotBlank(value: String?): Boolean {
294     return value != null && value.isNotBlank()
295 }
296
297 fun <T : String> T?.emptyTONull(): String? {
298     return if (this == null || this.isEmpty()) null else this
299 }
300
301 fun nullToEmpty(value: String?): String {
302     return if (isNotEmpty(value)) value!! else ""
303 }
304
305 inline fun <reified T : JsonNode> T.isComplexType(): Boolean {
306     return this is ObjectNode || this is ArrayNode
307 }
308
309 // Json Parsing Extensions
310 fun JsonNode.jsonPathParse(expression: String): JsonNode {
311     check(this.isComplexType()) { "$this is not complex or array node to apply expression" }
312     return JsonParserUtils.parse(this, expression)
313 }
314
315 // Json Path Extensions
316 fun JsonNode.jsonPaths(expression: String): List<String> {
317     check(this.isComplexType()) { "$this is not complex or array node to apply expression" }
318     return JsonParserUtils.paths(this, expression)
319 }
320
321