2 * Copyright © 2017-2018 AT&T Intellectual Property.
3 * Modifications Copyright © 2019 IBM.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package org.onap.ccsdk.cds.controllerblueprints.core
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
28 import kotlin.reflect.KClass
33 * @author Brinda Santh
36 fun <T : Any> logger(clazz: T) = LoggerFactory.getLogger(clazz.javaClass)!!
38 fun <T : KClass<*>> logger(clazz: T) = LoggerFactory.getLogger(clazz.java)!!
40 fun <T : Any> T?.defaultToEmpty(): String {
41 return this?.toString() ?: ""
44 fun <T : Any> T?.defaultToUUID(): String {
45 return this?.toString() ?: UUID.randomUUID().toString()
48 fun <T : Any> T.bpClone(): T {
49 return ObjectUtils.clone(this)
52 fun String.isJson(): Boolean {
53 return ((this.trim().startsWith("{") && this.trim().endsWith("}"))
54 || (this.trim().startsWith("[") && this.trim().endsWith("]")))
57 fun Any.asJsonString(intend: Boolean? = false): String {
58 return JacksonUtils.getJson(this, intend!!)
61 fun String.asJsonPrimitive(): TextNode {
65 inline fun <reified T : Any> String.jsonAsType(): T {
66 return JacksonUtils.readValue<T>(this.trim())
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())
74 fun Boolean.asJsonPrimitive(): BooleanNode {
75 return BooleanNode.valueOf(this)
78 fun Int.asJsonPrimitive(): IntNode {
79 return IntNode.valueOf(this)
82 fun Double.asJsonPrimitive(): DoubleNode {
83 return DoubleNode.valueOf(this)
87 * Utility to convert Primitive object to Json Type Primitive.
89 fun <T : Any?> T.asJsonPrimitive(): JsonNode {
90 return if (this == null || this is MissingNode || this is NullNode) {
95 this.asJsonPrimitive()
97 this.asJsonPrimitive()
99 this.asJsonPrimitive()
101 this.asJsonPrimitive()
103 throw BluePrintException("$this type is not supported")
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()
122 * Utility to convert Complex or Primitive object to Json Type.
124 fun <T : Any?> T.asJsonType(): JsonNode {
125 return if (this == null || this is MissingNode || this is NullNode) {
133 this.jsonAsJsonType()
138 BooleanNode.valueOf(this)
140 IntNode.valueOf(this.toInt())
142 DoubleNode.valueOf(this.toDouble())
144 JacksonUtils.jsonNodeFromObject(this)
149 fun Map<String, *>.asJsonNode(): JsonNode {
150 return JacksonUtils.jsonNodeFromObject(this)
153 fun Map<String, *>.asObjectNode(): ObjectNode {
154 return JacksonUtils.objectNodeFromObject(this)
157 fun format(message: String, vararg args: Any?): String {
158 if (args != null && args.isNotEmpty()) {
159 return MessageFormatter.arrayFormat(message, args).message
164 fun <T : Any> Map<String, *>.castOptionalValue(key: String, valueType: KClass<T>): T? {
165 return if (containsKey(key)) {
172 fun <T : Any> Map<String, *>.castValue(key: String, valueType: KClass<T>): T {
173 if (containsKey(key)) {
176 throw BluePrintException("couldn't find the key $key")
180 fun ArrayNode.asListOfString(): List<String> {
181 return JacksonUtils.getListFromJsonNode(this, String::class.java)
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")
189 fun JsonNode.asListOfString(): List<String> {
190 check(this is ArrayNode) { "JsonNode is not of type ArrayNode" }
191 return this.asListOfString()
194 fun <T : JsonNode> T?.returnNullIfMissing(): JsonNode? {
195 return if (this == null || this is NullNode || this is MissingNode) {
200 fun <T : JsonNode> T?.isNullOrMissing(): Boolean {
201 return this == null || this is NullNode || this is MissingNode
205 * Convert Json to map of json node, the root fields will be map keys
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
215 throw BluePrintException("json node should be Object Node Type")
219 fun JsonNode.removeNullNode() {
220 val it = this.iterator()
221 while (it.hasNext()) {
222 val child = it.next()
226 child.removeNullNode()
232 fun MutableMap<String, JsonNode>.putJsonElement(key: String, value: Any) {
233 val convertedValue = value.asJsonType()
234 this[key] = convertedValue
237 fun Map<String, JsonNode>.getAsString(key: String): String {
238 return this[key]?.asText() ?: throw BluePrintException("couldn't find value for key($key)")
241 fun Map<String, JsonNode>.getAsBoolean(key: String): Boolean {
242 return this[key]?.asBoolean() ?: throw BluePrintException("couldn't find value for key($key)")
245 fun Map<String, JsonNode>.getAsInt(key: String): Int {
246 return this[key]?.asInt() ?: throw BluePrintException("couldn't find value for key($key)")
249 fun Map<String, JsonNode>.getAsDouble(key: String): Double {
250 return this[key]?.asDouble() ?: throw BluePrintException("couldn't find value for key($key)")
253 fun Map<String, JsonNode>.getOptionalAsString(key: String): String? {
254 return if (this.containsKey(key)) this[key]!!.asText() else null
257 fun Map<String, JsonNode>.getOptionalAsBoolean(key: String): Boolean? {
258 return if (this.containsKey(key)) this[key]!!.asBoolean() else null
261 fun Map<String, JsonNode>.getOptionalAsInt(key: String): Int? {
262 return if (this.containsKey(key)) this[key]!!.asInt() else null
265 fun Map<String, JsonNode>.getOptionalAsDouble(key: String): Double? {
266 return if (this.containsKey(key)) this[key]!!.asDouble() else null
271 inline fun checkEquals(value1: String?, value2: String?, lazyMessage: () -> Any): Boolean {
272 if (value1.equals(value2, ignoreCase = true)) {
275 throw BluePrintException(lazyMessage().toString())
279 inline fun checkNotEmpty(value: String?, lazyMessage: () -> Any): String {
280 if (value == null || value.isEmpty()) {
281 val message = lazyMessage()
282 throw IllegalStateException(message.toString())
288 inline fun checkNotBlank(value: String?, lazyMessage: () -> Any): String {
289 if (value == null || value.isBlank()) {
290 val message = lazyMessage()
291 throw IllegalStateException(message.toString())
297 fun isNotEmpty(value: String?): Boolean {
298 return value != null && value.isNotEmpty()
301 fun isNotBlank(value: String?): Boolean {
302 return value != null && value.isNotBlank()
305 fun <T : String> T?.emptyTONull(): String? {
306 return if (this == null || this.isEmpty()) null else this
309 fun nullToEmpty(value: String?): String {
310 return if (isNotEmpty(value)) value!! else ""
313 inline fun <reified T : JsonNode> T.isComplexType(): Boolean {
314 return this is ObjectNode || this is ArrayNode
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)
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)