ab54f566df3032fd79ab1b5c5bda751d4be3e9c7
[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.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, true)
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 fun <T : Any?> T.asJsonType(): JsonNode {
68     return if (this == null) {
69         NullNode.instance
70     } else {
71         when (this) {
72             is JsonNode ->
73                 this
74             is String -> {
75                 if (this.isJson())
76                     this.jsonAsJsonType()
77                 else
78                     TextNode(this)
79             }
80             is Boolean ->
81                 BooleanNode.valueOf(this)
82             is Int ->
83                 IntNode.valueOf(this.toInt())
84             is Double ->
85                 DoubleNode.valueOf(this.toDouble())
86             else ->
87                 JacksonUtils.jsonNodeFromObject(this)
88         }
89     }
90 }
91
92 fun Map<String, *>.asJsonNode(): JsonNode {
93     return JacksonUtils.jsonNodeFromObject(this)
94 }
95
96 fun Map<String, *>.asObjectNode(): ObjectNode {
97     return JacksonUtils.objectNodeFromObject(this)
98 }
99
100 fun format(message: String, vararg args: Any?): String {
101     if (args != null && args.isNotEmpty()) {
102         return MessageFormatter.arrayFormat(message, args).message
103     }
104     return message
105 }
106
107 fun <T : Any> Map<String, *>.castOptionalValue(key: String, valueType: KClass<T>): T? {
108     return if (containsKey(key)) {
109         get(key) as? T
110     } else {
111         null
112     }
113 }
114
115 fun <T : Any> Map<String, *>.castValue(key: String, valueType: KClass<T>): T {
116     if (containsKey(key)) {
117         return get(key) as T
118     } else {
119         throw BluePrintException("couldn't find the key $key")
120     }
121 }
122
123 fun ArrayNode.asListOfString(): List<String> {
124     return JacksonUtils.getListFromJsonNode(this, String::class.java)
125 }
126
127 fun JsonNode.returnNullIfMissing(): JsonNode? {
128     return if (this is NullNode || this is MissingNode) {
129         null
130     } else this
131 }
132
133 /**
134  * Convert Json to map of json node, the root fields will be map keys
135  */
136 fun JsonNode.rootFieldsToMap(): MutableMap<String, JsonNode> {
137     if (this is ObjectNode) {
138         val propertyMap: MutableMap<String, JsonNode> = hashMapOf()
139         this.fields().forEach {
140             propertyMap[it.key] = it.value
141         }
142         return propertyMap
143     } else {
144         throw BluePrintException("json node should be Object Node Type")
145     }
146 }
147
148 fun JsonNode.removeNullNode() {
149     val it = this.iterator()
150     while (it.hasNext()) {
151         val child = it.next()
152         if (child.isNull) {
153             it.remove()
154         } else {
155             child.removeNullNode()
156         }
157     }
158 }
159
160
161 fun MutableMap<String, JsonNode>.putJsonElement(key: String, value: Any) {
162     val convertedValue = value.asJsonType()
163     this[key] = convertedValue
164 }
165
166 fun Map<String, JsonNode>.getAsString(key: String): String {
167     return this[key]?.asText() ?: throw BluePrintException("couldn't find value for key($key)")
168 }
169
170 fun Map<String, JsonNode>.getAsBoolean(key: String): Boolean {
171     return this[key]?.asBoolean() ?: throw BluePrintException("couldn't find value for key($key)")
172 }
173
174 fun Map<String, JsonNode>.getAsInt(key: String): Int {
175     return this[key]?.asInt() ?: throw BluePrintException("couldn't find value for key($key)")
176 }
177
178 fun Map<String, JsonNode>.getAsDouble(key: String): Double {
179     return this[key]?.asDouble() ?: throw BluePrintException("couldn't find value for key($key)")
180 }
181
182 // Checks
183
184 inline fun checkEquals(value1: String?, value2: String?, lazyMessage: () -> Any): Boolean {
185     if (value1.equals(value2, ignoreCase = true)) {
186         return true
187     } else {
188         throw BluePrintException(lazyMessage().toString())
189     }
190 }
191
192 inline fun checkNotEmpty(value: String?, lazyMessage: () -> Any): String {
193     if (value == null || value.isEmpty()) {
194         val message = lazyMessage()
195         throw IllegalStateException(message.toString())
196     } else {
197         return value
198     }
199 }
200
201 inline fun checkNotBlank(value: String?, lazyMessage: () -> Any): String {
202     if (value == null || value.isBlank()) {
203         val message = lazyMessage()
204         throw IllegalStateException(message.toString())
205     } else {
206         return value
207     }
208 }
209
210 fun isNotEmpty(value: String?): Boolean {
211     return value != null && value.isNotEmpty()
212 }
213
214 fun isNotBlank(value: String?): Boolean {
215     return value != null && value.isNotBlank()
216 }
217
218
219 fun nullToEmpty(value: String?): String {
220     return if (isNotEmpty(value)) value!! else ""
221 }
222
223