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

de.bild.codec.EnumCodec Maven / Gradle / Ivy

Go to download

A very fast POJO codec for MongoDB (used in conjunction with the Mongo Java Driver) that handles generic types as well as polymorphic class hierarchies

There is a newer version: 2.8.2
Show newest version
package de.bild.codec;

import org.bson.BsonReader;
import org.bson.BsonType;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Codec for enum.
 * encode: value.name()
 * decode: Enum.valueOf(clazz, name)
 */
public class EnumCodec> implements Codec {
    private static final Logger LOGGER = LoggerFactory.getLogger(EnumCodec.class);

    final Class clazz;

    public EnumCodec(Class clazz) {
        this.clazz = clazz;

    }

    @Override
    public T decode(BsonReader reader, DecoderContext decoderContext) {
        if (BsonType.STRING.equals(reader.getCurrentBsonType())) {
            String name = reader.readString();
            if (name != null) {
                try {
                    return Enum.valueOf(clazz, name);
                } catch (IllegalArgumentException e) {
                    LOGGER.warn("Enum value {} could not be determined for enum type {}", name, clazz, e);
                }
            }
        } else {
            LOGGER.warn("Expected {} from reader but got {}. Skipping value.", BsonType.STRING, reader.getCurrentBsonType());
            reader.skipValue();
        }
        return null;
    }

    @Override
    public void encode(BsonWriter writer, T value, EncoderContext encoderContext) {
        writer.writeString(value.name());
    }

    @Override
    public Class getEncoderClass() {
        return clazz;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy