cea18ef9b46f68f38707100eebdc6558a8cc79a8
[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.helpers.MessageFormatter
25 import kotlin.reflect.KClass
26
27 /**
28  *
29  *
30  * @author Brinda Santh
31  */
32
33 fun <T : Any> T.bpClone(): T {
34     return ObjectUtils.clone(this)
35 }
36
37 fun String.isJson(): Boolean {
38     return ((this.startsWith("{") && this.endsWith("}"))
39             || (this.startsWith("[") && this.endsWith("]")))
40 }
41
42 fun Any.asJsonString(intend: Boolean? = false): String {
43     return JacksonUtils.getJson(this, intend!!)
44 }
45
46 fun String.asJsonPrimitive(): TextNode {
47     return TextNode(this)
48 }
49
50 // If you know the string is json content, then use the function directly
51 fun String.jsonAsJsonType(): JsonNode {
52     return JacksonUtils.jsonNode(this.trim())
53 }
54
55 fun Boolean.asJsonPrimitive(): BooleanNode {
56     return BooleanNode.valueOf(this)
57 }
58
59 fun Int.asJsonPrimitive(): IntNode {
60     return IntNode.valueOf(this)
61 }
62
63 fun Double.asJsonPrimitive(): DoubleNode {
64     return DoubleNode.valueOf(this)
65 }
66
67 /**
68  * Utility to convert Primitive object to Json Type Primitive.
69  */
70 fun <T : Any?> T.asJsonPrimitive(): JsonNode {
71     return if (this == null || this is MissingNode || this is NullNode) {
72         NullNode.instance
73     } else {
74         when (this) {
75             is String ->
76                 this.asJsonPrimitive()
77             is Boolean ->
78                 this.asJsonPrimitive()
79             is Int ->
80                 this.asJsonPrimitive()
81             is Double ->
82                 this.asJsonPrimitive()
83             else ->
84                 throw BluePrintException("$this type is not supported")
85         }
86     }
87 }
88
89 /**
90  * Utility to convert Complex or Primitive object to Json Type.
91  */
92 fun <T : Any?> T.asJsonType(): JsonNode {
93     return if (this == null || this is MissingNode || this is NullNode) {
94         NullNode.instance
95     } else {
96         when (this) {
97             is JsonNode ->
98                 this
99             is String -> {
100                 if (this.isJson())
101                     this.jsonAsJsonType()
102                 else
103                     TextNode(this)
104             }
105             is Boolean ->
106                 BooleanNode.valueOf(this)
107             is Int ->
108                 IntNode.valueOf(this.toInt())
109             is Double ->
110                 DoubleNode.valueOf(this.toDouble())
111             else ->
112                 JacksonUtils.jsonNodeFromObject(this)
113         }
114     }
115 }
116
117 fun Map<String, *>.asJsonNode(): JsonNode {
118     return JacksonUtils.jsonNodeFromObject(this)
119 }
120
121 fun Map<String, *>.asObjectNode(): ObjectNode {
122     return JacksonUtils.objectNodeFromObject(this)
123 }
124
125 fun format(message: String, vararg args: Any?): String {
126     if (args != null && args.isNotEmpty()) {
127         return MessageFormatter.arrayFormat(message, args).message
128     }
129     return message
130 }
131
132 fun <T : Any> Map<String, *>.castOptionalValue(key: String, valueType: KClass<T>): T? {
133     return if (containsKey(key)) {
134         get(key) as? T
135     } else {
136         null
137     }
138 }
139
140 fun <T : Any> Map<String, *>.castValue(key: String, valueType: KClass<T>): T {
141     if (containsKey(key)) {
142         return get(key) as T
143     } else {
144         throw BluePrintException("couldn't find the key $key")
145     }
146 }
147
148 fun ArrayNode.asListOfString(): List<String> {
149     return JacksonUtils.getListFromJsonNode(this, String::class.java)
150 }
151
152 fun JsonNode.returnNullIfMissing(): JsonNode? {
153     return if (this is NullNode || this is MissingNode) {
154         null
155     } else this
156 }
157
158 fun <T : JsonNode> T?.isNull(): Boolean {
159     return this == null || this is NullNode || this is MissingNode
160 }
161
162 fun <T : JsonNode> T?.isNotNull(): Boolean {
163     return !(this == null || this is NullNode || this is MissingNode)
164 }
165
166 /**
167  * Convert Json to map of json node, the root fields will be map keys
168  */
169 fun JsonNode.rootFieldsToMap(): MutableMap<String, JsonNode> {
170     if (this is ObjectNode) {
171         val propertyMap: MutableMap<String, JsonNode> = linkedMapOf()
172         this.fields().forEach {
173             propertyMap[it.key] = it.value
174         }
175         return propertyMap
176     } else {
177         throw BluePrintException("json node should be Object Node Type")
178     }
179 }
180
181 fun JsonNode.removeNullNode() {
182     val it = this.iterator()
183     while (it.hasNext()) {
184         val child = it.next()
185         if (child.isNull) {
186             it.remove()
187         } else {
188             child.removeNullNode()
189         }
190     }
191 }
192
193
194 fun MutableMap<String, JsonNode>.putJsonElement(key: String, value: Any) {
195     val convertedValue = value.asJsonType()
196     this[key] = convertedValue
197 }
198
199 fun Map<String, JsonNode>.getAsString(key: String): String {
200     return this[key]?.asText() ?: throw BluePrintException("couldn't find value for key($key)")
201 }
202
203 fun Map<String, JsonNode>.getAsBoolean(key: String): Boolean {
204     return this[key]?.asBoolean() ?: throw BluePrintException("couldn't find value for key($key)")
205 }
206
207 fun Map<String, JsonNode>.getAsInt(key: String): Int {
208     return this[key]?.asInt() ?: throw BluePrintException("couldn't find value for key($key)")
209 }
210
211 fun Map<String, JsonNode>.getAsDouble(key: String): Double {
212     return this[key]?.asDouble() ?: throw BluePrintException("couldn't find value for key($key)")
213 }
214
215 // Checks
216
217 inline fun checkEquals(value1: String?, value2: String?, lazyMessage: () -> Any): Boolean {
218     if (value1.equals(value2, ignoreCase = true)) {
219         return true
220     } else {
221         throw BluePrintException(lazyMessage().toString())
222     }
223 }
224
225 inline fun checkNotEmpty(value: String?, lazyMessage: () -> Any): String {
226     if (value == null || value.isEmpty()) {
227         val message = lazyMessage()
228         throw IllegalStateException(message.toString())
229     } else {
230         return value
231     }
232 }
233
234 inline fun checkNotBlank(value: String?, lazyMessage: () -> Any): String {
235     if (value == null || value.isBlank()) {
236         val message = lazyMessage()
237         throw IllegalStateException(message.toString())
238     } else {
239         return value
240     }
241 }
242
243 fun isNotEmpty(value: String?): Boolean {
244     return value != null && value.isNotEmpty()
245 }
246
247 fun isNotBlank(value: String?): Boolean {
248     return value != null && value.isNotBlank()
249 }
250
251
252 fun nullToEmpty(value: String?): String {
253     return if (isNotEmpty(value)) value!! else ""
254 }
255
256