ProtoTypeRegistryOption.java

package net.morimekta.proto.jackson;

import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import net.morimekta.proto.utils.ProtoTypeRegistry;

/**
 * Providence specific features or attributes used to configure
 * serialization further. These are technically 'attributes' on
 * the serialization config, but is used are simple feature
 * flags.
 */
public final class ProtoTypeRegistryOption {
    /**
     * @param mapper The mapper to set value on.
     * @param value  The value to be set for this feature.
     * @return The mapper.
     */
    public static ObjectMapper setRegistry(ObjectMapper mapper, ProtoTypeRegistry value) {
        mapper.setConfig(mapper.getSerializationConfig().withAttribute(ProtoTypeRegistry.class, value));
        mapper.setConfig(mapper.getDeserializationConfig().withAttribute(ProtoTypeRegistry.class, value));
        return mapper;
    }

    /**
     * @param sp The serializer provider.
     * @return The feature value, or default if not set.
     */
    public static ProtoTypeRegistry getRegistry(SerializerProvider sp) {
        Object o = sp.getAttribute(ProtoTypeRegistry.class);
        return (ProtoTypeRegistry) o;
    }

    /**
     * @param config The deserialization config.
     * @return The feature value, or default if not set.
     */
    public static ProtoTypeRegistry getRegistry(DeserializationConfig config) {
        Object o = config.getAttributes().getAttribute(ProtoTypeRegistry.class);
        return (ProtoTypeRegistry) o;
    }
}