gsonpath.adapter.standard.model.GsonObjectTreeFactory.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of gsonpath-compiler Show documentation
Show all versions of gsonpath-compiler Show documentation
An annotation processor which generates Type Adapters for the Google Gson library
package gsonpath.adapter.standard.model
import gsonpath.ProcessingException
import gsonpath.model.FieldInfo
import java.util.regex.Pattern
data class GsonTreeResult(
val rootObject: GsonObject,
val flattenedFields: List
)
class GsonObjectTreeFactory(private val gsonObjectFactory: GsonObjectFactory) {
@Throws(ProcessingException::class)
fun createGsonObject(
fieldInfoList: List,
rootField: String,
metadata: GsonObjectMetadata): GsonTreeResult {
// Obtain the correct mapping structure beforehand.
val absoluteRootObject = MutableGsonObject()
val gsonPathObject =
if (rootField.isNotEmpty()) {
createGsonObjectFromRootField(absoluteRootObject, rootField, metadata.flattenDelimiter)
} else {
absoluteRootObject
}
for (fieldInfoIndex in fieldInfoList.indices) {
gsonObjectFactory.addGsonType(gsonPathObject, fieldInfoList[fieldInfoIndex], fieldInfoIndex, metadata)
}
val immutableAbsoluteGsonObject = absoluteRootObject.toImmutable()
val flattenedFields = getFlattenedFields(immutableAbsoluteGsonObject).sortedBy { it.fieldIndex }
return GsonTreeResult(immutableAbsoluteGsonObject, flattenedFields)
}
private fun createGsonObjectFromRootField(
rootObject: MutableGsonObject,
rootField: String,
flattenDelimiter: Char): MutableGsonObject {
if (rootField.isEmpty()) {
return rootObject
}
val regexSafeDelimiter = Pattern.quote(flattenDelimiter.toString())
val split = rootField.split(regexSafeDelimiter.toRegex()).dropLastWhile(String::isEmpty)
if (split.isNotEmpty()) {
// Keep adding branches to the tree and switching our root to the new branch.
return split.fold(rootObject) { currentRoot, field ->
val currentObject = MutableGsonObject()
currentRoot.addObject(field, currentObject)
return@fold currentObject
}
} else {
// Add a single branch to the tree and return the new branch.
val mapWithRoot = MutableGsonObject()
rootObject.addObject(rootField, mapWithRoot)
return mapWithRoot
}
}
private fun getFlattenedFields(currentGsonObject: GsonObject): List {
return currentGsonObject.entries()
.flatMap { (_, gsonType) ->
when (gsonType) {
is GsonField -> listOf(gsonType)
is GsonObject -> getFlattenedFields(gsonType)
is GsonArray -> {
gsonType.entries()
.flatMap { (_, arrayGsonType) ->
when (arrayGsonType) {
is GsonField -> listOf(arrayGsonType)
is GsonObject -> getFlattenedFields(arrayGsonType)
}
}
}
}
}
}
}