Class TypeCodec<T>
- java.lang.Object
-
- org.apache.cassandra.cql3.functions.types.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 givenCQL type
and a givenJava Type
.Serializing and deserializing
Two methods handle the serialization and deserialization of Java types into CQL types according to the native protocol specifications:
serialize(Object, ProtocolVersion)
: used to serialize from the codec's Java type to aByteBuffer
instance corresponding to the codec's CQL type;deserialize(ByteBuffer, ProtocolVersion)
: used to deserialize aByteBuffer
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:
format(Object)
: formats the Java type handled by the codec as a CQL string;parse(String)
; parses a CQL string into the Java type handled by the codec.
Inspection
Codecs also have the following inspection methods:
accepts(DataType)
: returns true if the codec can deserialize the given CQL type;accepts(TypeToken)
: returns true if the codec can serialize the given Java type;accepts(Object)
; returns true if the codec can serialize the given object.
Implementation notes
- TypeCodec implementations must be thread-safe.
- TypeCodec implementations must perform fast and never block.
- 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.
- 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.
- TypeCodec implementations should be stateless and immutable.
- TypeCodec implementations should interpret
null
values and empty ByteBuffers (i.e.
) in a reasonable way; usually,Buffer.remaining()
== 0NULL
CQL values should map tonull
references, but exceptions exist; e.g. for varchar types, aNULL
CQL value maps to anull
reference, whereas an empty buffer maps to an empty String. For collection types, it is also admitted thatNULL
CQL values map to empty Java collections instead ofnull
references. In any case, the codec's behavior in respect tonull
values and empty ByteBuffers should be clearly documented. - 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 primitiveboolean
types; there is one such interface for each Java primitive type). - 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 shouldduplicate
their byte buffers prior to reading them.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
TypeCodec.AbstractCollectionCodec<E,C extends java.util.Collection<E>>
static class
TypeCodec.AbstractMapCodec<K,V>
Base class for codecs mapping CQLmaps
to a JavaMap
.static class
TypeCodec.AbstractTupleCodec<T>
Base class for codecs mapping CQLtuples
to Java objects.static class
TypeCodec.AbstractUDTCodec<T>
Base class for codecs mapping CQLuser-defined types
(UDTs) to Java objects.static class
TypeCodec.PrimitiveBooleanCodec
A codec that is capable of handling primitive booleans, thus avoiding the overhead of boxing and unboxing such primitives.static class
TypeCodec.PrimitiveByteCodec
A codec that is capable of handling primitive bytes, thus avoiding the overhead of boxing and unboxing such primitives.static class
TypeCodec.PrimitiveDoubleCodec
A codec that is capable of handling primitive doubles, thus avoiding the overhead of boxing and unboxing such primitives.static class
TypeCodec.PrimitiveFloatCodec
A codec that is capable of handling primitive floats, thus avoiding the overhead of boxing and unboxing such primitives.static class
TypeCodec.PrimitiveIntCodec
A codec that is capable of handling primitive ints, thus avoiding the overhead of boxing and unboxing such primitives.static class
TypeCodec.PrimitiveLongCodec
A codec that is capable of handling primitive longs, thus avoiding the overhead of boxing and unboxing such primitives.static class
TypeCodec.PrimitiveShortCodec
A codec that is capable of handling primitive shorts, thus avoiding the overhead of boxing and unboxing such primitives.
-
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)
Returntrue
if this codec is capable of serializing the givenjavaType
.boolean
accepts(java.lang.Class<?> javaType)
Returntrue
if this codec is capable of serializing the givenjavaType
.boolean
accepts(java.lang.Object value)
Returntrue
if this codec is capable of serializing the given object.boolean
accepts(DataType cqlType)
Returntrue
if this codec is capable of deserializing the givencqlType
.static TypeCodec<java.lang.String>
ascii()
Return the default codec for the CQL typeascii
.static TypeCodec.PrimitiveLongCodec
bigint()
Return the default codec for the CQL typebigint
.static TypeCodec<java.nio.ByteBuffer>
blob()
Return the default codec for the CQL typeblob
.static TypeCodec.PrimitiveBooleanCodec
cboolean()
Return the default codec for the CQL typeboolean
.static TypeCodec.PrimitiveDoubleCodec
cdouble()
Return the default codec for the CQL typedouble
.static TypeCodec.PrimitiveFloatCodec
cfloat()
Return the default codec for the CQL typefloat
.static TypeCodec.PrimitiveIntCodec
cint()
Return the default codec for the CQL typeint
.static TypeCodec.PrimitiveLongCodec
counter()
Return the default codec for the CQL typecounter
.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 typedate
.static TypeCodec<java.math.BigDecimal>
decimal()
Return the default codec for the CQL typedecimal
.abstract T
deserialize(java.nio.ByteBuffer bytes, ProtocolVersion protocolVersion)
Deserialize the givenByteBuffer
instance according to the CQL type handled by this codec.static TypeCodec<Duration>
duration()
Returns the default codec for theDuration 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 typeinet
.static <T> TypeCodec<java.util.List<T>>
list(TypeCodec<T> elementCodec)
Return a newly-created codec for the CQL typelist
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 typemap
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 typeset
whose element type is determined by the given element codec.static TypeCodec.PrimitiveShortCodec
smallInt()
Return the default codec for the CQL typesmallint
.static TypeCodec.PrimitiveLongCodec
time()
Return the default codec for the CQL typetime
.static TypeCodec<java.util.Date>
timestamp()
Return the default codec for the CQL typetimestamp
.static TypeCodec<java.util.UUID>
timeUUID()
Return the default codec for the CQL typetimeuuid
.static TypeCodec.PrimitiveByteCodec
tinyInt()
Return the default codec for the CQL typetinyint
.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 typeuuid
.static TypeCodec<java.lang.String>
varchar()
Return the default codec for the CQL typevarchar
.static TypeCodec<java.math.BigInteger>
varint()
Return the default codec for the CQL typevarint
.
-
-
-
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 useTypeCodec(DataType, TypeToken)
instead.- Parameters:
javaClass
- The Java class this codec serializes from and deserializes to.
-
-
Method Detail
-
cboolean
public static TypeCodec.PrimitiveBooleanCodec cboolean()
Return the default codec for the CQL typeboolean
. The returned codec maps the CQL typeboolean
into the Java typeBoolean
. 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 typetinyint
. The returned codec maps the CQL typetinyint
into the Java typeByte
. 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 typesmallint
. The returned codec maps the CQL typesmallint
into the Java typeShort
. 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 typeint
. The returned codec maps the CQL typeint
into the Java typeInteger
. 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 typebigint
. The returned codec maps the CQL typebigint
into the Java typeLong
. 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 typecounter
. The returned codec maps the CQL typecounter
into the Java typeLong
. 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 typefloat
. The returned codec maps the CQL typefloat
into the Java typeFloat
. 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 typedouble
. The returned codec maps the CQL typedouble
into the Java typeDouble
. 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 typevarint
. The returned codec maps the CQL typevarint
into the Java typeBigInteger
. 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 typedecimal
. The returned codec maps the CQL typedecimal
into the Java typeBigDecimal
. 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 typeascii
. The returned codec maps the CQL typeascii
into the Java typeString
. 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 typevarchar
. The returned codec maps the CQL typevarchar
into the Java typeString
. 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 typeblob
. The returned codec maps the CQL typeblob
into the Java typeByteBuffer
. 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 typedate
. The returned codec maps the CQL typedate
into the Java typeLocalDate
. 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 typetime
. The returned codec maps the CQL typetime
into the Java typeLong
. 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 typetimestamp
. The returned codec maps the CQL typetimestamp
into the Java typeDate
. 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 typeuuid
. The returned codec maps the CQL typeuuid
into the Java typeUUID
. 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 typetimeuuid
. The returned codec maps the CQL typetimeuuid
into the Java typeUUID
. 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 typeinet
. The returned codec maps the CQL typeinet
into the Java typeInetAddress
. 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 typelist
whose element type is determined by the given element codec. The returned codec maps the CQL typelist
into the Java typeList
. 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 typeset
whose element type is determined by the given element codec. The returned codec maps the CQL typeset
into the Java typeSet
. 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 typemap
whose key type and value type are determined by the given codecs. The returned codec maps the CQL typemap
into the Java typeMap
. 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 typeUDTValue
. 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 typeTupleValue
. 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 toparse
andformat
literals for this type. This is notoriously true for types inheriting fromorg.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 theDuration 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 regularcustom 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:
- Null values should be gracefully handled and no exception should be raised; these should be considered as the equivalent of a NULL CQL value;
- Codecs for CQL collection types should not permit null elements;
- Codecs for CQL collection types should treat a
null
input as the equivalent of an empty collection.
- Parameters:
value
- An instance of T; may benull
.protocolVersion
- the protocol version to use when serializingbytes
. In most cases, the proper value to provide for this argument is the value returned byProtocolOptions#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 givenByteBuffer
instance according to the CQL type handled by this codec.Implementation notes:
- 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; - 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);
- 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). - 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
- AByteBuffer
instance containing the serialized form of T; may benull
or empty.protocolVersion
- the protocol version to use when serializingbytes
. In most cases, the proper value to provide for this argument is the value returned byProtocolOptions#getProtocolVersion
(which is the protocol version in use by the driver).- Returns:
- An instance of T
- Throws:
InvalidTypeException
- if the givenByteBuffer
instance cannot be deserialized
- 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
-
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 anull
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 benull
or empty.- Returns:
- An instance of T; may be
null
on anull 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"
fornull
inputs.Implementing this method is not strictly mandatory. It is used:
- in the query builder, when values are inlined in the query string (see
querybuilder.BuiltStatement
for a detailed explanation of when this happens); - in the
QueryLogger
, if parameter logging is enabled; - to format the INITCOND in
AggregateMetadata#asCQLQuery(boolean)
; - in the
toString()
implementation of some objects (UDTValue
,TupleValue
, and the internal representation of aROWS
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 benull
.- Returns:
- CQL string
- Throws:
InvalidTypeException
- if the given value does not have the expected type
- in the query builder, when values are inlined in the query string (see
-
accepts
public boolean accepts(com.google.common.reflect.TypeToken<?> javaType)
Returntrue
if this codec is capable of serializing the givenjavaType
.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 returntrue
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 benull
.- Returns:
true
if the codec is capable of serializing the givenjavaType
, andfalse
otherwise.- Throws:
java.lang.NullPointerException
- ifjavaType
isnull
.
-
accepts
public boolean accepts(java.lang.Class<?> javaType)
Returntrue
if this codec is capable of serializing the givenjavaType
.This implementation simply calls
accepts(TypeToken)
.- Parameters:
javaType
- The Java type this codec should serialize from and deserialize to; cannot benull
.- Returns:
true
if the codec is capable of serializing the givenjavaType
, andfalse
otherwise.- Throws:
java.lang.NullPointerException
- ifjavaType
isnull
.
-
accepts
public boolean accepts(DataType cqlType)
Returntrue
if this codec is capable of deserializing the givencqlType
.- Parameters:
cqlType
- The CQL type this codec should deserialize from and serialize to; cannot benull
.- Returns:
true
if the codec is capable of deserializing the givencqlType
, andfalse
otherwise.- Throws:
java.lang.NullPointerException
- ifcqlType
isnull
.
-
accepts
public boolean accepts(java.lang.Object value)
Returntrue
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 toaccepts(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:
- The default implementation is covariant with respect to the passed argument
(through the usage of
TypeToken#isAssignableFrom(TypeToken)
orTypeToken.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. - 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.
- 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 benull
.- Returns:
true
if the codec is capable of serializing the givenjavaType
, andfalse
otherwise.- Throws:
java.lang.NullPointerException
- ifvalue
isnull
.
- The default implementation is covariant with respect to the passed argument
(through the usage of
-
toString
public java.lang.String toString()
- Overrides:
toString
in classjava.lang.Object
-
-