import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.*
+import org.apache.commons.lang3.ObjectUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+import org.slf4j.LoggerFactory
import org.slf4j.helpers.MessageFormatter
import kotlin.reflect.KClass
* @author Brinda Santh
*/
+fun <T : Any> logger(clazz: T) = LoggerFactory.getLogger(clazz.javaClass)!!
+
+fun <T : KClass<*>> logger(clazz: T) = LoggerFactory.getLogger(clazz.java)!!
+
+
+fun <T : Any> T.bpClone(): T {
+ return ObjectUtils.clone(this)
+}
+
+fun String.isJson(): Boolean {
+ return ((this.startsWith("{") && this.endsWith("}"))
+ || (this.startsWith("[") && this.endsWith("]")))
+}
+
+fun Any.asJsonString(intend: Boolean? = false): String {
+ return JacksonUtils.getJson(this, intend!!)
+}
+
fun String.asJsonPrimitive(): TextNode {
return TextNode(this)
}
+// If you know the string is json content, then use the function directly
+fun String.jsonAsJsonType(): JsonNode {
+ return JacksonUtils.jsonNode(this.trim())
+}
+
fun Boolean.asJsonPrimitive(): BooleanNode {
return BooleanNode.valueOf(this)
}
return DoubleNode.valueOf(this)
}
+/**
+ * Utility to convert Primitive object to Json Type Primitive.
+ */
+fun <T : Any?> T.asJsonPrimitive(): JsonNode {
+ return if (this == null || this is MissingNode || this is NullNode) {
+ NullNode.instance
+ } else {
+ when (this) {
+ is String ->
+ this.asJsonPrimitive()
+ is Boolean ->
+ this.asJsonPrimitive()
+ is Int ->
+ this.asJsonPrimitive()
+ is Double ->
+ this.asJsonPrimitive()
+ else ->
+ throw BluePrintException("$this type is not supported")
+ }
+ }
+}
+
+/**
+ * Utility to convert Complex or Primitive object to Json Type.
+ */
fun <T : Any?> T.asJsonType(): JsonNode {
- return if (this == null) {
+ return if (this == null || this is MissingNode || this is NullNode) {
NullNode.instance
} else {
when (this) {
is JsonNode ->
this
- is String ->
- TextNode(this)
+ is String -> {
+ if (this.isJson())
+ this.jsonAsJsonType()
+ else
+ TextNode(this)
+ }
is Boolean ->
BooleanNode.valueOf(this)
is Int ->
}
fun <T : Any> Map<String, *>.castOptionalValue(key: String, valueType: KClass<T>): T? {
- if (containsKey(key)) {
- return get(key) as? T
+ return if (containsKey(key)) {
+ get(key) as? T
} else {
- return null
+ null
}
}
} else this
}
+fun <T : JsonNode> T?.isNull(): Boolean {
+ return this == null || this is NullNode || this is MissingNode
+}
+
+fun <T : JsonNode> T?.isNotNull(): Boolean {
+ return !(this == null || this is NullNode || this is MissingNode)
+}
+
/**
* Convert Json to map of json node, the root fields will be map keys
*/
fun JsonNode.rootFieldsToMap(): MutableMap<String, JsonNode> {
if (this is ObjectNode) {
- val propertyMap: MutableMap<String, JsonNode> = hashMapOf()
+ val propertyMap: MutableMap<String, JsonNode> = linkedMapOf()
this.fields().forEach {
propertyMap[it.key] = it.value
}