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.ObjectA Codec that can serialize and deserialize to and from a givenCQL typeand 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 aByteBufferinstance corresponding to the codec's CQL type;deserialize(ByteBuffer, ProtocolVersion): used to deserialize aByteBufferinstance 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
nullvalues and empty ByteBuffers (i.e.) in a reasonable way; usually,Buffer.remaining()== 0NULLCQL values should map tonullreferences, but exceptions exist; e.g. for varchar types, aNULLCQL value maps to anullreference, whereas an empty buffer maps to an empty String. For collection types, it is also admitted thatNULLCQL values map to empty Java collections instead ofnullreferences. In any case, the codec's behavior in respect tonullvalues 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.PrimitiveBooleanCodecfor primitivebooleantypes; there is one such interface for each Java primitive type). - When deserializing, TypeCodec implementations should not consume
ByteBufferinstances by performing relative read operations that modify their current position; codecs should instead prefer absolute read methods, or, if necessary, they shouldduplicatetheir byte buffers prior to reading them.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classTypeCodec.AbstractCollectionCodec<E,C extends java.util.Collection<E>>static classTypeCodec.AbstractMapCodec<K,V>Base class for codecs mapping CQLmapsto a JavaMap.static classTypeCodec.AbstractTupleCodec<T>Base class for codecs mapping CQLtuplesto Java objects.static classTypeCodec.AbstractUDTCodec<T>Base class for codecs mapping CQLuser-defined types(UDTs) to Java objects.static classTypeCodec.PrimitiveBooleanCodecA codec that is capable of handling primitive booleans, thus avoiding the overhead of boxing and unboxing such primitives.static classTypeCodec.PrimitiveByteCodecA codec that is capable of handling primitive bytes, thus avoiding the overhead of boxing and unboxing such primitives.static classTypeCodec.PrimitiveDoubleCodecA codec that is capable of handling primitive doubles, thus avoiding the overhead of boxing and unboxing such primitives.static classTypeCodec.PrimitiveFloatCodecA codec that is capable of handling primitive floats, thus avoiding the overhead of boxing and unboxing such primitives.static classTypeCodec.PrimitiveIntCodecA codec that is capable of handling primitive ints, thus avoiding the overhead of boxing and unboxing such primitives.static classTypeCodec.PrimitiveLongCodecA codec that is capable of handling primitive longs, thus avoiding the overhead of boxing and unboxing such primitives.static classTypeCodec.PrimitiveShortCodecA 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 booleanaccepts(com.google.common.reflect.TypeToken<?> javaType)Returntrueif this codec is capable of serializing the givenjavaType.booleanaccepts(java.lang.Class<?> javaType)Returntrueif this codec is capable of serializing the givenjavaType.booleanaccepts(java.lang.Object value)Returntrueif this codec is capable of serializing the given object.booleanaccepts(DataType cqlType)Returntrueif this codec is capable of deserializing the givencqlType.static TypeCodec<java.lang.String>ascii()Return the default codec for the CQL typeascii.static TypeCodec.PrimitiveLongCodecbigint()Return the default codec for the CQL typebigint.static TypeCodec<java.nio.ByteBuffer>blob()Return the default codec for the CQL typeblob.static TypeCodec.PrimitiveBooleanCodeccboolean()Return the default codec for the CQL typeboolean.static TypeCodec.PrimitiveDoubleCodeccdouble()Return the default codec for the CQL typedouble.static TypeCodec.PrimitiveFloatCodeccfloat()Return the default codec for the CQL typefloat.static TypeCodec.PrimitiveIntCodeccint()Return the default codec for the CQL typeint.static TypeCodec.PrimitiveLongCodeccounter()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 Tdeserialize(java.nio.ByteBuffer bytes, ProtocolVersion protocolVersion)Deserialize the givenByteBufferinstance according to the CQL type handled by this codec.static TypeCodec<Duration>duration()Returns the default codec for theDuration type.abstract java.lang.Stringformat(T value)Format the given value as a valid CQL literal according to the CQL type handled by this codec.DataTypegetCqlType()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 typelistwhose 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 typemapwhose key type and value type are determined by the given codecs.abstract Tparse(java.lang.String value)Parse the given CQL literal into an instance of the Java type handled by this codec.abstract java.nio.ByteBufferserialize(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 typesetwhose element type is determined by the given element codec.static TypeCodec.PrimitiveShortCodecsmallInt()Return the default codec for the CQL typesmallint.static TypeCodec.PrimitiveLongCodectime()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.PrimitiveByteCodectinyInt()Return the default codec for the CQL typetinyint.java.lang.StringtoString()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 typebooleaninto 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 typetinyintinto 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 typesmallintinto 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 typeintinto 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 typebigintinto 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 typecounterinto 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 typefloatinto 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 typedoubleinto 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 typevarintinto 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 typedecimalinto 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 typeasciiinto 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 typevarcharinto 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 typeblobinto 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 typedateinto 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 typetimeinto 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 typetimestampinto 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 typeuuidinto 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 typetimeuuidinto 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 typeinetinto 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 typelistwhose element type is determined by the given element codec. The returned codec maps the CQL typelistinto 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 typesetwhose element type is determined by the given element codec. The returned codec maps the CQL typesetinto 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 typemapwhose key type and value type are determined by the given codecs. The returned codec maps the CQL typemapinto 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 toparseandformatliterals 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
Durationclass, 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
nullinput 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
ByteBufferinstance 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 givenByteBufferinstance 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
nullor 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
ByteBuffershould never be consumed by read operations that modify its current position; if necessary,ByteBuffer.duplicate()duplicate} it before consuming.
- Parameters:
bytes- AByteBufferinstance containing the serialized form of T; may benullor 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 givenByteBufferinstance 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 anullreference.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 benullor empty.- Returns:
- An instance of T; may be
nullon 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"fornullinputs.Implementing this method is not strictly mandatory. It is used:
- in the query builder, when values are inlined in the query string (see
querybuilder.BuiltStatementfor 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 aROWSresponse), 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)
Returntrueif 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 returntruefor 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:
trueif the codec is capable of serializing the givenjavaType, andfalseotherwise.- Throws:
java.lang.NullPointerException- ifjavaTypeisnull.
-
accepts
public boolean accepts(java.lang.Class<?> javaType)
Returntrueif 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:
trueif the codec is capable of serializing the givenjavaType, andfalseotherwise.- Throws:
java.lang.NullPointerException- ifjavaTypeisnull.
-
accepts
public boolean accepts(DataType cqlType)
Returntrueif this codec is capable of deserializing the givencqlType.- Parameters:
cqlType- The CQL type this codec should deserialize from and serialize to; cannot benull.- Returns:
trueif the codec is capable of deserializing the givencqlType, andfalseotherwise.- Throws:
java.lang.NullPointerException- ifcqlTypeisnull.
-
accepts
public boolean accepts(java.lang.Object value)
Returntrueif 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:
trueif the codec is capable of serializing the givenjavaType, andfalseotherwise.- Throws:
java.lang.NullPointerException- ifvalueisnull.
- The default implementation is covariant with respect to the passed argument
(through the usage of
-
toString
public java.lang.String toString()
- Overrides:
toStringin classjava.lang.Object
-
-