Class TypeCodec<T>

  • Type Parameters:
    T - The codec's Java type
    Direct Known Subclasses:
    TypeCodec.AbstractCollectionCodec, TypeCodec.AbstractMapCodec, TypeCodec.AbstractTupleCodec, TypeCodec.AbstractUDTCodec, TypeCodec.PrimitiveBooleanCodec, TypeCodec.PrimitiveByteCodec, TypeCodec.PrimitiveDoubleCodec, TypeCodec.PrimitiveFloatCodec, TypeCodec.PrimitiveIntCodec, TypeCodec.PrimitiveLongCodec, TypeCodec.PrimitiveShortCodec

    public abstract class TypeCodec<T>
    extends java.lang.Object
    A Codec that can serialize and deserialize to and from a given CQL type and a given Java Type.

    Serializing and deserializing

    Two methods handle the serialization and deserialization of Java types into CQL types according to the native protocol specifications:

    1. serialize(Object, ProtocolVersion): used to serialize from the codec's Java type to a ByteBuffer instance corresponding to the codec's CQL type;
    2. deserialize(ByteBuffer, ProtocolVersion): used to deserialize a ByteBuffer instance corresponding to the codec's CQL type to the codec's Java type.

    Formatting and parsing

    Two methods handle the formatting and parsing of Java types into CQL strings:

    1. format(Object): formats the Java type handled by the codec as a CQL string;
    2. parse(String); parses a CQL string into the Java type handled by the codec.

    Inspection

    Codecs also have the following inspection methods:

    1. accepts(DataType): returns true if the codec can deserialize the given CQL type;
    2. accepts(TypeToken): returns true if the codec can serialize the given Java type;
    3. accepts(Object); returns true if the codec can serialize the given object.

    Implementation notes

    1. TypeCodec implementations must be thread-safe.
    2. TypeCodec implementations must perform fast and never block.
    3. TypeCodec implementations must support all native protocol versions; it is not possible to use different codecs for the same types but under different protocol versions.
    4. TypeCodec implementations must comply with the native protocol specifications; failing to do so will result in unexpected results and could cause the driver to crash.
    5. TypeCodec implementations should be stateless and immutable.
    6. TypeCodec implementations should interpret null values and empty ByteBuffers (i.e. Buffer.remaining() == 0) in a reasonable way; usually, NULL CQL values should map to null references, but exceptions exist; e.g. for varchar types, a NULL CQL value maps to a null reference, whereas an empty buffer maps to an empty String. For collection types, it is also admitted that NULL CQL values map to empty Java collections instead of null references. In any case, the codec's behavior in respect to null values and empty ByteBuffers should be clearly documented.
    7. TypeCodec implementations that wish to handle Java primitive types must be instantiated with the wrapper Java class instead, and implement the appropriate interface (e.g. TypeCodec.PrimitiveBooleanCodec for primitive boolean types; there is one such interface for each Java primitive type).
    8. When deserializing, TypeCodec implementations should not consume ByteBuffer instances by performing relative read operations that modify their current position; codecs should instead prefer absolute read methods, or, if necessary, they should duplicate their byte buffers prior to reading them.
    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      protected TypeCodec​(DataType cqlType, com.google.common.reflect.TypeToken<T> javaType)  
      protected TypeCodec​(DataType cqlType, java.lang.Class<T> javaClass)
      This constructor can only be used for non parameterized types.
    • Method Summary

      All Methods Static Methods Instance Methods Abstract Methods Concrete Methods 
      Modifier and Type Method Description
      boolean accepts​(com.google.common.reflect.TypeToken<?> javaType)
      Return true if this codec is capable of serializing the given javaType.
      boolean accepts​(java.lang.Class<?> javaType)
      Return true if this codec is capable of serializing the given javaType.
      boolean accepts​(java.lang.Object value)
      Return true if this codec is capable of serializing the given object.
      boolean accepts​(DataType cqlType)
      Return true if this codec is capable of deserializing the given cqlType.
      static TypeCodec<java.lang.String> ascii()
      Return the default codec for the CQL type ascii.
      static TypeCodec.PrimitiveLongCodec bigint()
      Return the default codec for the CQL type bigint.
      static TypeCodec<java.nio.ByteBuffer> blob()
      Return the default codec for the CQL type blob.
      static TypeCodec.PrimitiveBooleanCodec cboolean()
      Return the default codec for the CQL type boolean.
      static TypeCodec.PrimitiveDoubleCodec cdouble()
      Return the default codec for the CQL type double.
      static TypeCodec.PrimitiveFloatCodec cfloat()
      Return the default codec for the CQL type float.
      static TypeCodec.PrimitiveIntCodec cint()
      Return the default codec for the CQL type int.
      static TypeCodec.PrimitiveLongCodec counter()
      Return the default codec for the CQL type counter.
      static TypeCodec<java.nio.ByteBuffer> custom​(DataType.CustomType type)
      Return a newly-created codec for the given CQL custom type.
      static TypeCodec<LocalDate> date()
      Return the default codec for the CQL type date.
      static TypeCodec<java.math.BigDecimal> decimal()
      Return the default codec for the CQL type decimal.
      abstract T deserialize​(java.nio.ByteBuffer bytes, ProtocolVersion protocolVersion)
      Deserialize the given ByteBuffer instance according to the CQL type handled by this codec.
      static TypeCodec<Duration> duration()
      Returns the default codec for the Duration type.
      abstract java.lang.String format​(T value)
      Format the given value as a valid CQL literal according to the CQL type handled by this codec.
      DataType getCqlType()
      Return the CQL type that this codec deserializes from and serializes to.
      com.google.common.reflect.TypeToken<T> getJavaType()
      Return the Java type that this codec deserializes to and serializes from.
      static TypeCodec<java.net.InetAddress> inet()
      Return the default codec for the CQL type inet.
      static <T> TypeCodec<java.util.List<T>> list​(TypeCodec<T> elementCodec)
      Return a newly-created codec for the CQL type list whose element type is determined by the given element codec.
      static <K,​V>
      TypeCodec<java.util.Map<K,​V>>
      map​(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec)
      Return a newly-created codec for the CQL type map whose key type and value type are determined by the given codecs.
      abstract T parse​(java.lang.String value)
      Parse the given CQL literal into an instance of the Java type handled by this codec.
      abstract java.nio.ByteBuffer serialize​(T value, ProtocolVersion protocolVersion)
      Serialize the given value according to the CQL type handled by this codec.
      static <T> TypeCodec<java.util.Set<T>> set​(TypeCodec<T> elementCodec)
      Return a newly-created codec for the CQL type set whose element type is determined by the given element codec.
      static TypeCodec.PrimitiveShortCodec smallInt()
      Return the default codec for the CQL type smallint.
      static TypeCodec.PrimitiveLongCodec time()
      Return the default codec for the CQL type time.
      static TypeCodec<java.util.Date> timestamp()
      Return the default codec for the CQL type timestamp.
      static TypeCodec<java.util.UUID> timeUUID()
      Return the default codec for the CQL type timeuuid.
      static TypeCodec.PrimitiveByteCodec tinyInt()
      Return the default codec for the CQL type tinyint.
      java.lang.String toString()  
      static TypeCodec<TupleValue> tuple​(TupleType type)
      Return a newly-created codec for the given CQL tuple type.
      static TypeCodec<UDTValue> userType​(UserType type)
      Return a newly-created codec for the given user-defined CQL type.
      static TypeCodec<java.util.UUID> uuid()
      Return the default codec for the CQL type uuid.
      static TypeCodec<java.lang.String> varchar()
      Return the default codec for the CQL type varchar.
      static TypeCodec<java.math.BigInteger> varint()
      Return the default codec for the CQL type varint.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Constructor Detail

      • TypeCodec

        protected TypeCodec​(DataType cqlType,
                            java.lang.Class<T> javaClass)
        This constructor can only be used for non parameterized types. For parameterized ones, please use TypeCodec(DataType, TypeToken) instead.
        Parameters:
        javaClass - The Java class this codec serializes from and deserializes to.
      • TypeCodec

        protected TypeCodec​(DataType cqlType,
                            com.google.common.reflect.TypeToken<T> javaType)
    • Method Detail

      • cboolean

        public static TypeCodec.PrimitiveBooleanCodec cboolean()
        Return the default codec for the CQL type boolean. The returned codec maps the CQL type boolean into the Java type Boolean. The returned instance is a singleton.
        Returns:
        the default codec for CQL type boolean.
      • tinyInt

        public static TypeCodec.PrimitiveByteCodec tinyInt()
        Return the default codec for the CQL type tinyint. The returned codec maps the CQL type tinyint into the Java type Byte. The returned instance is a singleton.
        Returns:
        the default codec for CQL type tinyint.
      • smallInt

        public static TypeCodec.PrimitiveShortCodec smallInt()
        Return the default codec for the CQL type smallint. The returned codec maps the CQL type smallint into the Java type Short. The returned instance is a singleton.
        Returns:
        the default codec for CQL type smallint.
      • cint

        public static TypeCodec.PrimitiveIntCodec cint()
        Return the default codec for the CQL type int. The returned codec maps the CQL type int into the Java type Integer. The returned instance is a singleton.
        Returns:
        the default codec for CQL type int.
      • bigint

        public static TypeCodec.PrimitiveLongCodec bigint()
        Return the default codec for the CQL type bigint. The returned codec maps the CQL type bigint into the Java type Long. The returned instance is a singleton.
        Returns:
        the default codec for CQL type bigint.
      • counter

        public static TypeCodec.PrimitiveLongCodec counter()
        Return the default codec for the CQL type counter. The returned codec maps the CQL type counter into the Java type Long. The returned instance is a singleton.
        Returns:
        the default codec for CQL type counter.
      • cfloat

        public static TypeCodec.PrimitiveFloatCodec cfloat()
        Return the default codec for the CQL type float. The returned codec maps the CQL type float into the Java type Float. The returned instance is a singleton.
        Returns:
        the default codec for CQL type float.
      • cdouble

        public static TypeCodec.PrimitiveDoubleCodec cdouble()
        Return the default codec for the CQL type double. The returned codec maps the CQL type double into the Java type Double. The returned instance is a singleton.
        Returns:
        the default codec for CQL type double.
      • varint

        public static TypeCodec<java.math.BigInteger> varint()
        Return the default codec for the CQL type varint. The returned codec maps the CQL type varint into the Java type BigInteger. The returned instance is a singleton.
        Returns:
        the default codec for CQL type varint.
      • decimal

        public static TypeCodec<java.math.BigDecimal> decimal()
        Return the default codec for the CQL type decimal. The returned codec maps the CQL type decimal into the Java type BigDecimal. The returned instance is a singleton.
        Returns:
        the default codec for CQL type decimal.
      • ascii

        public static TypeCodec<java.lang.String> ascii()
        Return the default codec for the CQL type ascii. The returned codec maps the CQL type ascii into the Java type String. The returned instance is a singleton.
        Returns:
        the default codec for CQL type ascii.
      • varchar

        public static TypeCodec<java.lang.String> varchar()
        Return the default codec for the CQL type varchar. The returned codec maps the CQL type varchar into the Java type String. The returned instance is a singleton.
        Returns:
        the default codec for CQL type varchar.
      • blob

        public static TypeCodec<java.nio.ByteBuffer> blob()
        Return the default codec for the CQL type blob. The returned codec maps the CQL type blob into the Java type ByteBuffer. The returned instance is a singleton.
        Returns:
        the default codec for CQL type blob.
      • date

        public static TypeCodec<LocalDate> date()
        Return the default codec for the CQL type date. The returned codec maps the CQL type date into the Java type LocalDate. The returned instance is a singleton.
        Returns:
        the default codec for CQL type date.
      • time

        public static TypeCodec.PrimitiveLongCodec time()
        Return the default codec for the CQL type time. The returned codec maps the CQL type time into the Java type Long. The returned instance is a singleton.
        Returns:
        the default codec for CQL type time.
      • timestamp

        public static TypeCodec<java.util.Date> timestamp()
        Return the default codec for the CQL type timestamp. The returned codec maps the CQL type timestamp into the Java type Date. The returned instance is a singleton.
        Returns:
        the default codec for CQL type timestamp.
      • uuid

        public static TypeCodec<java.util.UUID> uuid()
        Return the default codec for the CQL type uuid. The returned codec maps the CQL type uuid into the Java type UUID. The returned instance is a singleton.
        Returns:
        the default codec for CQL type uuid.
      • timeUUID

        public static TypeCodec<java.util.UUID> timeUUID()
        Return the default codec for the CQL type timeuuid. The returned codec maps the CQL type timeuuid into the Java type UUID. The returned instance is a singleton.
        Returns:
        the default codec for CQL type timeuuid.
      • inet

        public static TypeCodec<java.net.InetAddress> inet()
        Return the default codec for the CQL type inet. The returned codec maps the CQL type inet into the Java type InetAddress. The returned instance is a singleton.
        Returns:
        the default codec for CQL type inet.
      • list

        public static <T> TypeCodec<java.util.List<T>> list​(TypeCodec<T> elementCodec)
        Return a newly-created codec for the CQL type list whose element type is determined by the given element codec. The returned codec maps the CQL type list into the Java type List. This method does not cache returned instances and returns a newly-allocated object at each invocation.
        Parameters:
        elementCodec - the codec that will handle elements of this list.
        Returns:
        A newly-created codec for CQL type list.
      • set

        public static <T> TypeCodec<java.util.Set<T>> set​(TypeCodec<T> elementCodec)
        Return a newly-created codec for the CQL type set whose element type is determined by the given element codec. The returned codec maps the CQL type set into the Java type Set. This method does not cache returned instances and returns a newly-allocated object at each invocation.
        Parameters:
        elementCodec - the codec that will handle elements of this set.
        Returns:
        A newly-created codec for CQL type set.
      • map

        public static <K,​V> TypeCodec<java.util.Map<K,​V>> map​(TypeCodec<K> keyCodec,
                                                                          TypeCodec<V> valueCodec)
        Return a newly-created codec for the CQL type map whose key type and value type are determined by the given codecs. The returned codec maps the CQL type map into the Java type Map. This method does not cache returned instances and returns a newly-allocated object at each invocation.
        Parameters:
        keyCodec - the codec that will handle keys of this map.
        valueCodec - the codec that will handle values of this map.
        Returns:
        A newly-created codec for CQL type map.
      • userType

        public static TypeCodec<UDTValue> userType​(UserType type)
        Return a newly-created codec for the given user-defined CQL type. The returned codec maps the user-defined type into the Java type UDTValue. This method does not cache returned instances and returns a newly-allocated object at each invocation.
        Parameters:
        type - the user-defined type this codec should handle.
        Returns:
        A newly-created codec for the given user-defined CQL type.
      • tuple

        public static TypeCodec<TupleValue> tuple​(TupleType type)
        Return a newly-created codec for the given CQL tuple type. The returned codec maps the tuple type into the Java type TupleValue. This method does not cache returned instances and returns a newly-allocated object at each invocation.
        Parameters:
        type - the tuple type this codec should handle.
        Returns:
        A newly-created codec for the given CQL tuple type.
      • custom

        public static TypeCodec<java.nio.ByteBuffer> custom​(DataType.CustomType type)
        Return a newly-created codec for the given CQL custom type.

        The returned codec maps the custom type into the Java type ByteBuffer, thus providing a (very lightweight) support for Cassandra types that do not have a CQL equivalent.

        Note that the returned codec assumes that CQL literals for the given custom type are expressed in binary form as well, e.g. 0xcafebabe. If this is not the case, the returned codec might be unable to parse and format literals for this type. This is notoriously true for types inheriting from org.apache.cassandra.db.marshal.AbstractCompositeType, whose CQL literals are actually expressed as quoted strings.

        This method does not cache returned instances and returns a newly-allocated object at each invocation.

        Parameters:
        type - the custom type this codec should handle.
        Returns:
        A newly-created codec for the given CQL custom type.
      • duration

        public static TypeCodec<Duration> duration()
        Returns the default codec for the Duration type.

        This codec maps duration types to the driver's built-in Duration class, thus providing a more user-friendly mapping than the low-level mapping provided by regular custom type codecs.

        The returned instance is a singleton.

        Returns:
        the default codec for the Duration type.
      • getJavaType

        public com.google.common.reflect.TypeToken<T> getJavaType()
        Return the Java type that this codec deserializes to and serializes from.
        Returns:
        The Java type this codec deserializes to and serializes from.
      • getCqlType

        public DataType getCqlType()
        Return the CQL type that this codec deserializes from and serializes to.
        Returns:
        The Java type this codec deserializes from and serializes to.
      • serialize

        public abstract java.nio.ByteBuffer serialize​(T value,
                                                      ProtocolVersion protocolVersion)
                                               throws InvalidTypeException
        Serialize the given value according to the CQL type handled by this codec.

        Implementation notes:

        1. Null values should be gracefully handled and no exception should be raised; these should be considered as the equivalent of a NULL CQL value;
        2. Codecs for CQL collection types should not permit null elements;
        3. Codecs for CQL collection types should treat a null input as the equivalent of an empty collection.
        Parameters:
        value - An instance of T; may be null.
        protocolVersion - the protocol version to use when serializing bytes. In most cases, the proper value to provide for this argument is the value returned by ProtocolOptions#getProtocolVersion (which is the protocol version in use by the driver).
        Returns:
        A ByteBuffer instance containing the serialized form of T
        Throws:
        InvalidTypeException - if the given value does not have the expected type
      • deserialize

        public abstract T deserialize​(java.nio.ByteBuffer bytes,
                                      ProtocolVersion protocolVersion)
                               throws InvalidTypeException
        Deserialize the given ByteBuffer instance according to the CQL type handled by this codec.

        Implementation notes:

        1. Null or empty buffers should be gracefully handled and no exception should be raised; these should be considered as the equivalent of a NULL CQL value and, in most cases, should map to null or a default value for the corresponding Java type, if applicable;
        2. Codecs for CQL collection types should clearly document whether they return immutable collections or not (note that the driver's default collection codecs return mutable collections);
        3. Codecs for CQL collection types should avoid returning null; they should return empty collections instead (the driver's default collection codecs all comply with this rule).
        4. The provided ByteBuffer should never be consumed by read operations that modify its current position; if necessary, ByteBuffer.duplicate() duplicate} it before consuming.
        Parameters:
        bytes - A ByteBuffer instance containing the serialized form of T; may be null or empty.
        protocolVersion - the protocol version to use when serializing bytes. In most cases, the proper value to provide for this argument is the value returned by ProtocolOptions#getProtocolVersion (which is the protocol version in use by the driver).
        Returns:
        An instance of T
        Throws:
        InvalidTypeException - if the given ByteBuffer instance cannot be deserialized
      • parse

        public abstract T parse​(java.lang.String value)
                         throws InvalidTypeException
        Parse the given CQL literal into an instance of the Java type handled by this codec.

        Implementors should take care of unquoting and unescaping the given CQL string where applicable. Null values and empty Strings should be accepted, as well as the string "NULL"; in most cases, implementations should interpret these inputs has equivalent to a null reference.

        Implementing this method is not strictly mandatory: internally, the driver only uses it to parse the INITCOND when building the metadata of an aggregate function (and in most cases it will use a built-in codec, unless the INITCOND has a custom type).

        Parameters:
        value - The CQL string to parse, may be null or empty.
        Returns:
        An instance of T; may be null on a null input.
        Throws:
        InvalidTypeException - if the given value cannot be parsed into the expected type
      • format

        public abstract java.lang.String format​(T value)
                                         throws InvalidTypeException
        Format the given value as a valid CQL literal according to the CQL type handled by this codec.

        Implementors should take care of quoting and escaping the resulting CQL literal where applicable. Null values should be accepted; in most cases, implementations should return the CQL keyword "NULL" for null inputs.

        Implementing this method is not strictly mandatory. It is used:

        1. in the query builder, when values are inlined in the query string (see querybuilder.BuiltStatement for a detailed explanation of when this happens);
        2. in the QueryLogger, if parameter logging is enabled;
        3. to format the INITCOND in AggregateMetadata#asCQLQuery(boolean);
        4. in the toString() implementation of some objects (UDTValue, TupleValue, and the internal representation of a ROWS response), which may appear in driver logs.

        If you choose not to implement this method, you should not throw an exception but instead return a constant string (for example "XxxCodec.format not implemented").

        Parameters:
        value - An instance of T; may be null.
        Returns:
        CQL string
        Throws:
        InvalidTypeException - if the given value does not have the expected type
      • accepts

        public boolean accepts​(com.google.common.reflect.TypeToken<?> javaType)
        Return true if this codec is capable of serializing the given javaType.

        The implementation is invariant with respect to the passed argument (through the usage of TypeToken.equals(Object) and it's strongly recommended not to modify this behavior. This means that a codec will only ever return true for the exact Java type that it has been created for.

        If the argument represents a Java primitive type, its wrapper type is considered instead.

        Parameters:
        javaType - The Java type this codec should serialize from and deserialize to; cannot be null.
        Returns:
        true if the codec is capable of serializing the given javaType, and false otherwise.
        Throws:
        java.lang.NullPointerException - if javaType is null.
      • accepts

        public boolean accepts​(java.lang.Class<?> javaType)
        Return true if this codec is capable of serializing the given javaType.

        This implementation simply calls accepts(TypeToken).

        Parameters:
        javaType - The Java type this codec should serialize from and deserialize to; cannot be null.
        Returns:
        true if the codec is capable of serializing the given javaType, and false otherwise.
        Throws:
        java.lang.NullPointerException - if javaType is null.
      • accepts

        public boolean accepts​(DataType cqlType)
        Return true if this codec is capable of deserializing the given cqlType.
        Parameters:
        cqlType - The CQL type this codec should deserialize from and serialize to; cannot be null.
        Returns:
        true if the codec is capable of deserializing the given cqlType, and false otherwise.
        Throws:
        java.lang.NullPointerException - if cqlType is null.
      • accepts

        public boolean accepts​(java.lang.Object value)
        Return true if this codec is capable of serializing the given object. Note that the object's Java type is inferred from the object' runtime (raw) type, contrary to accepts(TypeToken) which is capable of handling generic types.

        This method is intended mostly to be used by the QueryBuilder when no type information is available when the codec is used.

        Implementation notes:

        1. The default implementation is covariant with respect to the passed argument (through the usage of TypeToken#isAssignableFrom(TypeToken) or TypeToken.isSupertypeOf(Type)) and it's strongly recommended not to modify this behavior. This means that, by default, a codec will accept any subtype of the Java type that it has been created for.
        2. The base implementation provided here can only handle non-parameterized types; codecs handling parameterized types, such as collection types, must override this method and perform some sort of "manual" inspection of the actual type parameters.
        3. Similarly, codecs that only accept a partial subset of all possible values must override this method and manually inspect the object to check if it complies or not with the codec's limitations.
        Parameters:
        value - The Java type this codec should serialize from and deserialize to; cannot be null.
        Returns:
        true if the codec is capable of serializing the given javaType, and false otherwise.
        Throws:
        java.lang.NullPointerException - if value is null.
      • toString

        public java.lang.String toString()
        Overrides:
        toString in class java.lang.Object