All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.apache.tinkerpop.gremlin.ogm.mappers.PropertySerializer.kt Maven / Gradle / Ivy

There is a newer version: 0.21.0
Show newest version
package org.apache.tinkerpop.gremlin.ogm.mappers

import org.apache.tinkerpop.gremlin.ogm.exceptions.IncompatibleIterable
import org.apache.tinkerpop.gremlin.ogm.exceptions.IncompatibleMap
import org.apache.tinkerpop.gremlin.ogm.reflection.GraphDescription
import org.apache.tinkerpop.gremlin.ogm.reflection.PropertyDescription
import kotlin.reflect.KClass

internal class PropertySerializer(
        private val graphDescription: GraphDescription,
        private val propertyDescription: PropertyDescription<*, T>
) : Mapper {

    override fun invoke(from: Any?): SerializedProperty? {
        if (propertyDescription.mapper != null && from != null) {
            return propertyDescription.mapper.forwardMap(from)
        }
        return when (from) {
            null -> null
            is Iterable<*> -> {
                val fromClass by lazy {
                    propertyDescription.property.returnType.arguments.single().type?.classifier as? KClass
                            ?: throw IncompatibleIterable(propertyDescription)
                }
                from.map {
                    serializeProperty(it, fromClass)
                }
            }
            is Map<*, *> -> {
                val mapTypeParameters by lazy { propertyDescription.property.returnType.arguments }
                val keyClass by lazy {
                    mapTypeParameters.first().type?.classifier as? KClass
                            ?: throw IncompatibleMap(propertyDescription)
                }
                val valueClass by lazy {
                    mapTypeParameters.last().type?.classifier as? KClass
                            ?: throw IncompatibleMap(propertyDescription)
                }
                from.entries.associate {
                    serializeProperty(it.key, keyClass) to serializeProperty(it.value, valueClass)
                }
            }
            else -> serializeProperty(from, propertyDescription.kClass)
        }
    }

    private fun serializeProperty(property: Any?, deserializedClass: KClass): SerializedProperty? {
        if (property == null) {
            return null
        }
        if (graphDescription.scalarPropertyClasses.contains(deserializedClass)) {
            return graphDescription.getScalarPropertyMapper(deserializedClass).forwardMap(property)
        }
        val description = graphDescription.getObjectPropertyDescription(deserializedClass)
        val serializer = ObjectSerializer(graphDescription, description)
        return serializer(property)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy