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

dev.morphia.mapping.codec.ReadWritePropertyCodecProvider.kt Maven / Gradle / Ivy

There is a newer version: 2.4.14
Show newest version
package dev.morphia.mapping.codec

import com.mongodb.lang.Nullable
import dev.morphia.annotations.internal.MorphiaInternal
import dev.morphia.mapping.codec.pojo.TypeData
import kotlin.properties.ReadWriteProperty
import org.bson.codecs.Codec
import org.bson.codecs.configuration.CodecConfigurationException
import org.bson.codecs.pojo.PropertyCodecRegistry
import org.bson.codecs.pojo.TypeWithTypeParameters

/**
 * @since 2.2
 * @hidden
 */
@MorphiaInternal
@Suppress("UNCHECKED_CAST")
class ReadWritePropertyCodecProvider : MorphiaPropertyCodecProvider() {
    @Nullable
    override fun  get(
        type: TypeWithTypeParameters,
        registry: PropertyCodecRegistry
    ): Codec? {
        if (ReadWriteProperty::class.java.isAssignableFrom(type.type)) {
            val typeParameters = type.typeParameters
            val valueType = getType(typeParameters, 0)
            return try {
                val codec: Codec = registry[valueType] as Codec
                ReadWritePropertyCodec(codec) as Codec
            } catch (e: CodecConfigurationException) {
                if (valueType.type == Any::class.java) {
                    try {
                        return registry.get(TypeData.builder(Collection::class.java).build())
                            as Codec
                    } catch (_: CodecConfigurationException) {
                        // Ignore and return original exception
                    }
                }
                throw e
            }
        }
        return null
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy