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