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