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