Elffuss BraidHub

kikocis/java-driver public

JAVA-932: Limit visibility of codec internals.

- do not expose default codec classes
- remove "utility" codecs from public API (Enum*Codec, MappingCodec,
  StringParsingCodec).
- remove setObject method from SettableBy*Data.
Changeset0fef13bfb9a064e9fb7b0daff8f64e8cd2c24cf5c2fd06cfe0f91d5c3def7d0a
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-10-07 16:06 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-10-14 22:35 +02:00
Parents0788d958beb9

Browse the files at this changeset

40 files changed

modified changelog/README.md +1 −0
@@ -12,6 +12,7 @@
1212 - [bug] Make table metadata options class visible (JAVA-946)
1313 - [bug] Add crcCheckChance to TableOptionsMetadata#equals/hashCode (JAVA-939)
1414 - [bug] Make TypeCodec return mutable collections (JAVA-922)
15+- [improvement] Limit visibility of codec internals (JAVA-932)
1516
1617
1718 ### 3.0.0-alpha3
modified driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java +0 −6
@@ -265,12 +265,6 @@
265265 return setValue(i, codecFor(i, TupleValue.class).serialize(v, protocolVersion));
266266 }
267267
268- @Override
269- public <V> T setObject(int i, V v) {
270- TypeCodec<V> codec = v == null ? this.<V>codecFor(i) : codecFor(i, v);
271- return set(i, v, codec);
272- }
273-
274268 @Override
275269 public <V> T set(int i, V v, Class<V> targetClass) {
276270 return set(i, v, codecFor(i, targetClass));
modified driver-core/src/main/java/com/datastax/driver/core/AbstractData.java +0 −14
@@ -509,20 +509,6 @@
509509 return wrapped;
510510 }
511511
512- @Override
513- public <V> T setObject(int i, V v) {
514- TypeCodec<V> codec = v == null ? this.<V>codecFor(i) : codecFor(i, v);
515- return set(i, v, codec);
516- }
517-
518- @Override
519- public <V> T setObject(String name, V v) {
520- for (int i : getAllIndexesOf(name)) {
521- setObject(i, v);
522- }
523- return wrapped;
524- }
525-
526512 @Override
527513 public <V> T set(int i, V v, Class<V> targetClass) {
528514 return set(i, v, codecFor(i, targetClass));
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −1
@@ -442,6 +442,6 @@
442442 if (value == null || value.remaining() == 0)
443443 return false;
444444
445- return TypeCodec.BooleanCodec.instance.deserializeNoBoxing(value, protocolVersion);
445+ return TypeCodec.cboolean().deserializeNoBoxing(value, protocolVersion);
446446 }
447447 }
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +0 −16
@@ -838,22 +838,6 @@
838838 return wrapper.setTupleValue(name, v);
839839 }
840840
841- /**
842- * {@inheritDoc}
843- */
844- @Override
845- public <V> BoundStatement setObject(int i, V v) {
846- return wrapper.setObject(i, v);
847- }
848-
849- /**
850- * {@inheritDoc}
851- */
852- @Override
853- public <V> BoundStatement setObject(String name, V v) {
854- return wrapper.setObject(name, v);
855- }
856-
857841 /**
858842 * {@inheritDoc}
859843 */
modified driver-core/src/main/java/com/datastax/driver/core/CassandraTypeParser.java +2 −2
@@ -105,7 +105,7 @@
105105
106106 String keyspace = parser.readOne();
107107 parser.skipBlankAndComma();
108- String typeName = TypeCodec.VarcharCodec.instance.deserialize(Bytes.fromHexString("0x" + parser.readOne()), protocolVersion);
108+ String typeName = TypeCodec.varchar().deserialize(Bytes.fromHexString("0x" + parser.readOne()), protocolVersion);
109109 parser.skipBlankAndComma();
110110 Map<String, String> rawFields = parser.getNameAndTypeParameters();
111111 List<UserType.Field> fields = new ArrayList<UserType.Field>(rawFields.size());
@@ -319,7 +319,7 @@
319319 String bbHex = readNextIdentifier();
320320 String name = null;
321321 try {
322- name = TypeCodec.VarcharCodec.instance.deserialize(Bytes.fromHexString("0x" + bbHex), ProtocolVersion.NEWEST_SUPPORTED);
322+ name = TypeCodec.varchar().deserialize(Bytes.fromHexString("0x" + bbHex), ProtocolVersion.NEWEST_SUPPORTED);
323323 } catch (NumberFormatException e) {
324324 throwSyntaxError(e.getMessage());
325325 }
modified driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java +137 −119
@@ -17,6 +17,7 @@
1717
1818 import java.lang.reflect.ParameterizedType;
1919 import java.lang.reflect.Type;
20+import java.nio.ByteBuffer;
2021 import java.util.*;
2122 import java.util.concurrent.CopyOnWriteArrayList;
2223 import java.util.concurrent.ExecutionException;
@@ -31,29 +32,28 @@
3132
3233 import static com.google.common.base.Preconditions.checkNotNull;
3334
34-import com.datastax.driver.core.TypeCodec.*;
3535 import com.datastax.driver.core.exceptions.CodecNotFoundException;
3636
37-import static com.datastax.driver.core.DataType.Name.*;
37+import static com.datastax.driver.core.DataType.Name.LIST;
38+import static com.datastax.driver.core.DataType.Name.MAP;
39+import static com.datastax.driver.core.DataType.Name.SET;
3840
3941 /**
40- * A registry for {@link TypeCodec}s. When the driver
42+ * A registry for {@link TypeCodec codec}s. When the driver
4143 * needs to serialize or deserialize an object,
42- * it will lookup in the {@link CodecRegistry} for
44+ * it will lookup in the registry for
4345 * a suitable codec.
4446 *
4547 * <h3>Usage</h3>
4648 *
4749 * <p>
48- * Most users won't need to manipulate {@link CodecRegistry} instances directly.
49- * Only those willing to register user-defined codecs are required to do so.
50- * By default, the driver uses {@link CodecRegistry#DEFAULT_INSTANCE}, a shareable
51- * instance that initially contains all the built-in codecs required by the driver.
50+ * By default, the driver uses the CodecRegistry's {@link CodecRegistry#DEFAULT_INSTANCE},
51+ * a shareable instance that initially contains all the built-in codecs required by the driver.
5252 *
5353 * <p>
54- * Users willing to customize their {@link CodecRegistry} can do so by {@code register registering}
55- * new {@link TypeCodec}s either on {@link CodecRegistry#DEFAULT_INSTANCE},
56- * or on a newly-crated one:
54+ * For most users, the default instance is good enough and
55+ * they won't need to manipulate {@link CodecRegistry} instances directly.
56+ * Only those willing to {@link #register(TypeCodec) register} user-defined codecs are required to do so:
5757 *
5858 * <pre>
5959 * CodecRegistry myCodecRegistry;
@@ -61,20 +61,11 @@
6161 * myCodecRegistry = CodecRegistry.DEFAULT_INSTANCE;
6262 * // or alternatively, create a new one
6363 * myCodecRegistry = new CodecRegistry();
64- * // then
64+ * // then register additional codecs
6565 * myCodecRegistry.register(myCodec1, myCodec2, myCodec3);
6666 * </pre>
6767 *
6868 * <p>
69- * Note that the order in which codecs are registered matters;
70- * if a codec is registered while another codec already handles the same
71- * CQL-to-Java mapping, that codec will never be used (unless
72- * the user forces its usage through e.g. {@link GettableByIndexData#get(int, TypeCodec)}).
73- * In order words, it is not possible to replace an existing codec,
74- * specially the built-in ones; it is only possible to enrich the initial
75- * set of codecs with new ones.
76- *
77- * <p>
7869 * To be used by the driver, {@link CodecRegistry} instances must then
7970 * be associated with a {@link Cluster} instance:
8071 *
@@ -90,20 +81,21 @@
9081 * CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
9182 * </pre>
9283 *
93- * <p>
94- * By default, {@link Cluster} instances will use {@link CodecRegistry#DEFAULT_INSTANCE}.
95- *
9684 * <h3>Example</h3>
9785 *
9886 * <p>
99- * E.g. let's suppose you want to have all your CQL timestamps
100- * deserialized as {@code java.time.DateTime} instances:
87+ * Suppose that one wants to have all CQL timestamps seamlessly
88+ * converted to {@code java.time.DateTime} instances and vice versa; the following
89+ * code contains the necessary steps to achieve this:
10190 *
10291 * <pre>
92+ * // 1. Instantiate the custom codec
10393 * TypeCodec&lt;DateTime> timestampCodec = ...
104- * CodecRegistry myCodecRegistry = new CodecRegistry().register(timestampCodec);
94+ * // 2. Register the codec
95+ * CodecRegistry.DEFAULT_INSTANCE.register(timestampCodec);
10596 * </pre>
10697 *
98+ * <p>
10799 * Read the
108100 * <a href="http://datastax.github.io/java-driver/features/custom_codecs">online documentation</a>
109101 * for more examples.
@@ -111,59 +103,72 @@
111103 * <h3>Notes</h3>
112104 *
113105 * <p>
114- * When a {@link CodecRegistry} cannot find a suitable codec among all registered codecs,
115- * it will attempt to create a suitable codec.
106+ * <strong>Registration order</strong>: the order in which codecs are registered matters:
107+ * when looking for a suitable codec, the registry will consider
108+ * all registered codecs <em>in the order they were registered</em>, and
109+ * will pick the first matching one.
110+ *
111+ * <p>
112+ * If a codec is registered while another codec already handles the <em>exact same</em>
113+ * CQL-to-Java mapping, that codec will never be used (unless
114+ * the user forces its usage through e.g. {@link GettableByIndexData#get(int, TypeCodec)}).
115+ * In order words, it is not possible to replace an existing codec,
116+ * specially the built-in ones; it is only possible to enrich the initial
117+ * set of codecs with new ones.
118+ *
116119 * <p>
117- * If the creation succeeds, that codec is added to the list of known codecs and is returned;
120+ * <strong>On-the-fly codec instantiation</strong>: When a {@link CodecRegistry}
121+ * cannot find a suitable codec among all registered codecs,
122+ * it will attempt to create such a codec on-the-fly. If the creation succeeds, that codec is returned;
118123 * otherwise, a {@link CodecNotFoundException} is thrown.
124+ *
119125 * <p>
120126 * Note that {@link CodecRegistry} instances can only create codecs in very limited situations:
121127 * <ol>
122- * <li>Codecs for Enums are created on the fly using {@link EnumStringCodec};</li>
123- * <li>Codecs for {@link UserType user types} are created on the fly using {@link UDTCodec};</li>
124- * <li>Codecs for {@link TupleType tuple types} are created on the fly using {@link TupleCodec};</li>
125- * <li>Codecs for collections are created on the fly using {@link ListCodec}, {@link SetCodec} and
126- * {@link MapCodec}, if their element types can be handled by existing codecs (or codecs that can
128+ * <li>Codecs for {@link UserType user types} are created on the fly using {@link TypeCodec#userType(UserType)};</li>
129+ * <li>Codecs for {@link TupleType tuple types} are created on the fly using {@link TypeCodec#tuple(TupleType)}};</li>
130+ * <li>Codecs for collections are created on the fly using {@link TypeCodec#list(TypeCodec)}}, {@link TypeCodec#set(TypeCodec)}} and
131+ * {@link TypeCodec#map(TypeCodec, TypeCodec)}}, if their element types can be handled by existing codecs (or codecs that can
127132 * themselves be generated).</li>
133+ * <li>Codecs for {@link com.datastax.driver.core.DataType.CustomType custom types} are created on the fly using {@link TypeCodec#custom(DataType.CustomType)};</li>
128134 * </ol>
129135 * Other combinations of Java and CQL types cannot have their codecs created on the fly;
130136 * such codecs must be manually registered.
131137 * <p>
132- * Note that the default set of codecs has no support for
133- * <a href="https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java">Cassandra custom types</a>;
134- * to be able to deserialize values of such types, you need to manually register an appropriate codec.
135- * <p>
136- * {@link CodecRegistry} instances are not meant to be shared between two or more {@link Cluster} instances; doing so
137- * could yield unexpected results.
138+ *
139+ * <strong>Debugging the codec registry</strong>: it is possible to turn on log messages
140+ * by setting the {@code com.datastax.driver.core.CodecRegistry} logger level to {@code TRACE}.
141+ * Beware that the registry can be very verbose at this log level.
142+ *
138143 * <p>
139- * {@link CodecRegistry} instances are thread-safe.
144+ * <strong>Thread-safety</strong>: {@link CodecRegistry} instances are thread-safe.
140145 *
141146 */
142-@SuppressWarnings("all")
143147 public final class CodecRegistry {
144148
145149 private static final Logger logger = LoggerFactory.getLogger(CodecRegistry.class);
146150
151+ @SuppressWarnings("unchecked")
147152 private static final ImmutableSet<TypeCodec<?>> PRIMITIVE_CODECS = ImmutableSet.of(
148- BlobCodec.instance,
149- BooleanCodec.instance,
150- SmallIntCodec.instance,
151- TinyIntCodec.instance,
152- IntCodec.instance,
153- BigintCodec.instance,
154- CounterCodec.instance,
155- DoubleCodec.instance,
156- FloatCodec.instance,
157- VarintCodec.instance,
158- DecimalCodec.instance,
159- VarcharCodec.instance, // must be declared before AsciiCodec so it gets chosen when CQL type not available
160- AsciiCodec.instance,
161- TimestampCodec.instance,
162- DateCodec.instance,
163- TimeCodec.instance,
164- UUIDCodec.instance, // must be declared before TimeUUIDCodec so it gets chosen when CQL type not available
165- TimeUUIDCodec.instance,
166- InetCodec.instance
153+ TypeCodec.blob(),
154+ TypeCodec.cboolean(),
155+ TypeCodec.smallInt(),
156+ TypeCodec.tinyInt(),
157+ TypeCodec.cint(),
158+ TypeCodec.bigint(),
159+ TypeCodec.counter(),
160+ TypeCodec.cdouble(),
161+ TypeCodec.cfloat(),
162+ TypeCodec.varint(),
163+ TypeCodec.decimal(),
164+ TypeCodec.varchar(), // must be declared before AsciiCodec so it gets chosen when CQL type not available
165+ TypeCodec.ascii(),
166+ TypeCodec.timestamp(),
167+ TypeCodec.date(),
168+ TypeCodec.time(),
169+ TypeCodec.uuid(), // must be declared before TimeUUIDCodec so it gets chosen when CQL type not available
170+ TypeCodec.timeUUID(),
171+ TypeCodec.inet()
167172 );
168173
169174 /**
@@ -174,6 +179,9 @@
174179 */
175180 public static final CodecRegistry DEFAULT_INSTANCE = new CodecRegistry();
176181
182+ /**
183+ * Cache key for the codecs cache.
184+ */
177185 private static final class CacheKey {
178186
179187 private final DataType cqlType;
@@ -197,12 +205,23 @@
197205
198206 @Override
199207 public int hashCode() {
200- return Objects.hashCode(javaType, cqlType);
208+ return Objects.hashCode(cqlType, javaType);
209+ }
210+
211+ }
212+
213+ /**
214+ * Cache loader for the codecs cache.
215+ */
216+ private class TypeCodecCacheLoader extends CacheLoader<CacheKey, TypeCodec<?>> {
217+ @Override
218+ public TypeCodec<?> load(CacheKey cacheKey) {
219+ return findCodec(cacheKey.cqlType, cacheKey.javaType);
201220 }
202221 }
203222
204223 /**
205- * A complexity-based weigher.
224+ * A complexity-based weigher for the codecs cache.
206225 * Weights are computed mainly according to the CQL type:
207226 * <ol>
208227 * <li>Manually-registered codecs always weigh 0;
@@ -254,6 +273,10 @@
254273 }
255274 }
256275
276+ /**
277+ * Simple removal listener for the codec cache (can be used for debugging purposes
278+ * by setting the {@code com.datastax.driver.core.CodecRegistry} logger level to {@code TRACE}.
279+ */
257280 private class TypeCodecRemovalListener implements RemovalListener<CacheKey, TypeCodec<?>> {
258281 @Override
259282 public void onRemoval(RemovalNotification<CacheKey, TypeCodec<?>> notification) {
@@ -262,7 +285,7 @@
262285 }
263286
264287 /**
265- * The list of all known codecs.
288+ * The list of registered codecs.
266289 * This list is initialized with the built-in codecs;
267290 * User-defined codecs are appended to the list.
268291 */
@@ -279,22 +302,20 @@
279302 */
280303 public CodecRegistry() {
281304 this.codecs = new CopyOnWriteArrayList<TypeCodec<?>>(PRIMITIVE_CODECS);
282- this.cache = CacheBuilder.newBuilder()
305+ this.cache = defaultCacheBuilder().build(new TypeCodecCacheLoader());
306+ }
307+
308+ private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() {
309+ CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder()
283310 // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs,
284311 // so let's start with roughly 1/4 of that
285312 .initialCapacity(100)
286313 .weigher(new TypeCodecWeigher())
287- // a cache with all 418 "basic" codecs weighs 399 (19*2 + 19*19),
288- // so let's cap at roughly 2.5x this size
289- .maximumWeight(1000)
290- .concurrencyLevel(Runtime.getRuntime().availableProcessors() * 4)
291- .removalListener(new TypeCodecRemovalListener())
292- .build(
293- new CacheLoader<CacheKey, TypeCodec<?>>() {
294- public TypeCodec<?> load(CacheKey cacheKey) {
295- return findCodec(cacheKey.cqlType, cacheKey.javaType);
296- }
297- });
314+ .maximumWeight(1000);
315+ if (logger.isTraceEnabled())
316+ // do not bother adding a listener if it will be ineffective
317+ builder = builder.removalListener(new TypeCodecRemovalListener());
318+ return builder;
298319 }
299320
300321 /**
@@ -355,9 +376,7 @@
355376 * @throws CodecNotFoundException if a suitable codec cannot be found.
356377 */
357378 public <T> TypeCodec<T> codecFor(T value) {
358- checkNotNull(value, "Parameter value cannot be null");
359- TypeCodec<T> codec = findCodec(null, value);
360- return codec;
379+ return findCodec(null, value);
361380 }
362381
363382 /**
@@ -394,7 +413,7 @@
394413 * Codecs returned by this method are cached.
395414 *
396415 * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
397- * @param javaType The Java type the codec should accept; must not be {@code null}.
416+ * @param javaType The Java type the codec should accept; can be {@code null}.
398417 * @return A suitable codec.
399418 * @throws CodecNotFoundException if a suitable codec cannot be found.
400419 */
@@ -416,13 +435,11 @@
416435 * Codecs returned by this method are cached.
417436 *
418437 * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
419- * @param javaType The {@link TypeToken Java type} the codec should accept; must not be {@code null}.
438+ * @param javaType The {@link TypeToken Java type} the codec should accept; can be {@code null}.
420439 * @return A suitable codec.
421440 * @throws CodecNotFoundException if a suitable codec cannot be found.
422441 */
423442 public <T> TypeCodec<T> codecFor(DataType cqlType, TypeToken<T> javaType) throws CodecNotFoundException {
424- checkNotNull(cqlType, "Parameter cqlType cannot be null");
425- checkNotNull(javaType, "Parameter javaType cannot be null");
426443 return lookupCodec(cqlType, javaType);
427444 }
428445
@@ -438,24 +455,23 @@
438455 * <p>
439456 * Codecs returned by this method are <em>NOT</em> cached.
440457 *
441- * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
458+ * @param cqlType The {@link DataType CQL type} the codec should accept; can be {@code null}.
442459 * @param value The value the codec should accept; must not be {@code null}.
443460 * @return A suitable codec.
444461 * @throws CodecNotFoundException if a suitable codec cannot be found.
445462 */
446463 public <T> TypeCodec<T> codecFor(DataType cqlType, T value) {
447- checkNotNull(cqlType, "Parameter cqlType cannot be null");
448- checkNotNull(value, "Parameter value cannot be null");
449464 return findCodec(cqlType, value);
450465 }
451466
467+ @SuppressWarnings("unchecked")
452468 private <T> TypeCodec<T> lookupCodec(DataType cqlType, TypeToken<T> javaType) {
453469 checkNotNull(cqlType, "Parameter cqlType cannot be null");
454- logger.trace("Querying cache for codec [{} <-> {}]", cqlType, javaType);
470+ logger.trace("Querying cache for codec [{} <-> {}]", cqlType, javaType == null ? "ANY" : javaType);
455471 CacheKey cacheKey = new CacheKey(cqlType, javaType);
456472 try {
457473 TypeCodec<?> codec = cache.get(cacheKey);
458- logger.trace("Returning cached codec [{} <-> {}]", cqlType, javaType);
474+ logger.trace("Returning cached codec {}", codec);
459475 return (TypeCodec<T>)codec;
460476 } catch (UncheckedExecutionException e) {
461477 if(e.getCause() instanceof CodecNotFoundException) {
@@ -467,13 +483,12 @@
467483 }
468484 }
469485
486+ @SuppressWarnings("unchecked")
470487 private <T> TypeCodec<T> findCodec(DataType cqlType, TypeToken<T> javaType) {
471488 checkNotNull(cqlType, "Parameter cqlType cannot be null");
472- logger.trace("Looking for codec [{} <-> {}]",
473- cqlType == null ? "ANY" : cqlType,
474- javaType == null ? "ANY" : javaType);
489+ logger.trace("Looking for codec [{} <-> {}]", cqlType, javaType == null ? "ANY" : javaType);
475490 for (TypeCodec<?> codec : codecs) {
476- if ((cqlType == null || codec.accepts(cqlType)) && (javaType == null || codec.accepts(javaType))) {
491+ if (codec.accepts(cqlType) && (javaType == null || codec.accepts(javaType))) {
477492 logger.trace("Codec found: {}", codec);
478493 return (TypeCodec<T>)codec;
479494 }
@@ -481,6 +496,7 @@
481496 return createCodec(cqlType, javaType);
482497 }
483498
499+ @SuppressWarnings("unchecked")
484500 private <T> TypeCodec<T> findCodec(DataType cqlType, T value) {
485501 checkNotNull(value, "Parameter value cannot be null");
486502 logger.trace("Looking for codec [{} <-> {}]", cqlType == null ? "ANY" : cqlType, value.getClass());
@@ -496,10 +512,10 @@
496512 private <T> TypeCodec<T> createCodec(DataType cqlType, TypeToken<T> javaType) {
497513 TypeCodec<T> codec = maybeCreateCodec(cqlType, javaType);
498514 if (codec == null)
499- throw newException(cqlType, javaType);
515+ throw notFound(cqlType, javaType);
500516 // double-check that the created codec satisfies the initial request
501517 if (!codec.accepts(cqlType) || (javaType != null && !codec.accepts(javaType)))
502- throw newException(cqlType, javaType);
518+ throw notFound(cqlType, javaType);
503519 logger.trace("Codec created: {}", codec);
504520 return codec;
505521 }
@@ -507,21 +523,18 @@
507523 private <T> TypeCodec<T> createCodec(DataType cqlType, T value) {
508524 TypeCodec<T> codec = maybeCreateCodec(cqlType, value);
509525 if(codec == null)
510- throw newException(cqlType, TypeToken.of(value.getClass()));
526+ throw notFound(cqlType, TypeToken.of(value.getClass()));
511527 // double-check that the created codec satisfies the initial request
512528 if((cqlType != null && !codec.accepts(cqlType)) || !codec.accepts(value))
513- throw newException(cqlType, TypeToken.of(value.getClass()));
529+ throw notFound(cqlType, TypeToken.of(value.getClass()));
514530 logger.trace("Codec created: {}", codec);
515531 return codec;
516532 }
517533
534+ @SuppressWarnings("unchecked")
518535 private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, TypeToken<T> javaType) {
519536 checkNotNull(cqlType);
520537
521- if ((cqlType.getName() == VARCHAR || cqlType.getName() == TEXT) && javaType != null && Enum.class.isAssignableFrom(javaType.getRawType())) {
522- return new EnumStringCodec(javaType.getRawType());
523- }
524-
525538 if (cqlType.getName() == LIST && (javaType == null || List.class.isAssignableFrom(javaType.getRawType()))) {
526539 TypeToken<?> elementType = null;
527540 if (javaType != null && javaType.getType() instanceof ParameterizedType) {
@@ -529,7 +542,7 @@
529542 elementType = TypeToken.of(typeArguments[0]);
530543 }
531544 TypeCodec<?> eltCodec = findCodec(cqlType.getTypeArguments().get(0), elementType);
532- return new ListCodec(eltCodec);
545+ return (TypeCodec<T>)TypeCodec.list(eltCodec);
533546 }
534547
535548 if (cqlType.getName() == SET && (javaType == null || Set.class.isAssignableFrom(javaType.getRawType()))) {
@@ -539,7 +552,7 @@
539552 elementType = TypeToken.of(typeArguments[0]);
540553 }
541554 TypeCodec<?> eltCodec = findCodec(cqlType.getTypeArguments().get(0), elementType);
542- return new SetCodec(eltCodec);
555+ return (TypeCodec<T>)TypeCodec.set(eltCodec);
543556 }
544557
545558 if (cqlType.getName() == MAP && (javaType == null || Map.class.isAssignableFrom(javaType.getRawType()))) {
@@ -552,39 +565,40 @@
552565 }
553566 TypeCodec<?> keyCodec = findCodec(cqlType.getTypeArguments().get(0), keyType);
554567 TypeCodec<?> valueCodec = findCodec(cqlType.getTypeArguments().get(1), valueType);
555- return new MapCodec(keyCodec, valueCodec);
568+ return (TypeCodec<T>)TypeCodec.map(keyCodec, valueCodec);
556569 }
557570
558571 if (cqlType instanceof TupleType && (javaType == null || TupleValue.class.isAssignableFrom(javaType.getRawType()))) {
559- return (TypeCodec<T>)new TupleCodec((TupleType)cqlType);
572+ return (TypeCodec<T>)TypeCodec.tuple((TupleType)cqlType);
560573 }
561574
562575 if (cqlType instanceof UserType && (javaType == null || UDTValue.class.isAssignableFrom(javaType.getRawType()))) {
563- return (TypeCodec<T>)new UDTCodec((UserType)cqlType);
576+ return (TypeCodec<T>)TypeCodec.userType((UserType)cqlType);
577+ }
578+
579+ if(cqlType instanceof DataType.CustomType && (javaType == null || ByteBuffer.class.isAssignableFrom(javaType.getRawType()))) {
580+ return (TypeCodec<T>)TypeCodec.custom((DataType.CustomType)cqlType);
564581 }
565582
566583 return null;
567584 }
568585
586+ @SuppressWarnings("unchecked")
569587 private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, T value) {
570588 checkNotNull(value);
571589
572- if ((cqlType == null || cqlType.getName() == VARCHAR || cqlType.getName() == TEXT) && value instanceof Enum) {
573- return new EnumStringCodec(value.getClass());
574- }
575-
576590 if ((cqlType == null || cqlType.getName() == LIST) && value instanceof List) {
577591 List list = (List)value;
578592 if (list.isEmpty()) {
579593 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
580594 ? DataType.blob()
581595 : cqlType.getTypeArguments().get(0);
582- return new ListCodec(findCodec(elementType, (TypeToken)null));
596+ return TypeCodec.list(findCodec(elementType, (TypeToken)null));
583597 } else {
584598 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
585599 ? null
586600 : cqlType.getTypeArguments().get(0);
587- return new ListCodec(findCodec(elementType, list.iterator().next()));
601+ return (TypeCodec<T>)TypeCodec.list(findCodec(elementType, list.iterator().next()));
588602 }
589603 }
590604
@@ -594,12 +608,12 @@
594608 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
595609 ? DataType.blob()
596610 : cqlType.getTypeArguments().get(0);
597- return new SetCodec(findCodec(elementType, (TypeToken)null));
611+ return TypeCodec.set(findCodec(elementType, (TypeToken)null));
598612 } else {
599613 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
600614 ? null
601615 : cqlType.getTypeArguments().get(0);
602- return new SetCodec(findCodec(elementType, set.iterator().next()));
616+ return (TypeCodec<T>)TypeCodec.set(findCodec(elementType, set.iterator().next()));
603617 }
604618 }
605619
@@ -612,7 +626,7 @@
612626 DataType valueType = (cqlType == null || cqlType.getTypeArguments().size() < 2)
613627 ? DataType.blob() :
614628 cqlType.getTypeArguments().get(1);
615- return new MapCodec(
629+ return TypeCodec.map(
616630 findCodec(keyType, (TypeToken)null),
617631 findCodec(valueType, (TypeToken)null));
618632 } else {
@@ -623,24 +637,28 @@
623637 ? null
624638 : cqlType.getTypeArguments().get(1);
625639 Map.Entry entry = (Map.Entry)map.entrySet().iterator().next();
626- return new MapCodec(
640+ return (TypeCodec<T>)TypeCodec.map(
627641 findCodec(keyType, entry.getKey()),
628642 findCodec(valueType, entry.getValue()));
629643 }
630644 }
631645
632646 if ((cqlType == null || cqlType.getName() == DataType.Name.TUPLE) && value instanceof TupleValue) {
633- return (TypeCodec<T>)new TupleCodec(cqlType == null ? ((TupleValue)value).getType() : (TupleType) cqlType);
647+ return (TypeCodec<T>)TypeCodec.tuple(cqlType == null ? ((TupleValue)value).getType() : (TupleType)cqlType);
634648 }
635649
636650 if ((cqlType == null || cqlType.getName() == DataType.Name.UDT) && value instanceof UDTValue) {
637- return (TypeCodec<T>)new UDTCodec(cqlType == null ? ((UDTValue)value).getType() : (UserType) cqlType);
651+ return (TypeCodec<T>)TypeCodec.userType(cqlType == null ? ((UDTValue)value).getType() : (UserType)cqlType);
652+ }
653+
654+ if((cqlType != null && cqlType instanceof DataType.CustomType) && value instanceof ByteBuffer) {
655+ return (TypeCodec<T>)TypeCodec.custom((DataType.CustomType)cqlType);
638656 }
639657
640658 return null;
641659 }
642660
643- private static CodecNotFoundException newException(DataType cqlType, TypeToken<?> javaType) {
661+ private static CodecNotFoundException notFound(DataType cqlType, TypeToken<?> javaType) {
644662 String msg = String.format("Codec not found for requested operation: [%s <-> %s]",
645663 cqlType == null ? "ANY" : cqlType,
646664 javaType == null ? "ANY" : javaType);
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +1 −1
@@ -32,7 +32,7 @@
3232 import com.datastax.driver.core.exceptions.DriverInternalError;
3333 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3434
35-import static com.datastax.driver.core.SchemaElement.KEYSPACE;
35+import static com.datastax.driver.core.SchemaElement.*;
3636
3737 class ControlConnection implements Connection.Owner {
3838
modified driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java +1 −1
@@ -29,7 +29,7 @@
2929
3030 private static final Logger logger = LoggerFactory.getLogger(SchemaParser.class);
3131
32- private static final TypeCodec.ListCodec<String> LIST_OF_TEXT_CODEC = new TypeCodec.ListCodec<String>(TypeCodec.VarcharCodec.instance);
32+ private static final TypeCodec<List<String>> LIST_OF_TEXT_CODEC = TypeCodec.list(TypeCodec.varchar());
3333
3434 private static final SchemaParser V2_PARSER = new V2SchemaParser();
3535 private static final SchemaParser V3_PARSER = new V3SchemaParser();
modified driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java +0 −33
@@ -519,39 +519,11 @@
519519 */
520520 public T setToNull(int i);
521521
522- /**
523- * Sets the {@code i}th value to the provided value.
524- * <p>
525- * Note about performance: this method must perform a runtime inspection of the provided object,
526- * in order to guess the best codec to serialize it.
527- * The result of such inspection cannot be cached and thus must be performed for each invocation
528- * of this method, which may incur in a performance penalty.
529- * <p>
530- * Furthermore, if two or more codecs are available
531- * for the underlying CQL type, <em>which one will be used will depend
532- * on the actual object being serialized</em>.
533- * <p>
534- * For these reasons, it is generally preferable to use the more
535- * deterministic methods {@link #set(int, V, Class)}
536- * or {@link #set(int, V, TypeToken)} instead.
537- *
538- * @param i the index of the value to set.
539- * @param v the value to set; may be {@code null}.
540- * @return this object.
541- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
542- */
543- <V> T setObject(int i, V v);
544-
545522 /**
546523 * Sets the {@code i}th value to the provided value of the provided Java class.
547524 * <p>
548525 * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
549526 * have been previously registered with the {@link CodecRegistry} currently in use.
550- * <p>
551- * This method should be used instead of {@link #setObject(int, Object)} in cases
552- * where more than one codec is registered for the same CQL type; specifying the Java class
553- * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
554- * thus avoiding any risk of ambiguity.
555527 *
556528 * @param i the index of the value to set.
557529 * @param v the value to set; may be {@code null}.
@@ -566,11 +538,6 @@
566538 * <p>
567539 * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
568540 * have been previously registered with the {@link CodecRegistry} currently in use.
569- * <p>
570- * This method should be used instead of {@link #setObject(int, Object)} in cases
571- * where more than one codec is registered for the same CQL type; specifying the Java class
572- * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
573- * thus avoiding any risk of ambiguity.
574541 *
575542 * @param i the index of the value to set.
576543 * @param v the value to set; may be {@code null}.
modified driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java +0 −33
@@ -581,39 +581,11 @@
581581 */
582582 public T setToNull(String name);
583583
584- /**
585- * Sets the value for (all occurrences of) variable {@code name} to the provided value.
586- * <p>
587- * Note about performance: this method must perform a runtime inspection of the provided object,
588- * in order to guess the best codec to serialize it.
589- * The result of such inspection cannot be cached and thus must be performed for each invocation
590- * of this method, which may incur in a performance penalty.
591- * <p>
592- * Furthermore, if two or more codecs are available
593- * for the underlying CQL type, <em>which one will be used will depend
594- * on the actual object being serialized</em>.
595- * <p>
596- * For these reasons, it is generally preferable to use the more
597- * deterministic methods {@link #set(String, V, Class)} or {@link #set(String, V, TypeToken)} instead.
598- *
599- * @param name the name of the value to set; if {@code name} is present multiple
600- * times, all its values are set.
601- * @param v the value to set; may be {@code null}.
602- * @return this object.
603- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
604- */
605- <V> T setObject(String name, V v);
606-
607584 /**
608585 * Sets the value for (all occurrences of) variable {@code name} to the provided value of the provided Java class.
609586 * <p>
610587 * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
611588 * have been previously registered with the {@link CodecRegistry} currently in use.
612- * <p>
613- * This method should be used instead of {@link #setObject(String, Object)} in cases
614- * where more than one codec is registered for the same CQL type; specifying the Java class
615- * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
616- * thus avoiding any risk of ambiguity.
617589 *
618590 * @param name the name of the value to set; if {@code name} is present multiple
619591 * times, all its values are set.
@@ -629,11 +601,6 @@
629601 * <p>
630602 * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
631603 * have been previously registered with the {@link CodecRegistry} currently in use.
632- * <p>
633- * This method should be used instead of {@link #setObject(String, Object)} in cases
634- * where more than one codec is registered for the same CQL type; specifying the Java class
635- * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
636- * thus avoiding any risk of ambiguity.
637604 *
638605 * @param name the name of the value to set; if {@code name} is present multiple
639606 * times, all its values are set.
modified driver-core/src/main/java/com/datastax/driver/core/Token.java +5 −5
@@ -223,7 +223,7 @@
223223
224224 @Override
225225 Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion) {
226- return new M3PToken(TypeCodec.BigintCodec.instance.deserialize(buffer, protocolVersion));
226+ return new M3PToken(TypeCodec.bigint().deserialize(buffer, protocolVersion));
227227 }
228228
229229 @Override
@@ -276,7 +276,7 @@
276276
277277 @Override
278278 public ByteBuffer serialize(ProtocolVersion protocolVersion) {
279- return TypeCodec.BigintCodec.instance.serialize(value, protocolVersion);
279+ return TypeCodec.bigint().serialize(value, protocolVersion);
280280 }
281281
282282 @Override
@@ -483,7 +483,7 @@
483483
484484 @Override
485485 public ByteBuffer serialize(ProtocolVersion protocolVersion) {
486- return TypeCodec.BlobCodec.instance.serialize(value, protocolVersion);
486+ return TypeCodec.blob().serialize(value, protocolVersion);
487487 }
488488
489489 @Override
@@ -552,7 +552,7 @@
552552
553553 @Override
554554 Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion) {
555- return new RPToken(TypeCodec.VarintCodec.instance.deserialize(buffer, protocolVersion));
555+ return new RPToken(TypeCodec.varint().deserialize(buffer, protocolVersion));
556556 }
557557
558558 @Override
@@ -604,7 +604,7 @@
604604
605605 @Override
606606 public ByteBuffer serialize(ProtocolVersion protocolVersion) {
607- return TypeCodec.VarintCodec.instance.serialize(value, protocolVersion);
607+ return TypeCodec.varint().serialize(value, protocolVersion);
608608 }
609609
610610 @Override
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +538 −477
@@ -29,7 +29,6 @@
2929 import java.util.concurrent.TimeUnit;
3030 import java.util.regex.Pattern;
3131
32-import com.google.common.base.Objects;
3332 import com.google.common.collect.ImmutableMap;
3433 import com.google.common.reflect.TypeToken;
3534
@@ -53,9 +52,9 @@
5352 * Two methods handle the serialization and deserialization of Java types into
5453 * CQL types according to the native protocol specifications:
5554 * <ol>
56- * <li>{@link #serialize(Object,ProtocolVersion)}: used to serialize from the codec's Java type to a
55+ * <li>{@link #serialize(Object, ProtocolVersion)}: used to serialize from the codec's Java type to a
5756 * {@link ByteBuffer} instance corresponding to the codec's CQL type;</li>
58- * <li>{@link #deserialize(ByteBuffer,ProtocolVersion)}: used to deserialize a {@link ByteBuffer} instance
57+ * <li>{@link #deserialize(ByteBuffer, ProtocolVersion)}: used to deserialize a {@link ByteBuffer} instance
5958 * corresponding to the codec's CQL type to the codec's Java type.</li>
6059 * </ol>
6160 *
@@ -99,11 +98,12 @@
9998 * <li>TypeCodec implementations that wish to handle Java primitive types <em>must</em> be instantiated with
10099 * the wrapper Java class instead, and implement the appropriate interface (see {@link BooleanCodec}
101100 * for an example).</li>
101+ * <li>TypeCodec implementations should not consume {@link ByteBuffer} instances by performing read operations
102+ * that modify their current position; if necessary, codecs should {@link ByteBuffer#duplicate()} duplicate} them.</li>
102103 * </ol>
103104 *
104105 * @param <T> The codec's Java type
105106 */
106-@SuppressWarnings("all")
107107 public abstract class TypeCodec<T> {
108108
109109 private static final Map<TypeToken<?>, TypeToken<?>> primitiveToWrapperMap = ImmutableMap.<TypeToken<?>, TypeToken<?>>builder()
@@ -118,9 +118,272 @@
118118 .build();
119119
120120 /**
121- * The CQL keyword {@code NULL}.
122- */
123- private static final String NULL = "NULL";
121+ * Return the default codec for the CQL type {@code boolean}.
122+ * The returned codec maps the CQL type {@code boolean} into the Java type {@link Boolean}.
123+ * The returned instance is a singleton.
124+ * @return the default codec for CQL type {@code boolean}.
125+ **/
126+ public static PrimitiveBooleanCodec cboolean() {
127+ return BooleanCodec.instance;
128+ }
129+
130+ /**
131+ * Return the default codec for the CQL type {@code tinyint}.
132+ * The returned codec maps the CQL type {@code tinyint} into the Java type {@link Byte}.
133+ * The returned instance is a singleton.
134+ * @return the default codec for CQL type {@code tinyint}.
135+ **/
136+ public static PrimitiveByteCodec tinyInt() {
137+ return TinyIntCodec.instance;
138+ }
139+
140+ /**
141+ * Return the default codec for the CQL type {@code smallint}.
142+ * The returned codec maps the CQL type {@code smallint} into the Java type {@link Short}.
143+ * The returned instance is a singleton.
144+ * @return the default codec for CQL type {@code smallint}.
145+ **/
146+ public static PrimitiveShortCodec smallInt() {
147+ return SmallIntCodec.instance;
148+ }
149+
150+ /**
151+ * Return the default codec for the CQL type {@code int}.
152+ * The returned codec maps the CQL type {@code int} into the Java type {@link Integer}.
153+ * The returned instance is a singleton.
154+ * @return the default codec for CQL type {@code int}.
155+ **/
156+ public static PrimitiveIntCodec cint() {
157+ return IntCodec.instance;
158+ }
159+
160+ /**
161+ * Return the default codec for the CQL type {@code bigint}.
162+ * The returned codec maps the CQL type {@code bigint} into the Java type {@link Long}.
163+ * The returned instance is a singleton.
164+ * @return the default codec for CQL type {@code bigint}.
165+ **/
166+ public static PrimitiveLongCodec bigint() {
167+ return BigintCodec.instance;
168+ }
169+
170+ /**
171+ * Return the default codec for the CQL type {@code counter}.
172+ * The returned codec maps the CQL type {@code counter} into the Java type {@link Long}.
173+ * The returned instance is a singleton.
174+ * @return the default codec for CQL type {@code counter}.
175+ **/
176+ public static PrimitiveLongCodec counter() {
177+ return CounterCodec.instance;
178+ }
179+
180+ /**
181+ * Return the default codec for the CQL type {@code float}.
182+ * The returned codec maps the CQL type {@code float} into the Java type {@link Float}.
183+ * The returned instance is a singleton.
184+ * @return the default codec for CQL type {@code float}.
185+ **/
186+ public static PrimitiveFloatCodec cfloat() {
187+ return FloatCodec.instance;
188+ }
189+
190+ /**
191+ * Return the default codec for the CQL type {@code double}.
192+ * The returned codec maps the CQL type {@code double} into the Java type {@link Double}.
193+ * The returned instance is a singleton.
194+ * @return the default codec for CQL type {@code double}.
195+ **/
196+ public static PrimitiveDoubleCodec cdouble() {
197+ return DoubleCodec.instance;
198+ }
199+
200+ /**
201+ * Return the default codec for the CQL type {@code varint}.
202+ * The returned codec maps the CQL type {@code varint} into the Java type {@link BigInteger}.
203+ * The returned instance is a singleton.
204+ * @return the default codec for CQL type {@code varint}.
205+ **/
206+ public static TypeCodec<BigInteger> varint() {
207+ return VarintCodec.instance;
208+ }
209+
210+ /**
211+ * Return the default codec for the CQL type {@code decimal}.
212+ * The returned codec maps the CQL type {@code decimal} into the Java type {@link BigDecimal}.
213+ * The returned instance is a singleton.
214+ * @return the default codec for CQL type {@code decimal}.
215+ **/
216+ public static TypeCodec<BigDecimal> decimal() {
217+ return DecimalCodec.instance;
218+ }
219+
220+ /**
221+ * Return the default codec for the CQL type {@code ascii}.
222+ * The returned codec maps the CQL type {@code ascii} into the Java type {@link String}.
223+ * The returned instance is a singleton.
224+ * @return the default codec for CQL type {@code ascii}.
225+ **/
226+ public static TypeCodec<String> ascii() {
227+ return AsciiCodec.instance;
228+ }
229+
230+ /**
231+ * Return the default codec for the CQL type {@code varchar}.
232+ * The returned codec maps the CQL type {@code varchar} into the Java type {@link String}.
233+ * The returned instance is a singleton.
234+ * @return the default codec for CQL type {@code varchar}.
235+ **/
236+ public static TypeCodec<String> varchar() {
237+ return VarcharCodec.instance;
238+ }
239+
240+ /**
241+ * Return the default codec for the CQL type {@code blob}.
242+ * The returned codec maps the CQL type {@code blob} into the Java type {@link ByteBuffer}.
243+ * The returned instance is a singleton.
244+ * @return the default codec for CQL type {@code blob}.
245+ **/
246+ public static TypeCodec<ByteBuffer> blob() {
247+ return BlobCodec.instance;
248+ }
249+
250+ /**
251+ * Return the default codec for the CQL type {@code date}.
252+ * The returned codec maps the CQL type {@code date} into the Java type {@link LocalDate}.
253+ * The returned instance is a singleton.
254+ * @return the default codec for CQL type {@code date}.
255+ **/
256+ public static TypeCodec<LocalDate> date() {
257+ return DateCodec.instance;
258+ }
259+
260+ /**
261+ * Return the default codec for the CQL type {@code time}.
262+ * The returned codec maps the CQL type {@code time} into the Java type {@link Long}.
263+ * The returned instance is a singleton.
264+ * @return the default codec for CQL type {@code time}.
265+ **/
266+ public static TypeCodec<Long> time() {
267+ return TimeCodec.instance;
268+ }
269+
270+ /**
271+ * Return the default codec for the CQL type {@code timestamp}.
272+ * The returned codec maps the CQL type {@code timestamp} into the Java type {@link Date}.
273+ * The returned instance is a singleton.
274+ * @return the default codec for CQL type {@code timestamp}.
275+ **/
276+ public static TypeCodec<Date> timestamp() {
277+ return TimestampCodec.instance;
278+ }
279+
280+ /**
281+ * Return the default codec for the CQL type {@code uuid}.
282+ * The returned codec maps the CQL type {@code uuid} into the Java type {@link UUID}.
283+ * The returned instance is a singleton.
284+ * @return the default codec for CQL type {@code uuid}.
285+ **/
286+ public static TypeCodec<UUID> uuid() {
287+ return UUIDCodec.instance;
288+ }
289+
290+ /**
291+ * Return the default codec for the CQL type {@code timeuuid}.
292+ * The returned codec maps the CQL type {@code timeuuid} into the Java type {@link UUID}.
293+ * The returned instance is a singleton.
294+ * @return the default codec for CQL type {@code timeuuid}.
295+ **/
296+ public static TypeCodec<UUID> timeUUID() {
297+ return TimeUUIDCodec.instance;
298+ }
299+
300+ /**
301+ * Return the default codec for the CQL type {@code inet}.
302+ * The returned codec maps the CQL type {@code inet} into the Java type {@link InetAddress}.
303+ * The returned instance is a singleton.
304+ * @return the default codec for CQL type {@code inet}.
305+ **/
306+ public static TypeCodec<InetAddress> inet() {
307+ return InetCodec.instance;
308+ }
309+
310+ /**
311+ * Return a newly-created codec for the CQL type {@code list} whose element type
312+ * is determined by the given element codec.
313+ * The returned codec maps the CQL type {@code list} into the Java type {@link List}.
314+ * This method does not cache returned instances and returns a newly-allocated object
315+ * at each invocation.
316+ * @param elementCodec the codec that will handle elements of this list.
317+ * @return A newly-created codec for CQL type {@code list}.
318+ **/
319+ public static <T> TypeCodec<List<T>> list(TypeCodec<T> elementCodec) {
320+ return new ListCodec<T>(elementCodec);
321+ }
322+
323+ /**
324+ * Return a newly-created codec for the CQL type {@code set} whose element type
325+ * is determined by the given element codec.
326+ * The returned codec maps the CQL type {@code set} into the Java type {@link Set}.
327+ * This method does not cache returned instances and returns a newly-allocated object
328+ * at each invocation.
329+ * @param elementCodec the codec that will handle elements of this set.
330+ * @return A newly-created codec for CQL type {@code set}.
331+ **/
332+ public static <T> TypeCodec<Set<T>> set(TypeCodec<T> elementCodec) {
333+ return new SetCodec<T>(elementCodec);
334+ }
335+
336+ /**
337+ * Return a newly-created codec for the CQL type {@code map} whose key type
338+ * and value type are determined by the given codecs.
339+ * The returned codec maps the CQL type {@code map} into the Java type {@link Map}.
340+ * This method does not cache returned instances and returns a newly-allocated object
341+ * at each invocation.
342+ * @param keyCodec the codec that will handle keys of this map.
343+ * @param valueCodec the codec that will handle values of this map.
344+ * @return A newly-created codec for CQL type {@code map}.
345+ **/
346+ public static <K, V> TypeCodec<Map<K, V>> map(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec) {
347+ return new MapCodec<K, V>(keyCodec, valueCodec);
348+ }
349+
350+ /**
351+ * Return a newly-created codec for the given user-defined CQL type.
352+ * The returned codec maps the user-defined type into the Java type {@link UDTValue}.
353+ * This method does not cache returned instances and returns a newly-allocated object
354+ * at each invocation.
355+ * @param type the user-defined type this codec should handle.
356+ * @return A newly-created codec for the given user-defined CQL type.
357+ **/
358+ public static TypeCodec<UDTValue> userType(UserType type) {
359+ return new UDTCodec(type);
360+ }
361+
362+ /**
363+ * Return a newly-created codec for the given CQL tuple type.
364+ * The returned codec maps the tuple type into the Java type {@link TupleValue}.
365+ * This method does not cache returned instances and returns a newly-allocated object
366+ * at each invocation.
367+ * @param type the tuple type this codec should handle.
368+ * @return A newly-created codec for the given CQL tuple type.
369+ **/
370+ public static TypeCodec<TupleValue> tuple(TupleType type) {
371+ return new TupleCodec(type);
372+ }
373+
374+ /**
375+ * Return a newly-created codec for the given CQL custom type.
376+ * The returned codec maps the custom type into the Java type {@link ByteBuffer}.
377+ * This method provides a (very lightweight) support for Cassandra
378+ * types that do not have a CQL equivalent.
379+ * This method does not cache returned instances and returns a newly-allocated object
380+ * at each invocation.
381+ * @param type the custom type this codec should handle.
382+ * @return A newly-created codec for the given CQL custom type.
383+ **/
384+ public static TypeCodec<ByteBuffer> custom(CustomType type) {
385+ return new CustomCodec(type);
386+ }
124387
125388 protected final TypeToken<T> javaType;
126389
@@ -196,6 +459,9 @@
196459 * (note that the driver's default collection codecs return <em>mutable</em> collections);</li>
197460 * <li>Codecs for CQL collection types should avoid returning {@code null};
198461 * they should return empty collections instead (the driver's default collection codecs all comply with this rule).</li>
462+ * <li>The provided {@link ByteBuffer} should never be consumed by read operations that
463+ * modify its current position; if necessary,
464+ * {@link ByteBuffer#duplicate()} duplicate} it before consuming.</li>
199465 * </ol>
200466 *
201467 * @param bytes A {@link ByteBuffer} instance containing the serialized form of T;
@@ -249,7 +515,7 @@
249515 */
250516 public boolean accepts(TypeToken javaType) {
251517 checkNotNull(javaType);
252- if(javaType.isPrimitive()) {
518+ if (javaType.isPrimitive()) {
253519 javaType = primitiveToWrapperMap.get(javaType);
254520 }
255521 // TODO accept generics type covariance, i.e. a codec for List<Number> should accept List<Integer>
@@ -302,119 +568,203 @@
302568 return accepts(TypeToken.of(value.getClass()));
303569 }
304570
305- @Override
306- public boolean equals(Object o) {
307- if (this == o)
308- return true;
309- if (!(o instanceof TypeCodec))
310- return false;
311- TypeCodec<?> typeCodec = (TypeCodec<?>)o;
312- return Objects.equal(javaType, typeCodec.javaType) && Objects.equal(cqlType, typeCodec.cqlType);
313- }
314-
315- @Override
316- public int hashCode() {
317- return Objects.hashCode(javaType, cqlType);
318- }
319-
320571 @Override
321572 public String toString() {
322573 return String.format("%s [%s <-> %s]", this.getClass().getSimpleName(), cqlType, javaType);
323574 }
324575
325576 /**
326- * An interface for codecs that are capable of handling primitive booleans,
577+ * A codec that is capable of handling primitive booleans,
327578 * thus avoiding the overhead of boxing and unboxing such primitives.
328579 */
329- public interface PrimitiveBooleanCodec {
580+ public static abstract class PrimitiveBooleanCodec extends TypeCodec<Boolean> {
581+
582+ protected PrimitiveBooleanCodec(DataType cqlType) {
583+ super(cqlType, Boolean.class);
584+ }
585+
586+ public abstract ByteBuffer serializeNoBoxing(boolean v, ProtocolVersion protocolVersion);
587+
588+ public abstract boolean deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
330589
331- ByteBuffer serializeNoBoxing(boolean v, ProtocolVersion protocolVersion);
332- boolean deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
590+ @Override
591+ public ByteBuffer serialize(Boolean value, ProtocolVersion protocolVersion) {
592+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
593+ }
333594
595+ @Override
596+ public Boolean deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
597+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
598+ }
334599 }
335600
336601 /**
337- * An interface for codecs that are capable of handling primitive bytes,
602+ * A codec that is capable of handling primitive bytes,
338603 * thus avoiding the overhead of boxing and unboxing such primitives.
339604 */
340- public interface PrimitiveByteCodec {
605+ public static abstract class PrimitiveByteCodec extends TypeCodec<Byte> {
341606
342- ByteBuffer serializeNoBoxing(byte v, ProtocolVersion protocolVersion);
343- byte deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
607+ protected PrimitiveByteCodec(DataType cqlType) {
608+ super(cqlType, Byte.class);
609+ }
610+
611+ public abstract ByteBuffer serializeNoBoxing(byte v, ProtocolVersion protocolVersion);
612+
613+ public abstract byte deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
614+
615+ @Override
616+ public ByteBuffer serialize(Byte value, ProtocolVersion protocolVersion) {
617+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
618+ }
344619
620+ @Override
621+ public Byte deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
622+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
623+ }
345624 }
346625
347626 /**
348- * An interface for codecs that are capable of handling primitive shorts,
627+ * A codec that is capable of handling primitive shorts,
349628 * thus avoiding the overhead of boxing and unboxing such primitives.
350629 */
351- public interface PrimitiveShortCodec {
630+ public static abstract class PrimitiveShortCodec extends TypeCodec<Short>{
631+
632+ protected PrimitiveShortCodec(DataType cqlType) {
633+ super(cqlType, Short.class);
634+ }
352635
353- ByteBuffer serializeNoBoxing(short v, ProtocolVersion protocolVersion);
354- short deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
636+ public abstract ByteBuffer serializeNoBoxing(short v, ProtocolVersion protocolVersion);
637+
638+ public abstract short deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
639+
640+ @Override
641+ public ByteBuffer serialize(Short value, ProtocolVersion protocolVersion) {
642+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
643+ }
355644
645+ @Override
646+ public Short deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
647+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
648+ }
356649 }
357650
358651 /**
359- * An interface for codecs that are capable of handling primitive ints,
652+ * A codec that is capable of handling primitive ints,
360653 * thus avoiding the overhead of boxing and unboxing such primitives.
361654 */
362- public interface PrimitiveIntCodec {
655+ public static abstract class PrimitiveIntCodec extends TypeCodec<Integer> {
656+
657+ protected PrimitiveIntCodec(DataType cqlType) {
658+ super(cqlType, Integer.class);
659+ }
660+
661+ public abstract ByteBuffer serializeNoBoxing(int v, ProtocolVersion protocolVersion);
662+
663+ public abstract int deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
363664
364- ByteBuffer serializeNoBoxing(int v, ProtocolVersion protocolVersion);
365- int deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
665+ @Override
666+ public ByteBuffer serialize(Integer value, ProtocolVersion protocolVersion) {
667+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
668+ }
366669
670+ @Override
671+ public Integer deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
672+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
673+ }
367674 }
368675
369676 /**
370- * An interface for codecs that are capable of handling primitive longs,
677+ * A codec that is capable of handling primitive longs,
371678 * thus avoiding the overhead of boxing and unboxing such primitives.
372679 */
373- public interface PrimitiveLongCodec {
680+ public static abstract class PrimitiveLongCodec extends TypeCodec<Long> {
681+
682+ protected PrimitiveLongCodec(DataType cqlType) {
683+ super(cqlType, Long.class);
684+ }
374685
375- ByteBuffer serializeNoBoxing(long v, ProtocolVersion protocolVersion);
376- long deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
686+ public abstract ByteBuffer serializeNoBoxing(long v, ProtocolVersion protocolVersion);
377687
688+ public abstract long deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
689+
690+ @Override
691+ public ByteBuffer serialize(Long value, ProtocolVersion protocolVersion) {
692+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
693+ }
694+
695+ @Override
696+ public Long deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
697+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
698+ }
378699 }
379700
380701 /**
381- * An interface for codecs that are capable of handling primitive floats,
702+ * A codec that is capable of handling primitive floats,
382703 * thus avoiding the overhead of boxing and unboxing such primitives.
383704 */
384- public interface PrimitiveFloatCodec {
705+ public static abstract class PrimitiveFloatCodec extends TypeCodec<Float> {
706+
707+ protected PrimitiveFloatCodec(DataType cqlType) {
708+ super(cqlType, Float.class);
709+ }
710+
711+ public abstract ByteBuffer serializeNoBoxing(float v, ProtocolVersion protocolVersion);
385712
386- ByteBuffer serializeNoBoxing(float v, ProtocolVersion protocolVersion);
387- float deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
713+ public abstract float deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
714+
715+ @Override
716+ public ByteBuffer serialize(Float value, ProtocolVersion protocolVersion) {
717+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
718+ }
388719
720+ @Override
721+ public Float deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
722+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
723+ }
389724 }
390725
391726 /**
392- * An interface for codecs that are capable of handling primitive doubles,
727+ * A codec that is capable of handling primitive doubles,
393728 * thus avoiding the overhead of boxing and unboxing such primitives.
394729 */
395- public interface PrimitiveDoubleCodec {
730+ public static abstract class PrimitiveDoubleCodec extends TypeCodec<Double> {
396731
397- ByteBuffer serializeNoBoxing(double v, ProtocolVersion protocolVersion);
398- double deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
732+ protected PrimitiveDoubleCodec(DataType cqlType) {
733+ super(cqlType, Double.class);
734+ }
735+
736+ public abstract ByteBuffer serializeNoBoxing(double v, ProtocolVersion protocolVersion);
737+
738+ public abstract double deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
739+
740+ @Override
741+ public ByteBuffer serialize(Double value, ProtocolVersion protocolVersion) {
742+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
743+ }
399744
745+ @Override
746+ public Double deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
747+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
748+ }
400749 }
401750
402751 /**
403752 * Base class for codecs handling CQL string types such as {@link DataType#varchar()},
404753 * {@link DataType#text()} or {@link DataType#ascii()}.
405754 */
406- public static abstract class StringCodec extends TypeCodec<String> {
755+ private static abstract class StringCodec extends TypeCodec<String> {
407756
408757 private final Charset charset;
409758
410- public StringCodec(DataType cqlType, Charset charset) {
759+ private StringCodec(DataType cqlType, Charset charset) {
411760 super(cqlType, String.class);
412761 this.charset = charset;
413762 }
414763
415764 @Override
416765 public String parse(String value) {
417- if (value == null || value.isEmpty() || value.equals(NULL)) return null;
766+ if (value == null || value.isEmpty() || value.equals("NULL"))
767+ return null;
418768 if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
419769 throw new InvalidTypeException("text or varchar values must be enclosed by single quotes");
420770
@@ -424,13 +774,13 @@
424774 @Override
425775 public String format(String value) {
426776 if (value == null)
427- return NULL;
777+ return "NULL";
428778 return '\'' + replace(value, '\'', "''") + '\'';
429779 }
430780
431781 // Simple method to replace a single character. String.replace is a bit too
432782 // inefficient (see JAVA-67)
433- static String replace(String text, char search, String replacement) {
783+ private static String replace(String text, char search, String replacement) {
434784 if (text == null || text.isEmpty())
435785 return text;
436786
@@ -475,7 +825,7 @@
475825 public String deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
476826 if (bytes == null)
477827 return null;
478- if(bytes.remaining() == 0)
828+ if (bytes.remaining() == 0)
479829 return "";
480830 return new String(Bytes.getArray(bytes), charset);
481831 }
@@ -486,12 +836,12 @@
486836 * Note that this codec also handles {@link DataType#text()}, which is merely
487837 * an alias for {@link DataType#varchar()}.
488838 */
489- public static class VarcharCodec extends StringCodec {
839+ private static class VarcharCodec extends StringCodec {
490840
491- public static final VarcharCodec instance = new VarcharCodec();
841+ private static final VarcharCodec instance = new VarcharCodec();
492842
493843 private VarcharCodec() {
494- super(varchar(), Charset.forName("UTF-8"));
844+ super(DataType.varchar(), Charset.forName("UTF-8"));
495845 }
496846
497847 }
@@ -499,22 +849,19 @@
499849 /**
500850 * This codec maps a CQL {@link DataType#ascii()} to a Java {@link String}.
501851 */
502- public static class AsciiCodec extends StringCodec {
852+ private static class AsciiCodec extends StringCodec {
503853
504- public static final AsciiCodec instance = new AsciiCodec();
854+ private static final AsciiCodec instance = new AsciiCodec();
505855
506856 private static final Pattern ASCII_PATTERN = Pattern.compile("^\\p{ASCII}*$");
507857
508858 private AsciiCodec() {
509- super(ascii(), Charset.forName("US-ASCII"));
859+ super(DataType.ascii(), Charset.forName("US-ASCII"));
510860 }
511861
512862 @Override
513863 public boolean accepts(Object value) {
514- if (value instanceof String) {
515- return ASCII_PATTERN.matcher((String)value).matches();
516- }
517- return false;
864+ return value instanceof String && ASCII_PATTERN.matcher((String)value).matches();
518865 }
519866
520867 }
@@ -523,16 +870,16 @@
523870 * Base class for codecs handling CQL 8-byte integer types such as {@link DataType#bigint()},
524871 * {@link DataType#counter()} or {@link DataType#time()}.
525872 */
526- public abstract static class LongCodec extends TypeCodec<Long> implements PrimitiveLongCodec {
873+ private abstract static class LongCodec extends PrimitiveLongCodec {
527874
528- public LongCodec(DataType cqlType) {
529- super(cqlType, Long.class);
875+ private LongCodec(DataType cqlType) {
876+ super(cqlType);
530877 }
531878
532879 @Override
533880 public Long parse(String value) {
534881 try {
535- return value == null || value.isEmpty() || value.equals(NULL) ? null : Long.parseLong(value);
882+ return value == null || value.isEmpty() || value.equals("NULL") ? null : Long.parseLong(value);
536883 } catch (NumberFormatException e) {
537884 throw new InvalidTypeException(String.format("Cannot parse 64-bits long value from \"%s\"", value));
538885 }
@@ -541,15 +888,10 @@
541888 @Override
542889 public String format(Long value) {
543890 if (value == null)
544- return NULL;
891+ return "NULL";
545892 return Long.toString(value);
546893 }
547894
548- @Override
549- public ByteBuffer serialize(Long value, ProtocolVersion protocolVersion) {
550- return value == null ? null : serializeNoBoxing(value, protocolVersion);
551- }
552-
553895 @Override
554896 public ByteBuffer serializeNoBoxing(long value, ProtocolVersion protocolVersion) {
555897 ByteBuffer bb = ByteBuffer.allocate(8);
@@ -557,11 +899,6 @@
557899 return bb;
558900 }
559901
560- @Override
561- public Long deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
562- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
563- }
564-
565902 @Override
566903 public long deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
567904 if (bytes == null || bytes.remaining() == 0)
@@ -576,12 +913,12 @@
576913 /**
577914 * This codec maps a CQL {@link DataType#bigint()} to a Java {@link Long}.
578915 */
579- public static class BigintCodec extends LongCodec {
916+ private static class BigintCodec extends LongCodec {
580917
581- public static final BigintCodec instance = new BigintCodec();
918+ private static final BigintCodec instance = new BigintCodec();
582919
583920 private BigintCodec() {
584- super(bigint());
921+ super(DataType.bigint());
585922 }
586923
587924 }
@@ -589,12 +926,12 @@
589926 /**
590927 * This codec maps a CQL {@link DataType#counter()} to a Java {@link Long}.
591928 */
592- public static class CounterCodec extends LongCodec {
929+ private static class CounterCodec extends LongCodec {
593930
594- public static final CounterCodec instance = new CounterCodec();
931+ private static final CounterCodec instance = new CounterCodec();
595932
596933 private CounterCodec() {
597- super(counter());
934+ super(DataType.counter());
598935 }
599936
600937 }
@@ -602,23 +939,23 @@
602939 /**
603940 * This codec maps a CQL {@link DataType#blob()} to a Java {@link ByteBuffer}.
604941 */
605- public static class BlobCodec extends TypeCodec<ByteBuffer> {
942+ private static class BlobCodec extends TypeCodec<ByteBuffer> {
606943
607- public static final BlobCodec instance = new BlobCodec();
944+ private static final BlobCodec instance = new BlobCodec();
608945
609946 private BlobCodec() {
610- super(blob(), ByteBuffer.class);
947+ super(DataType.blob(), ByteBuffer.class);
611948 }
612949
613950 @Override
614951 public ByteBuffer parse(String value) {
615- return value == null || value.isEmpty() || value.equals(NULL) ? null : Bytes.fromHexString(value);
952+ return value == null || value.isEmpty() || value.equals("NULL") ? null : Bytes.fromHexString(value);
616953 }
617954
618955 @Override
619956 public String format(ByteBuffer value) {
620957 if (value == null)
621- return NULL;
958+ return "NULL";
622959 return Bytes.toHexString(value);
623960 }
624961
@@ -634,26 +971,26 @@
634971 }
635972
636973 /**
637- * This codec maps a CQL {@link DataType#custom(String)} to a Java {@link ByteBuffer}.
974+ * This codec maps a CQL {@link DataType#custom(String) custom} type to a Java {@link ByteBuffer}.
638975 * Note that no instance of this codec is part of the default set of codecs used by the Java driver;
639976 * instances of this codec must be manually registered.
640977 */
641- public static class CustomCodec extends TypeCodec<ByteBuffer> {
978+ private static class CustomCodec extends TypeCodec<ByteBuffer> {
642979
643- public CustomCodec(DataType custom) {
980+ private CustomCodec(DataType custom) {
644981 super(custom, ByteBuffer.class);
645982 assert custom.getName() == Name.CUSTOM;
646983 }
647984
648985 @Override
649986 public ByteBuffer parse(String value) {
650- return value == null || value.isEmpty() || value.equals(NULL) ? null : Bytes.fromHexString(value);
987+ return value == null || value.isEmpty() || value.equals("NULL") ? null : Bytes.fromHexString(value);
651988 }
652989
653990 @Override
654991 public String format(ByteBuffer value) {
655992 if (value == null)
656- return NULL;
993+ return "NULL";
657994 return Bytes.toHexString(value);
658995 }
659996
@@ -671,20 +1008,20 @@
6711008 /**
6721009 * This codec maps a CQL {@link DataType#cboolean()} to a Java {@link Boolean}.
6731010 */
674- public static class BooleanCodec extends TypeCodec<Boolean> implements PrimitiveBooleanCodec {
1011+ private static class BooleanCodec extends PrimitiveBooleanCodec {
6751012
6761013 private static final ByteBuffer TRUE = ByteBuffer.wrap(new byte[]{ 1 });
6771014 private static final ByteBuffer FALSE = ByteBuffer.wrap(new byte[]{ 0 });
6781015
679- public static final BooleanCodec instance = new BooleanCodec();
1016+ private static final BooleanCodec instance = new BooleanCodec();
6801017
6811018 private BooleanCodec() {
682- super(cboolean(), Boolean.class);
1019+ super(DataType.cboolean());
6831020 }
6841021
6851022 @Override
6861023 public Boolean parse(String value) {
687- if (value == null || value.isEmpty() || value.equals(NULL))
1024+ if (value == null || value.isEmpty() || value.equals("NULL"))
6881025 return null;
6891026 if (value.equalsIgnoreCase(Boolean.FALSE.toString()))
6901027 return false;
@@ -697,25 +1034,15 @@
6971034 @Override
6981035 public String format(Boolean value) {
6991036 if (value == null)
700- return NULL;
1037+ return "NULL";
7011038 return value ? "true" : "false";
7021039 }
7031040
704- @Override
705- public ByteBuffer serialize(Boolean value, ProtocolVersion protocolVersion) {
706- return value == null ? null : serializeNoBoxing(value, protocolVersion);
707- }
708-
7091041 @Override
7101042 public ByteBuffer serializeNoBoxing(boolean value, ProtocolVersion protocolVersion) {
7111043 return value ? TRUE.duplicate() : FALSE.duplicate();
7121044 }
7131045
714- @Override
715- public Boolean deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
716- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
717- }
718-
7191046 @Override
7201047 public boolean deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
7211048 if (bytes == null || bytes.remaining() == 0)
@@ -730,18 +1057,18 @@
7301057 /**
7311058 * This codec maps a CQL {@link DataType#decimal()} to a Java {@link BigDecimal}.
7321059 */
733- public static class DecimalCodec extends TypeCodec<BigDecimal> {
1060+ private static class DecimalCodec extends TypeCodec<BigDecimal> {
7341061
735- public static final DecimalCodec instance = new DecimalCodec();
1062+ private static final DecimalCodec instance = new DecimalCodec();
7361063
7371064 private DecimalCodec() {
738- super(decimal(), BigDecimal.class);
1065+ super(DataType.decimal(), BigDecimal.class);
7391066 }
7401067
7411068 @Override
7421069 public BigDecimal parse(String value) {
7431070 try {
744- return value == null || value.isEmpty() || value.equals(NULL) ? null : new BigDecimal(value);
1071+ return value == null || value.isEmpty() || value.equals("NULL") ? null : new BigDecimal(value);
7451072 } catch (NumberFormatException e) {
7461073 throw new InvalidTypeException(String.format("Cannot parse decimal value from \"%s\"", value));
7471074 }
@@ -750,7 +1077,7 @@
7501077 @Override
7511078 public String format(BigDecimal value) {
7521079 if (value == null)
753- return NULL;
1080+ return "NULL";
7541081 return value.toString();
7551082 }
7561083
@@ -789,18 +1116,18 @@
7891116 /**
7901117 * This codec maps a CQL {@link DataType#cdouble()} to a Java {@link Double}.
7911118 */
792- public static class DoubleCodec extends TypeCodec<Double> implements PrimitiveDoubleCodec {
1119+ private static class DoubleCodec extends PrimitiveDoubleCodec {
7931120
794- public static final DoubleCodec instance = new DoubleCodec();
1121+ private static final DoubleCodec instance = new DoubleCodec();
7951122
7961123 private DoubleCodec() {
797- super(cdouble(), Double.class);
1124+ super(DataType.cdouble());
7981125 }
7991126
8001127 @Override
8011128 public Double parse(String value) {
8021129 try {
803- return value == null || value.isEmpty() || value.equals(NULL) ? null : Double.parseDouble(value);
1130+ return value == null || value.isEmpty() || value.equals("NULL") ? null : Double.parseDouble(value);
8041131 } catch (NumberFormatException e) {
8051132 throw new InvalidTypeException(String.format("Cannot parse 64-bits double value from \"%s\"", value));
8061133 }
@@ -809,15 +1136,10 @@
8091136 @Override
8101137 public String format(Double value) {
8111138 if (value == null)
812- return NULL;
1139+ return "NULL";
8131140 return Double.toString(value);
8141141 }
8151142
816- @Override
817- public ByteBuffer serialize(Double value, ProtocolVersion protocolVersion) {
818- return value == null ? null : serializeNoBoxing(value, protocolVersion);
819- }
820-
8211143 @Override
8221144 public ByteBuffer serializeNoBoxing(double value, ProtocolVersion protocolVersion) {
8231145 ByteBuffer bb = ByteBuffer.allocate(8);
@@ -825,11 +1147,6 @@
8251147 return bb;
8261148 }
8271149
828- @Override
829- public Double deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
830- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
831- }
832-
8331150 @Override
8341151 public double deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
8351152 if (bytes == null || bytes.remaining() == 0)
@@ -844,18 +1161,18 @@
8441161 /**
8451162 * This codec maps a CQL {@link DataType#cfloat()} to a Java {@link Float}.
8461163 */
847- public static class FloatCodec extends TypeCodec<Float> implements PrimitiveFloatCodec {
1164+ private static class FloatCodec extends PrimitiveFloatCodec {
8481165
849- public static final FloatCodec instance = new FloatCodec();
1166+ private static final FloatCodec instance = new FloatCodec();
8501167
8511168 private FloatCodec() {
852- super(cfloat(), Float.class);
1169+ super(DataType.cfloat());
8531170 }
8541171
8551172 @Override
8561173 public Float parse(String value) {
8571174 try {
858- return value == null || value.isEmpty() || value.equals(NULL) ? null : Float.parseFloat(value);
1175+ return value == null || value.isEmpty() || value.equals("NULL") ? null : Float.parseFloat(value);
8591176 } catch (NumberFormatException e) {
8601177 throw new InvalidTypeException(String.format("Cannot parse 32-bits float value from \"%s\"", value));
8611178 }
@@ -864,15 +1181,10 @@
8641181 @Override
8651182 public String format(Float value) {
8661183 if (value == null)
867- return NULL;
1184+ return "NULL";
8681185 return Float.toString(value);
8691186 }
8701187
871- @Override
872- public ByteBuffer serialize(Float value, ProtocolVersion protocolVersion) {
873- return value == null ? null : serializeNoBoxing(value, protocolVersion);
874- }
875-
8761188 @Override
8771189 public ByteBuffer serializeNoBoxing(float value, ProtocolVersion protocolVersion) {
8781190 ByteBuffer bb = ByteBuffer.allocate(4);
@@ -880,11 +1192,6 @@
8801192 return bb;
8811193 }
8821194
883- @Override
884- public Float deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
885- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
886- }
887-
8881195 @Override
8891196 public float deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
8901197 if (bytes == null || bytes.remaining() == 0)
@@ -899,17 +1206,17 @@
8991206 /**
9001207 * This codec maps a CQL {@link DataType#inet()} to a Java {@link InetAddress}.
9011208 */
902- public static class InetCodec extends TypeCodec<InetAddress> {
1209+ private static class InetCodec extends TypeCodec<InetAddress> {
9031210
904- public static final InetCodec instance = new InetCodec();
1211+ private static final InetCodec instance = new InetCodec();
9051212
9061213 private InetCodec() {
907- super(inet(), InetAddress.class);
1214+ super(DataType.inet(), InetAddress.class);
9081215 }
9091216
9101217 @Override
9111218 public InetAddress parse(String value) {
912- if (value == null || value.isEmpty() || value.equals(NULL))
1219+ if (value == null || value.isEmpty() || value.equals("NULL"))
9131220 return null;
9141221
9151222 value = value.trim();
@@ -925,7 +1232,7 @@
9251232 @Override
9261233 public String format(InetAddress value) {
9271234 if (value == null)
928- return NULL;
1235+ return "NULL";
9291236 return "'" + value.getHostAddress() + "'";
9301237 }
9311238
@@ -949,18 +1256,18 @@
9491256 /**
9501257 * This codec maps a CQL {@link DataType#tinyint()} to a Java {@link Byte}.
9511258 */
952- public static class TinyIntCodec extends TypeCodec<Byte> implements PrimitiveByteCodec {
1259+ private static class TinyIntCodec extends PrimitiveByteCodec {
9531260
954- public static final TinyIntCodec instance = new TinyIntCodec();
1261+ private static final TinyIntCodec instance = new TinyIntCodec();
9551262
9561263 private TinyIntCodec() {
957- super(tinyint(), Byte.class);
1264+ super(tinyint());
9581265 }
9591266
9601267 @Override
9611268 public Byte parse(String value) {
9621269 try {
963- return value == null || value.isEmpty() || value.equals(NULL) ? null : Byte.parseByte(value);
1270+ return value == null || value.isEmpty() || value.equals("NULL") ? null : Byte.parseByte(value);
9641271 } catch (NumberFormatException e) {
9651272 throw new InvalidTypeException(String.format("Cannot parse 8-bits int value from \"%s\"", value));
9661273 }
@@ -969,15 +1276,10 @@
9691276 @Override
9701277 public String format(Byte value) {
9711278 if (value == null)
972- return NULL;
1279+ return "NULL";
9731280 return Byte.toString(value);
9741281 }
9751282
976- @Override
977- public ByteBuffer serialize(Byte value, ProtocolVersion protocolVersion) {
978- return value == null ? null : serializeNoBoxing(value, protocolVersion);
979- }
980-
9811283 @Override
9821284 public ByteBuffer serializeNoBoxing(byte value, ProtocolVersion protocolVersion) {
9831285 ByteBuffer bb = ByteBuffer.allocate(1);
@@ -985,11 +1287,6 @@
9851287 return bb;
9861288 }
9871289
988- @Override
989- public Byte deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
990- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
991- }
992-
9931290 @Override
9941291 public byte deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
9951292 if (bytes == null || bytes.remaining() == 0)
@@ -1004,18 +1301,18 @@
10041301 /**
10051302 * This codec maps a CQL {@link DataType#smallint()} to a Java {@link Short}.
10061303 */
1007- public static class SmallIntCodec extends TypeCodec<Short> implements PrimitiveShortCodec {
1304+ private static class SmallIntCodec extends PrimitiveShortCodec {
10081305
1009- public static final SmallIntCodec instance = new SmallIntCodec();
1306+ private static final SmallIntCodec instance = new SmallIntCodec();
10101307
10111308 private SmallIntCodec() {
1012- super(smallint(), Short.class);
1309+ super(smallint());
10131310 }
10141311
10151312 @Override
10161313 public Short parse(String value) {
10171314 try {
1018- return value == null || value.isEmpty() || value.equals(NULL) ? null : Short.parseShort(value);
1315+ return value == null || value.isEmpty() || value.equals("NULL") ? null : Short.parseShort(value);
10191316 } catch (NumberFormatException e) {
10201317 throw new InvalidTypeException(String.format("Cannot parse 16-bits int value from \"%s\"", value));
10211318 }
@@ -1024,15 +1321,10 @@
10241321 @Override
10251322 public String format(Short value) {
10261323 if (value == null)
1027- return NULL;
1324+ return "NULL";
10281325 return Short.toString(value);
10291326 }
10301327
1031- @Override
1032- public ByteBuffer serialize(Short value, ProtocolVersion protocolVersion) {
1033- return value == null ? null : serializeNoBoxing(value, protocolVersion);
1034- }
1035-
10361328 @Override
10371329 public ByteBuffer serializeNoBoxing(short value, ProtocolVersion protocolVersion) {
10381330 ByteBuffer bb = ByteBuffer.allocate(2);
@@ -1040,11 +1332,6 @@
10401332 return bb;
10411333 }
10421334
1043- @Override
1044- public Short deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1045- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
1046- }
1047-
10481335 @Override
10491336 public short deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
10501337 if (bytes == null || bytes.remaining() == 0)
@@ -1059,18 +1346,18 @@
10591346 /**
10601347 * This codec maps a CQL {@link DataType#cint()} to a Java {@link Integer}.
10611348 */
1062- public static class IntCodec extends TypeCodec<Integer> implements PrimitiveIntCodec {
1349+ private static class IntCodec extends PrimitiveIntCodec {
10631350
1064- public static final IntCodec instance = new IntCodec();
1351+ private static final IntCodec instance = new IntCodec();
10651352
10661353 private IntCodec() {
1067- super(cint(), Integer.class);
1354+ super(DataType.cint());
10681355 }
10691356
10701357 @Override
10711358 public Integer parse(String value) {
10721359 try {
1073- return value == null || value.isEmpty() || value.equals(NULL) ? null : Integer.parseInt(value);
1360+ return value == null || value.isEmpty() || value.equals("NULL") ? null : Integer.parseInt(value);
10741361 } catch (NumberFormatException e) {
10751362 throw new InvalidTypeException(String.format("Cannot parse 32-bits int value from \"%s\"", value));
10761363 }
@@ -1079,15 +1366,10 @@
10791366 @Override
10801367 public String format(Integer value) {
10811368 if (value == null)
1082- return NULL;
1369+ return "NULL";
10831370 return Integer.toString(value);
10841371 }
10851372
1086- @Override
1087- public ByteBuffer serialize(Integer value, ProtocolVersion protocolVersion) {
1088- return value == null ? null : serializeNoBoxing(value, protocolVersion);
1089- }
1090-
10911373 @Override
10921374 public ByteBuffer serializeNoBoxing(int value, ProtocolVersion protocolVersion) {
10931375 ByteBuffer bb = ByteBuffer.allocate(4);
@@ -1095,11 +1377,6 @@
10951377 return bb;
10961378 }
10971379
1098- @Override
1099- public Integer deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1100- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
1101- }
1102-
11031380 @Override
11041381 public int deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
11051382 if (bytes == null || bytes.remaining() == 0)
@@ -1114,7 +1391,7 @@
11141391 /**
11151392 * This codec maps a CQL {@link DataType#timestamp()} to a Java {@link Date}.
11161393 */
1117- public static class TimestampCodec extends TypeCodec<Date> {
1394+ private static class TimestampCodec extends TypeCodec<Date> {
11181395
11191396 private static final String[] iso8601Patterns = new String[]{
11201397 "yyyy-MM-dd HH:mm",
@@ -1133,12 +1410,12 @@
11331410 "yyyy-MM-ddZ"
11341411 };
11351412
1136- public static final TimestampCodec instance = new TimestampCodec();
1413+ private static final TimestampCodec instance = new TimestampCodec();
11371414
11381415 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
11391416
11401417 private TimestampCodec() {
1141- super(timestamp(), Date.class);
1418+ super(DataType.timestamp(), Date.class);
11421419 }
11431420
11441421 /*
@@ -1152,14 +1429,12 @@
11521429
11531430 ParsePosition pos = new ParsePosition(0);
11541431 for (String parsePattern : parsePatterns) {
1155- String pattern = parsePattern;
11561432
1157- parser.applyPattern(pattern);
1433+ parser.applyPattern(parsePattern);
11581434 pos.setIndex(0);
11591435
1160- String str2 = str;
1161- Date date = parser.parse(str2, pos);
1162- if (date != null && pos.getIndex() == str2.length()) {
1436+ Date date = parser.parse(str, pos);
1437+ if (date != null && pos.getIndex() == str.length()) {
11631438 return date;
11641439 }
11651440 }
@@ -1168,7 +1443,7 @@
11681443
11691444 @Override
11701445 public Date parse(String value) {
1171- if (value == null || value.isEmpty() || value.equals(NULL))
1446+ if (value == null || value.isEmpty() || value.equals("NULL"))
11721447 return null;
11731448
11741449 // strip enclosing single quotes, if any
@@ -1193,7 +1468,7 @@
11931468 @Override
11941469 public String format(Date value) {
11951470 if (value == null)
1196- return NULL;
1471+ return "NULL";
11971472 return Long.toString(value.getTime());
11981473 }
11991474
@@ -1211,9 +1486,9 @@
12111486 /**
12121487 * This codec maps a CQL {@link DataType#date()} to the custom {@link LocalDate} class.
12131488 */
1214- public static class DateCodec extends TypeCodec<LocalDate> {
1489+ private static class DateCodec extends TypeCodec<LocalDate> {
12151490
1216- public static final DateCodec instance = new DateCodec();
1491+ private static final DateCodec instance = new DateCodec();
12171492
12181493 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
12191494 private static final String pattern = "yyyy-MM-dd";
@@ -1221,12 +1496,12 @@
12211496 private static final long EPOCH_AS_CQL_LONG = (1L << 31);
12221497
12231498 private DateCodec() {
1224- super(date(), LocalDate.class);
1499+ super(DataType.date(), LocalDate.class);
12251500 }
12261501
12271502 @Override
12281503 public LocalDate parse(String value) {
1229- if (value == null || value.isEmpty() || value.equals(NULL))
1504+ if (value == null || value.isEmpty() || value.equals("NULL"))
12301505 return null;
12311506
12321507 // strip enclosing single quotes, if any
@@ -1252,7 +1527,6 @@
12521527 return LocalDate.fromDaysSinceEpoch(days);
12531528 }
12541529
1255-
12561530 SimpleDateFormat parser = new SimpleDateFormat(pattern);
12571531 parser.setLenient(false);
12581532 parser.setTimeZone(TimeZone.getTimeZone("UTC"));
@@ -1269,7 +1543,7 @@
12691543 @Override
12701544 public String format(LocalDate value) {
12711545 if (value == null)
1272- return NULL;
1546+ return "NULL";
12731547 return "'" + value.toString() + "'";
12741548 }
12751549
@@ -1298,14 +1572,14 @@
12981572 /**
12991573 * This codec maps a CQL {@link DataType#time()} to a Java {@link Long}.
13001574 */
1301- public static class TimeCodec extends LongCodec {
1575+ private static class TimeCodec extends LongCodec {
13021576
13031577 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
13041578
1305- public static final TimeCodec instance = new TimeCodec();
1579+ private static final TimeCodec instance = new TimeCodec();
13061580
13071581 private TimeCodec() {
1308- super(time());
1582+ super(DataType.time());
13091583 }
13101584
13111585 // Time specific parsing loosely based on java.sql.Timestamp
@@ -1371,7 +1645,7 @@
13711645
13721646 @Override
13731647 public Long parse(String value) {
1374- if (value == null || value.isEmpty() || value.equals(NULL))
1648+ if (value == null || value.isEmpty() || value.equals("NULL"))
13751649 return null;
13761650
13771651 // enclosing single quotes required, even for long literals
@@ -1397,7 +1671,7 @@
13971671 @Override
13981672 public String format(Long value) {
13991673 if (value == null)
1400- return NULL;
1674+ return "NULL";
14011675 int nano = (int)(value % 1000000000);
14021676 value -= nano;
14031677 value /= 1000000000;
@@ -1410,7 +1684,7 @@
14101684 int hours = (int)(value % 24);
14111685 value -= hours;
14121686 value /= 24;
1413- assert(value == 0);
1687+ assert (value == 0);
14141688 StringBuilder sb = new StringBuilder("'");
14151689 leftPadZeros(hours, 2, sb);
14161690 sb.append(":");
@@ -1432,7 +1706,7 @@
14321706 /**
14331707 * Base class for codecs handling CQL UUID types such as {@link DataType#uuid()} and {@link DataType#timeuuid()}.
14341708 */
1435- public static abstract class AbstractUUIDCodec extends TypeCodec<UUID> {
1709+ private static abstract class AbstractUUIDCodec extends TypeCodec<UUID> {
14361710
14371711 private AbstractUUIDCodec(DataType cqlType) {
14381712 super(cqlType, UUID.class);
@@ -1441,7 +1715,7 @@
14411715 @Override
14421716 public UUID parse(String value) {
14431717 try {
1444- return value == null || value.isEmpty() || value.equals(NULL) ? null : UUID.fromString(value);
1718+ return value == null || value.isEmpty() || value.equals("NULL") ? null : UUID.fromString(value);
14451719 } catch (IllegalArgumentException e) {
14461720 throw new InvalidTypeException(String.format("Cannot parse UUID value from \"%s\"", value));
14471721 }
@@ -1450,13 +1724,13 @@
14501724 @Override
14511725 public String format(UUID value) {
14521726 if (value == null)
1453- return NULL;
1727+ return "NULL";
14541728 return value.toString();
14551729 }
14561730
14571731 @Override
14581732 public ByteBuffer serialize(UUID value, ProtocolVersion protocolVersion) {
1459- if(value == null)
1733+ if (value == null)
14601734 return null;
14611735 ByteBuffer bb = ByteBuffer.allocate(16);
14621736 bb.putLong(0, value.getMostSignificantBits());
@@ -1473,12 +1747,12 @@
14731747 /**
14741748 * This codec maps a CQL {@link DataType#uuid()} to a Java {@link UUID}.
14751749 */
1476- public static class UUIDCodec extends AbstractUUIDCodec {
1750+ private static class UUIDCodec extends AbstractUUIDCodec {
14771751
1478- public static final UUIDCodec instance = new UUIDCodec();
1752+ private static final UUIDCodec instance = new UUIDCodec();
14791753
14801754 private UUIDCodec() {
1481- super(uuid());
1755+ super(DataType.uuid());
14821756 }
14831757
14841758 }
@@ -1486,9 +1760,9 @@
14861760 /**
14871761 * This codec maps a CQL {@link DataType#timeuuid()} to a Java {@link UUID}.
14881762 */
1489- public static class TimeUUIDCodec extends AbstractUUIDCodec {
1763+ private static class TimeUUIDCodec extends AbstractUUIDCodec {
14901764
1491- public static final TimeUUIDCodec instance = new TimeUUIDCodec();
1765+ private static final TimeUUIDCodec instance = new TimeUUIDCodec();
14921766
14931767 private TimeUUIDCodec() {
14941768 super(timeuuid());
@@ -1496,17 +1770,14 @@
14961770
14971771 @Override
14981772 public boolean accepts(Object value) {
1499- if (super.accepts(value)) {
1500- // only accept time-based uuids
1501- return ((UUID)value).version() == 1;
1502- }
1503- return false;
1773+ // only accept time-based uuids
1774+ return super.accepts(value) && ((UUID)value).version() == 1;
15041775 }
15051776
15061777 @Override
15071778 public String format(UUID value) {
15081779 if (value == null)
1509- return NULL;
1780+ return "NULL";
15101781 if (value.version() != 1)
15111782 throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", value));
15121783 return super.format(value);
@@ -1514,7 +1785,7 @@
15141785
15151786 @Override
15161787 public ByteBuffer serialize(UUID value, ProtocolVersion protocolVersion) {
1517- if(value == null)
1788+ if (value == null)
15181789 return null;
15191790 if (value.version() != 1)
15201791 throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", value));
@@ -1525,18 +1796,18 @@
15251796 /**
15261797 * This codec maps a CQL {@link DataType#varint()} to a Java {@link BigInteger}.
15271798 */
1528- public static class VarintCodec extends TypeCodec<BigInteger> {
1799+ private static class VarintCodec extends TypeCodec<BigInteger> {
15291800
1530- public static final VarintCodec instance = new VarintCodec();
1801+ private static final VarintCodec instance = new VarintCodec();
15311802
15321803 private VarintCodec() {
1533- super(varint(), BigInteger.class);
1804+ super(DataType.varint(), BigInteger.class);
15341805 }
15351806
15361807 @Override
15371808 public BigInteger parse(String value) {
15381809 try {
1539- return value == null || value.isEmpty() || value.equals(NULL) ? null : new BigInteger(value);
1810+ return value == null || value.isEmpty() || value.equals("NULL") ? null : new BigInteger(value);
15401811 } catch (NumberFormatException e) {
15411812 throw new InvalidTypeException(String.format("Cannot parse varint value from \"%s\"", value));
15421813 }
@@ -1545,7 +1816,7 @@
15451816 @Override
15461817 public String format(BigInteger value) {
15471818 if (value == null)
1548- return NULL;
1819+ return "NULL";
15491820 return value.toString();
15501821 }
15511822
@@ -1565,18 +1836,18 @@
15651836 * or {@link DataType#set(DataType)}.
15661837 * Note that for practical reasons, {@link MapCodec} does not inherit from this class.
15671838 */
1568- public abstract static class CollectionCodec<E, C extends Collection<E>> extends TypeCodec<C> {
1839+ private abstract static class CollectionCodec<E, C extends Collection<E>> extends TypeCodec<C> {
15691840
15701841 protected final TypeCodec<E> eltCodec;
15711842
1572- public CollectionCodec(CollectionType cqlType, TypeToken<C> javaType, TypeCodec<E> eltCodec) {
1843+ private CollectionCodec(CollectionType cqlType, TypeToken<C> javaType, TypeCodec<E> eltCodec) {
15731844 super(cqlType, javaType);
15741845 this.eltCodec = eltCodec;
15751846 }
15761847
15771848 @Override
15781849 public ByteBuffer serialize(C value, ProtocolVersion protocolVersion) {
1579- if(value == null)
1850+ if (value == null)
15801851 return null;
15811852 List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(value.size());
15821853 for (E elt : value) {
@@ -1617,7 +1888,7 @@
16171888 @Override
16181889 public String format(C value) {
16191890 if (value == null)
1620- return NULL;
1891+ return "NULL";
16211892 StringBuilder sb = new StringBuilder();
16221893 sb.append(getOpeningChar());
16231894 int i = 0;
@@ -1632,7 +1903,7 @@
16321903
16331904 @Override
16341905 public C parse(String value) {
1635- if (value == null || value.isEmpty() || value.equals(NULL))
1906+ if (value == null || value.isEmpty() || value.equals("NULL"))
16361907 return null;
16371908
16381909 int idx = ParseUtils.skipSpaces(value, 0);
@@ -1692,10 +1963,10 @@
16921963 * This codec maps a CQL {@link DataType#list(DataType) list type} to a Java {@link List}.
16931964 * Implementation note: this codec returns mutable, non thread-safe {@link ArrayList} instances.
16941965 */
1695- public static class ListCodec<T> extends CollectionCodec<T, List<T>> {
1966+ private static class ListCodec<T> extends CollectionCodec<T, List<T>> {
16961967
1697- public ListCodec(TypeCodec<T> eltCodec) {
1698- super(list(eltCodec.getCqlType()), listOf(eltCodec.getJavaType()), eltCodec);
1968+ private ListCodec(TypeCodec<T> eltCodec) {
1969+ super(DataType.list(eltCodec.getCqlType()), listOf(eltCodec.getJavaType()), eltCodec);
16991970 }
17001971
17011972 @Override
@@ -1719,10 +1990,10 @@
17191990 * This codec maps a CQL {@link DataType#set(DataType) set type} to a Java {@link Set}.
17201991 * Implementation note: this codec returns mutable, non thread-safe {@link LinkedHashSet} instances.
17211992 */
1722- public static class SetCodec<T> extends CollectionCodec<T, Set<T>> {
1993+ private static class SetCodec<T> extends CollectionCodec<T, Set<T>> {
17231994
1724- public SetCodec(TypeCodec<T> eltCodec) {
1725- super(set(eltCodec.cqlType), setOf(eltCodec.getJavaType()), eltCodec);
1995+ private SetCodec(TypeCodec<T> eltCodec) {
1996+ super(DataType.set(eltCodec.cqlType), setOf(eltCodec.getJavaType()), eltCodec);
17261997 }
17271998
17281999 @Override
@@ -1745,14 +2016,14 @@
17452016 * This codec maps a CQL {@link DataType#map(DataType, DataType) map type} to a Java {@link Map}.
17462017 * Implementation note: this codec returns mutable, non thread-safe {@link LinkedHashMap} instances.
17472018 */
1748- public static class MapCodec<K, V> extends TypeCodec<Map<K, V>> {
2019+ private static class MapCodec<K, V> extends TypeCodec<Map<K, V>> {
17492020
17502021 private final TypeCodec<K> keyCodec;
17512022
17522023 private final TypeCodec<V> valueCodec;
17532024
1754- public MapCodec(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec) {
1755- super(map(keyCodec.getCqlType(), valueCodec.getCqlType()), mapOf(keyCodec.getJavaType(), valueCodec.getJavaType()));
2025+ private MapCodec(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec) {
2026+ super(DataType.map(keyCodec.getCqlType(), valueCodec.getCqlType()), mapOf(keyCodec.getJavaType(), valueCodec.getJavaType()));
17562027 this.keyCodec = keyCodec;
17572028 this.valueCodec = valueCodec;
17582029 }
@@ -1772,7 +2043,7 @@
17722043
17732044 @Override
17742045 public Map<K, V> parse(String value) {
1775- if (value == null || value.isEmpty() || value.equals(NULL))
2046+ if (value == null || value.isEmpty() || value.equals("NULL"))
17762047 return null;
17772048
17782049 int idx = ParseUtils.skipSpaces(value, 0);
@@ -1827,7 +2098,7 @@
18272098 @Override
18282099 public String format(Map<K, V> value) {
18292100 if (value == null)
1830- return NULL;
2101+ return "NULL";
18312102 StringBuilder sb = new StringBuilder();
18322103 sb.append("{");
18332104 int i = 0;
@@ -1897,26 +2168,23 @@
18972168 /**
18982169 * This codec maps a CQL {@link UserType} to a {@link UDTValue}.
18992170 */
1900- public static class UDTCodec extends TypeCodec<UDTValue> {
2171+ private static class UDTCodec extends TypeCodec<UDTValue> {
19012172
19022173 private final UserType definition;
19032174
1904- public UDTCodec(UserType definition) {
2175+ private UDTCodec(UserType definition) {
19052176 super(definition, UDTValue.class);
19062177 this.definition = definition;
19072178 }
19082179
19092180 @Override
19102181 public boolean accepts(Object value) {
1911- if(value instanceof UDTValue) {
1912- return ((UDTValue) value).getType().equals(definition);
1913- }
1914- return false;
2182+ return value instanceof UDTValue && ((UDTValue)value).getType().equals(definition);
19152183 }
19162184
19172185 @Override
19182186 public UDTValue parse(String value) {
1919- if (value == null || value.isEmpty() || value.equals(NULL))
2187+ if (value == null || value.isEmpty() || value.equals("NULL"))
19202188 return null;
19212189
19222190 UDTValue v = definition.newValue();
@@ -1975,7 +2243,7 @@
19752243 @Override
19762244 public String format(UDTValue value) {
19772245 if (value == null)
1978- return NULL;
2246+ return "NULL";
19792247 return value.toString();
19802248 }
19812249
@@ -2019,11 +2287,11 @@
20192287 /**
20202288 * This codec maps a CQL {@link TupleType} to a {@link TupleValue}.
20212289 */
2022- public static class TupleCodec extends TypeCodec<TupleValue> {
2290+ private static class TupleCodec extends TypeCodec<TupleValue> {
20232291
20242292 private final TupleType definition;
20252293
2026- public TupleCodec(TupleType definition) {
2294+ private TupleCodec(TupleType definition) {
20272295 super(definition, TupleValue.class);
20282296 this.definition = definition;
20292297 }
@@ -2039,12 +2307,12 @@
20392307 public boolean accepts(Object value) {
20402308 // a tuple codec should accept tuple values of a different type,
20412309 // provided that the latter is contained in this codec's type.
2042- return value instanceof TupleValue && definition.contains(((TupleValue) value).getType());
2310+ return value instanceof TupleValue && definition.contains(((TupleValue)value).getType());
20432311 }
20442312
20452313 @Override
20462314 public TupleValue parse(String value) {
2047- if (value == null || value.isEmpty() || value.equals(NULL))
2315+ if (value == null || value.isEmpty() || value.equals("NULL"))
20482316 return null;
20492317
20502318 TupleValue v = definition.newValue();
@@ -2088,7 +2356,7 @@
20882356 @Override
20892357 public String format(TupleValue value) {
20902358 if (value == null)
2091- return NULL;
2359+ return "NULL";
20922360 return value.toString();
20932361 }
20942362
@@ -2129,211 +2397,4 @@
21292397 }
21302398 }
21312399
2132- /**
2133- * An abstract TypeCodec that actually stores objects as serialized strings.
2134- * This can serve as a base for codecs dealing with XML or JSON formats.
2135- *
2136- * @param <T> The Java type this codec serializes from and deserializes to.
2137- */
2138- public abstract static class StringParsingCodec<T> extends TypeCodec<T> {
2139-
2140- private final TypeCodec<String> innerCodec;
2141-
2142- public StringParsingCodec(Class<T> javaType) {
2143- this(TypeToken.of(javaType));
2144- }
2145-
2146- public StringParsingCodec(TypeToken<T> javaType) {
2147- this(VarcharCodec.instance, javaType);
2148- }
2149-
2150- public StringParsingCodec(TypeCodec<String> innerCodec, Class<T> javaType) {
2151- this(innerCodec, TypeToken.of(javaType));
2152- }
2153-
2154- public StringParsingCodec(TypeCodec<String> innerCodec, TypeToken<T> javaType) {
2155- super(innerCodec.getCqlType(), javaType);
2156- this.innerCodec = innerCodec;
2157- }
2158-
2159- @Override
2160- public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
2161- return value == null ? null : innerCodec.serialize(toString(value), protocolVersion);
2162- }
2163-
2164- @Override
2165- public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
2166- String value = innerCodec.deserialize(bytes, protocolVersion);
2167- return value == null ? null : fromString(value);
2168- }
2169-
2170- @Override
2171- public String format(T value) throws InvalidTypeException {
2172- return value == null ? null : innerCodec.format(toString(value));
2173- }
2174-
2175- @Override
2176- public T parse(String value) throws InvalidTypeException {
2177- return value == null || value.isEmpty() || value.equals(NULL) ? null : fromString(innerCodec.parse(value));
2178- }
2179-
2180- /**
2181- * Return the String representation of the given object;
2182- * no special CQL quoting should be applied here.
2183- * Null values should be accepted; in most cases, implementors
2184- * should return null for null inputs.
2185- *
2186- * @param value the value to convert into a string
2187- * @return the String representation of the given object
2188- */
2189- protected abstract String toString(T value);
2190-
2191- /**
2192- * Parse the given string into an object;
2193- * no special CQL unquoting should be applied here.
2194- * Null values should be accepted; in most cases, implementors
2195- * should return null for null inputs.
2196- *
2197- * @param value the string to parse
2198- * @return the parsed object.
2199- */
2200- protected abstract T fromString(String value);
2201-
2202- }
2203-
2204- /**
2205- * An abstract TypeCodec that maps a Java Pojo to another Java object
2206- * that can in turn be serialized into a CQL type.
2207- * This can serve as a base for libraries dealing with Pojo mappings.
2208- *
2209- * @param <T> The outer Java type
2210- * @param <U> The inner Java type
2211- */
2212- public abstract static class MappingCodec<T, U> extends TypeCodec<T> {
2213-
2214- protected final TypeCodec<U> innerCodec;
2215-
2216- public MappingCodec(TypeCodec<U> innerCodec, Class<T> javaType) {
2217- this(innerCodec, TypeToken.of(javaType));
2218- }
2219-
2220- public MappingCodec(TypeCodec<U> innerCodec, TypeToken<T> javaType) {
2221- super(innerCodec.getCqlType(), javaType);
2222- this.innerCodec = innerCodec;
2223- }
2224-
2225- @Override
2226- public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
2227- return innerCodec.serialize(serialize(value), protocolVersion);
2228- }
2229-
2230- @Override
2231- public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
2232- return deserialize(innerCodec.deserialize(bytes, protocolVersion));
2233- }
2234-
2235- @Override
2236- public T parse(String value) throws InvalidTypeException {
2237- return value == null || value.isEmpty() || value.equals(NULL) ? null : deserialize(innerCodec.parse(value));
2238- }
2239-
2240- @Override
2241- public String format(T value) throws InvalidTypeException {
2242- return value == null ? null : innerCodec.format(serialize(value));
2243- }
2244-
2245- protected abstract T deserialize(U value);
2246-
2247- protected abstract U serialize(T value);
2248-
2249- }
2250-
2251- /**
2252- * A codec that serializes {@link Enum} instances as CQL {@link DataType#varchar() varchar}s
2253- * representing their programmatic names as returned by {@link Enum#name()}.
2254- * <p>
2255- * This codec is automatically used by the driver to create codecs for {@link Enum}
2256- * instances on the fly.
2257- *
2258- * @param <E> The Enum class this codec serializes from and deserializes to.
2259- */
2260- public static class EnumStringCodec<E extends Enum<E>> extends StringParsingCodec<E> {
2261-
2262- private final Class<E> enumClass;
2263-
2264- public EnumStringCodec(Class<E> enumClass) {
2265- super(enumClass);
2266- this.enumClass = enumClass;
2267- }
2268-
2269- public EnumStringCodec(TypeCodec<String> innerCodec, Class<E> enumClass) {
2270- super(innerCodec, enumClass);
2271- this.enumClass = enumClass;
2272- }
2273-
2274- @Override
2275- protected String toString(E value) {
2276- return value == null ? null : value.name();
2277- }
2278-
2279- @Override
2280- protected E fromString(String value) {
2281- return value == null ? null : Enum.valueOf(enumClass, value);
2282- }
2283-
2284- }
2285-
2286- /**
2287- * A codec that serializes {@link Enum} instances as CQL {@link DataType#cint() int}s
2288- * representing their ordinal values as returned by {@link Enum#ordinal()}.
2289- * <p>
2290- * Note that, by default, the driver uses {@link EnumStringCodec} to serialize {@link Enum} instances;
2291- * to force the use of this codec instead for a specific {@link Enum} instance,
2292- * the appropriate {@link EnumIntCodec} instance must be explicitly
2293- * {@link CodecRegistry#register(TypeCodec) registered}.
2294- * <p>
2295- * <strong>Note that this codec relies on the enum constants declaration order;
2296- * it is therefore vital that this order remains immutable.</strong>
2297- *
2298- * @param <E> The Enum class this codec serializes from and deserializes to.
2299- */
2300- public static class EnumIntCodec<E extends Enum<E>> extends TypeCodec<E> {
2301-
2302- private final E[] enumConstants;
2303-
2304- private final TypeCodec<Integer> innerCodec;
2305-
2306- public EnumIntCodec(Class<E> enumClass) {
2307- this(IntCodec.instance, enumClass);
2308- }
2309-
2310- public EnumIntCodec(TypeCodec<Integer> innerCodec, Class<E> enumClass) {
2311- super(innerCodec.getCqlType(), enumClass);
2312- this.enumConstants = enumClass.getEnumConstants();
2313- this.innerCodec = innerCodec;
2314- }
2315-
2316- @Override
2317- public ByteBuffer serialize(E value, ProtocolVersion protocolVersion) throws InvalidTypeException {
2318- return innerCodec.serialize(value.ordinal(), protocolVersion);
2319- }
2320-
2321- @Override
2322- public E deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
2323- return enumConstants[innerCodec.deserialize(bytes, protocolVersion)];
2324- }
2325-
2326- @Override
2327- public E parse(String value) throws InvalidTypeException {
2328- return value == null || value.isEmpty() || value.equals(NULL) ? null : enumConstants[Integer.parseInt(value)];
2329- }
2330-
2331- @Override
2332- public String format(E value) throws InvalidTypeException {
2333- if (value == null)
2334- return NULL;
2335- return Integer.toString(value.ordinal());
2336- }
2337- }
2338-
23392400 }
modified driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java +3 −3
@@ -152,13 +152,13 @@
152152 private static final String TEXT = "org.apache.cassandra.db.marshal.UTF8Type";
153153
154154 private static final Row SYSTEM_ROW_CAT_TOS = mockRow("cat_tos", ImmutableList.of("int"), ImmutableList.of(INT),
155- null, TypeCodec.VarcharCodec.instance.serialize("0", PROTOCOL_VERSION), TEXT, "cat", TEXT);
155+ null, TypeCodec.varchar().serialize("0", PROTOCOL_VERSION), TEXT, "cat", TEXT);
156156
157157 private static final Row SYSTEM_ROW_MYCOUNT = mockRow("mycount", Collections.<String>emptyList(), Collections.<String>emptyList(),
158- null, TypeCodec.IntCodec.instance.serialize(0, PROTOCOL_VERSION), INT, "inc", INT);
158+ null, TypeCodec.cint().serialize(0, PROTOCOL_VERSION), INT, "inc", INT);
159159
160160 private static final Row SYSTEM_ROW_PRETTYSUM = mockRow("prettysum", ImmutableList.of("int"), ImmutableList.of(INT),
161- "announce", TypeCodec.IntCodec.instance.serialize(0, PROTOCOL_VERSION), TEXT, "plus", INT);
161+ "announce", TypeCodec.cint().serialize(0, PROTOCOL_VERSION), TEXT, "plus", INT);
162162
163163 private static final Row SYSTEM_ROW_SUM = mockRow("sum", ImmutableList.of("int"), ImmutableList.of(INT),
164164 null, null, INT, "plus", INT);
added driver-core/src/test/java/com/datastax/driver/core/EnumIntCodec.java +75 −0
@@ -0,0 +1,75 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.nio.ByteBuffer;
19+
20+import com.datastax.driver.core.exceptions.InvalidTypeException;
21+
22+/**
23+ * A codec that serializes {@link Enum} instances as CQL {@link DataType#cint() int}s
24+ * representing their ordinal values as returned by {@link Enum#ordinal()}.
25+ * <p>
26+ * Note that, by default, the driver uses {@link EnumStringCodec} to serialize {@link Enum} instances;
27+ * to force the use of this codec instead for a specific {@link Enum} instance,
28+ * the appropriate {@link EnumIntCodec} instance must be explicitly
29+ * {@link CodecRegistry#register(TypeCodec) registered}.
30+ * <p>
31+ * <strong>Note that this codec relies on the enum constants declaration order;
32+ * it is therefore vital that this order remains immutable.</strong>
33+ *
34+ * @param <E> The Enum class this codec serializes from and deserializes to.
35+ */
36+public class EnumIntCodec<E extends Enum<E>> extends TypeCodec<E> {
37+
38+ private final E[] enumConstants;
39+
40+ private final TypeCodec<Integer> innerCodec;
41+
42+ public EnumIntCodec(Class<E> enumClass) {
43+ this(TypeCodec.cint(), enumClass);
44+ }
45+
46+ public EnumIntCodec(TypeCodec<Integer> innerCodec, Class<E> enumClass) {
47+ super(innerCodec.getCqlType(), enumClass);
48+ this.enumConstants = enumClass.getEnumConstants();
49+ this.innerCodec = innerCodec;
50+ }
51+
52+ @Override
53+ public ByteBuffer serialize(E value, ProtocolVersion protocolVersion) throws InvalidTypeException {
54+ return value == null ? null : innerCodec.serialize(value.ordinal(), protocolVersion);
55+ }
56+
57+ @Override
58+ public E deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
59+ Integer value = innerCodec.deserialize(bytes, protocolVersion);
60+ return value == null ? null : enumConstants[value];
61+ }
62+
63+ @Override
64+ public String format(E value) throws InvalidTypeException {
65+ if (value == null)
66+ return "NULL";
67+ return innerCodec.format(value.ordinal());
68+ }
69+
70+ @Override
71+ public E parse(String value) throws InvalidTypeException {
72+ return value == null || value.isEmpty() || value.equals("NULL") ? null : enumConstants[innerCodec.parse(value)];
73+ }
74+
75+}
added driver-core/src/test/java/com/datastax/driver/core/EnumStringCodec.java +70 −0
@@ -0,0 +1,70 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.nio.ByteBuffer;
19+
20+import com.datastax.driver.core.exceptions.InvalidTypeException;
21+
22+/**
23+ * A codec that serializes {@link Enum} instances as CQL {@link DataType#varchar() varchar}s
24+ * representing their programmatic names as returned by {@link Enum#name()}.
25+ * <p>
26+ * This codec is automatically used by the driver to create codecs for {@link Enum}
27+ * instances on the fly.
28+ *
29+ * @param <E> The Enum class this codec serializes from and deserializes to.
30+ */
31+public class EnumStringCodec<E extends Enum<E>> extends TypeCodec<E> {
32+
33+ private final Class<E> enumClass;
34+
35+ private final TypeCodec<String> innerCodec;
36+
37+ public EnumStringCodec(Class<E> enumClass) {
38+ this(TypeCodec.varchar(), enumClass);
39+ }
40+
41+ public EnumStringCodec(TypeCodec<String> innerCodec, Class<E> enumClass) {
42+ super(innerCodec.getCqlType(), enumClass);
43+ this.innerCodec = innerCodec;
44+ this.enumClass = enumClass;
45+ }
46+
47+ @Override
48+ public ByteBuffer serialize(E value, ProtocolVersion protocolVersion) throws InvalidTypeException {
49+ return value == null ? null : innerCodec.serialize(value.name(), protocolVersion);
50+ }
51+
52+ @Override
53+ public E deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
54+ String value = innerCodec.deserialize(bytes, protocolVersion);
55+ return value == null ? null : Enum.valueOf(enumClass, value);
56+ }
57+
58+ @Override
59+ public String format(E value) throws InvalidTypeException {
60+ if (value == null)
61+ return "NULL";
62+ return innerCodec.format(value.name());
63+ }
64+
65+ @Override
66+ public E parse(String value) throws InvalidTypeException {
67+ return value == null || value.isEmpty() || value.equals("NULL") ? null : Enum.valueOf(enumClass, innerCodec.parse(value));
68+ }
69+
70+}
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +2 −1
@@ -18,6 +18,7 @@
1818 import java.nio.ByteBuffer;
1919 import java.util.Collection;
2020 import java.util.List;
21+import java.util.Map;
2122
2223 import com.google.common.collect.ImmutableList;
2324 import com.google.common.collect.ImmutableMap;
@@ -60,7 +61,7 @@
6061 definition(IndexMetadata.KIND, text()),
6162 definition(IndexMetadata.OPTIONS, map(text(), text()))
6263 });
63- public static final TypeCodec.MapCodec<String, String> MAP_CODEC = new TypeCodec.MapCodec<String, String>(TypeCodec.VarcharCodec.instance, TypeCodec.VarcharCodec.instance);
64+ public static final TypeCodec<Map<String, String>> MAP_CODEC = TypeCodec.map(TypeCodec.varchar(), TypeCodec.varchar());
6465
6566 private static ProtocolVersion protocolVersion;
6667 private static CodecRegistry codecRegistry;
modified driver-core/src/test/java/com/datastax/driver/core/JodaCodecs.java +7 −10
@@ -25,9 +25,6 @@
2525
2626 import static com.google.common.base.Preconditions.checkArgument;
2727
28-import static com.datastax.driver.core.DataType.timestamp;
29-import static com.datastax.driver.core.DataType.varchar;
30-
3128 /**
3229 * A collection of convenience {@link TypeCodec} instances useful for
3330 * serializing between CQL types and Joda types like {@link DateTime}.
@@ -58,12 +55,12 @@
5855 * IMPORTANT: {@link LocalTime} as millisecond precision; nanoseconds below one millisecond will be lost
5956 * during deserialization.
6057 */
61- public static class LocalTimeCodec extends TypeCodec.MappingCodec<LocalTime, Long> {
58+ public static class LocalTimeCodec extends MappingCodec<LocalTime, Long> {
6259
6360 public static final LocalTimeCodec instance = new LocalTimeCodec();
6461
6562 private LocalTimeCodec() {
66- super(TimeCodec.instance, LocalTime.class);
63+ super(TypeCodec.time(), LocalTime.class);
6764 }
6865
6966 @Override
@@ -87,12 +84,12 @@
8784 * setting and retrieval of <code>date</code> columns as
8885 * {@link org.joda.time.LocalDate} instances.
8986 */
90- public static class LocalDateCodec extends TypeCodec.MappingCodec<org.joda.time.LocalDate, LocalDate> {
87+ public static class LocalDateCodec extends MappingCodec<org.joda.time.LocalDate, LocalDate> {
9188
9289 public static final LocalDateCodec instance = new LocalDateCodec();
9390
9491 private LocalDateCodec() {
95- super(DateCodec.instance, org.joda.time.LocalDate.class);
92+ super(TypeCodec.date(), org.joda.time.LocalDate.class);
9693 }
9794
9895 @Override
@@ -120,12 +117,12 @@
120117 *
121118 * @see TimeZonePreservingDateTimeCodec
122119 */
123- public static class DateTimeCodec extends TypeCodec.MappingCodec<DateTime, Date> {
120+ public static class DateTimeCodec extends MappingCodec<DateTime, Date> {
124121
125122 public static final DateTimeCodec instance = new DateTimeCodec();
126123
127124 private DateTimeCodec() {
128- super(TimestampCodec.instance, DateTime.class);
125+ super(TypeCodec.timestamp(), DateTime.class);
129126 }
130127
131128 @Override
@@ -158,7 +155,7 @@
158155 * </p>
159156 *
160157 */
161- public static class TimeZonePreservingDateTimeCodec extends TypeCodec.MappingCodec<DateTime, TupleValue> {
158+ public static class TimeZonePreservingDateTimeCodec extends MappingCodec<DateTime, TupleValue> {
162159
163160 private final TupleType tupleType;
164161
modified driver-core/src/test/java/com/datastax/driver/core/JsonCodec.java +46 −9
@@ -16,43 +16,80 @@
1616 package com.datastax.driver.core;
1717
1818 import java.io.IOException;
19+import java.nio.ByteBuffer;
1920
2021 import com.fasterxml.jackson.core.JsonProcessingException;
22+import com.fasterxml.jackson.databind.JavaType;
2123 import com.fasterxml.jackson.databind.ObjectMapper;
24+import com.fasterxml.jackson.databind.type.TypeFactory;
2225
2326 import com.datastax.driver.core.exceptions.InvalidTypeException;
27+import com.datastax.driver.core.utils.Bytes;
2428
2529 /**
26- * A simple Json codec for TypeCodec tests.
30+ * A simple Json codec for TypeCodec tests that uses Jackson to perform serialization and deserialization.
2731 */
28-public class JsonCodec<T> extends TypeCodec.StringParsingCodec<T> {
32+public class JsonCodec<T> extends TypeCodec<T> {
2933
3034 private final ObjectMapper objectMapper = new ObjectMapper();
3135
3236 public JsonCodec(Class<T> javaType) {
33- super(javaType);
37+ super(DataType.varchar(), javaType);
3438 }
3539
3640 @Override
37- @SuppressWarnings("unchecked")
38- public T fromString(String value) {
41+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
3942 if (value == null)
4043 return null;
4144 try {
42- return (T) objectMapper.readValue(value, getJavaType().getRawType());
45+ return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
46+ } catch (JsonProcessingException e) {
47+ throw new InvalidTypeException(e.getMessage(), e);
48+ }
49+ }
50+
51+ @Override
52+ @SuppressWarnings("unchecked")
53+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
54+ if (bytes == null)
55+ return null;
56+ try {
57+ return (T)objectMapper.readValue(Bytes.getArray(bytes), toJacksonJavaType());
4358 } catch (IOException e) {
4459 throw new InvalidTypeException(e.getMessage(), e);
4560 }
4661 }
4762
4863 @Override
49- public String toString(T value) {
64+ public String format(T value) throws InvalidTypeException {
5065 if (value == null)
66+ return "NULL";
67+ String json;
68+ try {
69+ json = objectMapper.writeValueAsString(value);
70+ } catch (IOException e) {
71+ throw new InvalidTypeException(e.getMessage(), e);
72+ }
73+ return '\'' + json.replace("\'", "''") + '\'';
74+ }
75+
76+ @Override
77+ @SuppressWarnings("unchecked")
78+ public T parse(String value) throws InvalidTypeException {
79+ if (value == null || value.isEmpty() || value.equals("NULL"))
5180 return null;
81+ if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
82+ throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
83+ String json = value.substring(1, value.length() - 1).replace("''", "'");
5284 try {
53- return objectMapper.writeValueAsString(value);
54- } catch (JsonProcessingException e) {
85+ return (T)objectMapper.readValue(json, toJacksonJavaType());
86+ } catch (IOException e) {
5587 throw new InvalidTypeException(e.getMessage(), e);
5688 }
5789 }
90+
91+ protected JavaType toJacksonJavaType() {
92+ return TypeFactory.defaultInstance().constructType(getJavaType().getType());
93+ }
94+
5895 }
added driver-core/src/test/java/com/datastax/driver/core/MappingCodec.java +69 −0
@@ -0,0 +1,69 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.nio.ByteBuffer;
19+
20+import com.google.common.reflect.TypeToken;
21+
22+import com.datastax.driver.core.exceptions.InvalidTypeException;
23+
24+/**
25+ * An abstract TypeCodec that maps a Java Pojo to another Java object
26+ * that can in turn be serialized into a CQL type.
27+ * This can serve as a base for libraries dealing with Pojo mappings.
28+ *
29+ * @param <T> The outer Java type
30+ * @param <U> The inner Java type
31+ */
32+public abstract class MappingCodec<T, U> extends TypeCodec<T> {
33+
34+ protected final TypeCodec<U> innerCodec;
35+
36+ public MappingCodec(TypeCodec<U> innerCodec, Class<T> javaType) {
37+ this(innerCodec, TypeToken.of(javaType));
38+ }
39+
40+ public MappingCodec(TypeCodec<U> innerCodec, TypeToken<T> javaType) {
41+ super(innerCodec.getCqlType(), javaType);
42+ this.innerCodec = innerCodec;
43+ }
44+
45+ @Override
46+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
47+ return innerCodec.serialize(serialize(value), protocolVersion);
48+ }
49+
50+ @Override
51+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
52+ return deserialize(innerCodec.deserialize(bytes, protocolVersion));
53+ }
54+
55+ @Override
56+ public T parse(String value) throws InvalidTypeException {
57+ return value == null || value.isEmpty() || value.equals("NULL") ? null : deserialize(innerCodec.parse(value));
58+ }
59+
60+ @Override
61+ public String format(T value) throws InvalidTypeException {
62+ return value == null ? null : innerCodec.format(serialize(value));
63+ }
64+
65+ protected abstract T deserialize(U value);
66+
67+ protected abstract U serialize(T value);
68+
69+}
modified driver-core/src/test/java/com/datastax/driver/core/OptionalCodec.java +3 −2
@@ -23,9 +23,10 @@
2323 import com.google.common.reflect.TypeParameter;
2424 import com.google.common.reflect.TypeToken;
2525
26-import static com.google.common.base.Predicates.*;
26+import static com.google.common.base.Predicates.isNull;
27+import static com.google.common.base.Predicates.or;
2728
28-public class OptionalCodec<T> extends TypeCodec.MappingCodec<Optional<T>, T> {
29+public class OptionalCodec<T> extends MappingCodec<Optional<T>, T> {
2930
3031 private final Predicate<T> isAbsent;
3132
modified driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java +1 −1
@@ -102,7 +102,7 @@
102102
103103 private static void forceSchemaVersion(Session session, InetAddress peerAddress, UUID schemaVersion) {
104104 session.execute(String.format("UPDATE system.peers SET schema_version = %s WHERE peer = %s",
105- TypeCodec.UUIDCodec.instance.format(schemaVersion), TypeCodec.InetCodec.instance.format(peerAddress)));
105+ TypeCodec.uuid().format(schemaVersion), TypeCodec.inet().format(peerAddress)));
106106 }
107107
108108 @AfterMethod(groups = "short")
added driver-core/src/test/java/com/datastax/driver/core/StringParsingCodec.java +94 −0
@@ -0,0 +1,94 @@
1+package com.datastax.driver.core;
2+
3+import java.nio.ByteBuffer;
4+
5+import com.google.common.reflect.TypeToken;
6+
7+/*
8+ * Copyright (C) 2012-2015 DataStax Inc.
9+ *
10+ * Licensed under the Apache License, Version 2.0 (the "License");
11+ * you may not use this file except in compliance with the License.
12+ * You may obtain a copy of the License at
13+ *
14+ * http://www.apache.org/licenses/LICENSE-2.0
15+ *
16+ * Unless required by applicable law or agreed to in writing, software
17+ * distributed under the License is distributed on an "AS IS" BASIS,
18+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19+ * See the License for the specific language governing permissions and
20+ * limitations under the License.
21+ */
22+import com.datastax.driver.core.exceptions.InvalidTypeException;
23+
24+/**
25+ * An abstract TypeCodec that actually stores objects as serialized strings.
26+ * This can serve as a base for codecs dealing with XML or JSON formats.
27+ *
28+ * @param <T> The Java type this codec serializes from and deserializes to.
29+ */
30+public abstract class StringParsingCodec<T> extends TypeCodec<T> {
31+
32+ private final TypeCodec<String> innerCodec;
33+
34+ public StringParsingCodec(Class<T> javaType) {
35+ this(TypeToken.of(javaType));
36+ }
37+
38+ public StringParsingCodec(TypeToken<T> javaType) {
39+ this(TypeCodec.varchar(), javaType);
40+ }
41+
42+ public StringParsingCodec(TypeCodec<String> innerCodec, Class<T> javaType) {
43+ this(innerCodec, TypeToken.of(javaType));
44+ }
45+
46+ public StringParsingCodec(TypeCodec<String> innerCodec, TypeToken<T> javaType) {
47+ super(innerCodec.getCqlType(), javaType);
48+ this.innerCodec = innerCodec;
49+ }
50+
51+ @Override
52+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
53+ return value == null ? null : innerCodec.serialize(toString(value), protocolVersion);
54+ }
55+
56+ @Override
57+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
58+ String value = innerCodec.deserialize(bytes, protocolVersion);
59+ return value == null ? null : fromString(value);
60+ }
61+
62+ @Override
63+ public String format(T value) throws InvalidTypeException {
64+ return value == null ? null : innerCodec.format(toString(value));
65+ }
66+
67+ @Override
68+ public T parse(String value) throws InvalidTypeException {
69+ return value == null || value.isEmpty() || value.equals("NULL") ? null : fromString(innerCodec.parse(value));
70+ }
71+
72+ /**
73+ * Return the String representation of the given object;
74+ * no special CQL quoting should be applied here.
75+ * Null values should be accepted; in most cases, implementors
76+ * should return null for null inputs.
77+ *
78+ * @param value the value to convert into a string
79+ * @return the String representation of the given object
80+ */
81+ protected abstract String toString(T value);
82+
83+ /**
84+ * Parse the given string into an object;
85+ * no special CQL unquoting should be applied here.
86+ * Null values should be accepted; in most cases, implementors
87+ * should return null for null inputs.
88+ *
89+ * @param value the string to parse
90+ * @return the parsed object.
91+ */
92+ protected abstract T fromString(String value);
93+
94+}
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +1 −1
@@ -119,7 +119,7 @@
119119
120120 // Find the replica for a given partition key
121121 int testKey = 1;
122- Set<Host> replicas = metadata.getReplicas("test", TypeCodec.IntCodec.instance.serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersion()));
122+ Set<Host> replicas = metadata.getReplicas("test", TypeCodec.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersion()));
123123 assertThat(replicas).hasSize(1);
124124 Host replica = replicas.iterator().next();
125125
modified driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +1 −1
@@ -55,7 +55,7 @@
5555 assertEquals(v.getString(1), "a");
5656 assertEquals(v.getFloat(2), 1.0f);
5757
58- assertEquals(new TypeCodec.TupleCodec(t).format(v), "(1, 'a', 1.0)");
58+ assertEquals(TypeCodec.tuple(t).format(v), "(1, 'a', 1.0)");
5959 }
6060
6161 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java +0 −19
@@ -126,25 +126,6 @@
126126
127127 @Test(groups = "short")
128128 public void should_use_collection_codecs_with_prepared_statements_3() {
129- session.execute(session.prepare(insertQuery).bind()
130- .setInt(0, n_int)
131- .setObject(1, l_int)
132- .setObject(2, l_bigint)
133- .setObject(3, s_float)
134- .setObject(4, s_double)
135- .setObject(5, m_varint)
136- .setObject(6, m_decimal)
137- );
138- PreparedStatement ps = session.prepare(selectQuery);
139- ResultSet rows = session.execute(ps.bind()
140- .setInt(0, n_int)
141- );
142- Row row = rows.one();
143- assertRow(row);
144- }
145-
146- @Test(groups = "short")
147- public void should_use_collection_codecs_with_prepared_statements_4() {
148129 session.execute(session.prepare(insertQuery).bind()
149130 .setInt(0, n_int)
150131 .set(1, l_int, listOf(Integer.class))
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecEncapsulationIntegrationTest.java +6 −45
@@ -29,7 +29,6 @@
2929 import static com.google.common.collect.Lists.newArrayList;
3030 import static org.assertj.core.api.Assertions.assertThat;
3131
32-import com.datastax.driver.core.TypeCodec.*;
3332 import com.datastax.driver.core.exceptions.InvalidTypeException;
3433 import com.datastax.driver.core.querybuilder.BuiltStatement;
3534 import com.datastax.driver.core.querybuilder.QueryBuilder;
@@ -74,12 +73,12 @@
7473 return builder.withCodecRegistry(
7574 new CodecRegistry()
7675 .register(
77- new NumberBoxCodec<Integer>(IntCodec.instance),
78- new NumberBoxCodec<Long>(BigintCodec.instance),
79- new NumberBoxCodec<Float>(FloatCodec.instance),
80- new NumberBoxCodec<Double>(DoubleCodec.instance),
81- new NumberBoxCodec<BigInteger>(VarintCodec.instance),
82- new NumberBoxCodec<BigDecimal>(DecimalCodec.instance)
76+ new NumberBoxCodec<Integer>(TypeCodec.cint()),
77+ new NumberBoxCodec<Long>(TypeCodec.bigint()),
78+ new NumberBoxCodec<Float>(TypeCodec.cfloat()),
79+ new NumberBoxCodec<Double>(TypeCodec.cdouble()),
80+ new NumberBoxCodec<BigInteger>(TypeCodec.varint()),
81+ new NumberBoxCodec<BigDecimal>(TypeCodec.decimal())
8382 )
8483 );
8584 }
@@ -131,25 +130,6 @@
131130
132131 @Test(groups = "short")
133132 public void should_use_custom_codecs_with_prepared_statements_2() {
134- session.execute(session.prepare(insertQuery).bind()
135- .setObject(0, new NumberBox<Integer>(n_int))
136- .setObject(1, new NumberBox<Long>(n_bigint))
137- .setObject(2, new NumberBox<Float>(n_float))
138- .setObject(3, new NumberBox<Double>(n_double))
139- .setObject(4, new NumberBox<BigInteger>(n_varint))
140- .setObject(5, new NumberBox<BigDecimal>(n_decimal))
141- );
142- PreparedStatement ps = session.prepare(selectQuery);
143- ResultSet rows = session.execute(ps.bind()
144- .setObject(0, new NumberBox<Integer>(n_int))
145- .setObject(1, new NumberBox<Long>(n_bigint))
146- );
147- Row row = rows.one();
148- assertRow(row);
149- }
150-
151- @Test(groups = "short")
152- public void should_use_custom_codecs_with_prepared_statements_3() {
153133 session.execute(session.prepare(insertQuery).bind()
154134 .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {})
155135 .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {})
@@ -184,25 +164,6 @@
184164
185165 @Test(groups = "short")
186166 public void should_use_custom_codecs_with_built_statements_2() {
187- session.execute(session.prepare(insertStmt).bind()
188- .setObject(0, new NumberBox<Integer>(n_int))
189- .setObject(1, new NumberBox<Long>(n_bigint))
190- .setObject(2, new NumberBox<Float>(n_float))
191- .setObject(3, new NumberBox<Double>(n_double))
192- .setObject(4, new NumberBox<BigInteger>(n_varint))
193- .setObject(5, new NumberBox<BigDecimal>(n_decimal))
194- );
195- PreparedStatement ps = session.prepare(selectStmt);
196- ResultSet rows = session.execute(ps.bind()
197- .setObject(0, new NumberBox<Integer>(n_int))
198- .setObject(1, new NumberBox<Long>(n_bigint))
199- );
200- Row row = rows.one();
201- assertRow(row);
202- }
203-
204- @Test(groups = "short")
205- public void should_use_custom_codecs_with_built_statements_3() {
206167 session.execute(session.prepare(insertStmt).bind()
207168 .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {})
208169 .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {})
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecEnumIntegrationTest.java +3 −4
@@ -29,7 +29,6 @@
2929 import static com.google.common.collect.Sets.newHashSet;
3030 import static org.assertj.core.api.Assertions.assertThat;
3131
32-import com.datastax.driver.core.TypeCodec.EnumIntCodec;
3332 import com.datastax.driver.core.utils.CassandraVersion;
3433
3534 import static com.datastax.driver.core.DataType.cint;
@@ -79,10 +78,10 @@
7978
8079 @Override
8180 protected Cluster.Builder configure(Cluster.Builder builder) {
82- // explicitly register an EnumIntCodec for Foo enums
83- // Bar enums will use the default EnumStringCodec so it doesn't need to be explicitly registered.
8481 return builder.withCodecRegistry(
85- new CodecRegistry().register(new EnumIntCodec<Foo>(Foo.class))
82+ new CodecRegistry()
83+ .register(new EnumIntCodec<Foo>(Foo.class))
84+ .register(new EnumStringCodec<Bar>(Bar.class))
8685 );
8786 }
8887
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecJodaIntegrationTest.java +1 −1
@@ -151,7 +151,7 @@
151151 public void should_map_tuple_to_datetime() {
152152 // Register codec that maps DateTime <-> tuple<timestamp,varchar>
153153 TupleType dateWithTimeZoneType = cluster.getMetadata().newTupleType(timestamp(), varchar());
154- JodaCodecs.TimeZonePreservingDateTimeCodec dateTimeCodec = new JodaCodecs.TimeZonePreservingDateTimeCodec(new TypeCodec.TupleCodec(dateWithTimeZoneType));
154+ JodaCodecs.TimeZonePreservingDateTimeCodec dateTimeCodec = new JodaCodecs.TimeZonePreservingDateTimeCodec(TypeCodec.tuple(dateWithTimeZoneType));
155155 cluster.getConfiguration().getCodecRegistry().register(dateTimeCodec);
156156
157157 DateTime dateTime = DateTime.parse("2010-06-30T01:20+05:30");
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecJsonIntegrationTest.java +0 −9
@@ -135,15 +135,6 @@
135135 );
136136 Row row = rows.one();
137137 assertRow(row);
138- rows = session.execute(ps.bind()
139- .setString(0, notAJsonString)
140- // here we lost information about the java type of alice
141- // so the registry will look for a codec accepting varchar <-> ANY
142- // and will find jsonCodec because it is the only matching one
143- .setObject(1, alice)
144- );
145- row = rows.one();
146- assertRow(row);
147138 }
148139
149140 private void assertRow(Row row) {
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedCollectionsIntegrationTest.java +2 −16
@@ -125,20 +125,6 @@
125125
126126 @Test(groups = "short")
127127 public void should_work_with_prepared_statements_3() {
128- session.execute(session.prepare(insertQuery).bind()
129- .setInt(0, pk)
130- .setObject(1, v)
131- );
132- PreparedStatement ps = session.prepare(selectQuery);
133- ResultSet rows = session.execute(ps.bind()
134- .setInt(0, pk)
135- );
136- Row row = rows.one();
137- assertRow(row);
138- }
139-
140- @Test(groups = "short")
141- public void should_work_with_prepared_statements_4() {
142128 session.execute(session.prepare(insertQuery).bind()
143129 .setInt(0, pk)
144130 .set(1, v, listType)
@@ -202,12 +188,12 @@
202188
203189 @Override
204190 public ByteBuffer serialize(MyInt value, ProtocolVersion protocolVersion) throws InvalidTypeException {
205- return IntCodec.instance.serialize(value.i, protocolVersion);
191+ return TypeCodec.cint().serialize(value.i, protocolVersion);
206192 }
207193
208194 @Override
209195 public MyInt deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
210- return new MyInt(IntCodec.instance.deserialize(bytes, protocolVersion));
196+ return new MyInt(TypeCodec.cint().deserialize(bytes, protocolVersion));
211197 }
212198
213199 @Override
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNumbersIntegrationTest.java +0 −19
@@ -94,25 +94,6 @@
9494
9595 @Test(groups = "short")
9696 public void should_use_default_codecs_with_prepared_statements_3() {
97- session.execute(session.prepare(insertQuery).bind()
98- .setObject(0, n_int)
99- .setObject(1, n_bigint)
100- .setObject(2, n_float)
101- .setObject(3, n_double)
102- .setObject(4, n_varint)
103- .setObject(5, n_decimal)
104- );
105- PreparedStatement ps = session.prepare(selectQuery);
106- ResultSet rows = session.execute(ps.bind()
107- .setInt(0, n_int)
108- .setLong(1, n_bigint)
109- );
110- Row row = rows.one();
111- assertRow(row);
112- }
113-
114- @Test(groups = "short")
115- public void should_use_default_codecs_with_prepared_statements_4() {
11697 session.execute(session.prepare(insertQuery).bind()
11798 .set(0, n_int, Integer.class)
11899 .set(1, n_bigint, Long.class)
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java +6 −13
@@ -67,20 +67,13 @@
6767 );
6868 session.execute(
6969 ps.bind()
70- .setObject(0, 42)
71- .setObject(1, newArrayList(42))
72- .setObject(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
73- );
74- session.execute(
75- ps.bind()
76- .setObject(0, "42")
77- .setObject(1, newArrayList("42"))
78- .setObject(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
70+ .setString(0, "42")
71+ .setList(1, newArrayList("42"))
72+ .setString(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
7973 );
8074 ps = session.prepare(selectQuery);
8175 assertRow(session.execute(ps.bind().setInt(0, 42)).one());
82- assertRow(session.execute(ps.bind().setObject(0, 42)).one());
83- assertRow(session.execute(ps.bind().setObject(0, "42")).one());
76+ assertRow(session.execute(ps.bind().setString(0, "42")).one());
8477 }
8578
8679 private void assertRow(Row row) {
@@ -104,12 +97,12 @@
10497
10598 @Override
10699 public ByteBuffer serialize(String value, ProtocolVersion protocolVersion) throws InvalidTypeException {
107- return IntCodec.instance.serialize(value == null ? null : Integer.parseInt(value), protocolVersion);
100+ return TypeCodec.cint().serialize(value == null ? null : Integer.parseInt(value), protocolVersion);
108101 }
109102
110103 @Override
111104 public String deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
112- Integer i = IntCodec.instance.deserialize(bytes, protocolVersion);
105+ Integer i = TypeCodec.cint().deserialize(bytes, protocolVersion);
113106 return i == null ? null : Integer.toString(i);
114107 }
115108
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java +24 −21
@@ -31,7 +31,6 @@
3131 import static com.google.common.collect.Lists.newArrayList;
3232 import static org.testng.Assert.fail;
3333
34-import com.datastax.driver.core.TypeCodec.UDTCodec;
3534 import com.datastax.driver.core.UserType.Field;
3635 import com.datastax.driver.core.exceptions.CodecNotFoundException;
3736 import com.datastax.driver.core.exceptions.InvalidTypeException;
@@ -45,10 +44,7 @@
4544
4645 public static final DataType CUSTOM_FOO = DataType.custom("com.example.FooBar");
4746
48- public static final TypeCodec.CustomCodec CUSTOM_FOO_CODEC = new TypeCodec.CustomCodec(CUSTOM_FOO);
49-
50- private CodecRegistry codecRegistry = new CodecRegistry()
51- .register(CUSTOM_FOO_CODEC);
47+ private CodecRegistry codecRegistry = new CodecRegistry();
5248
5349 @Test(groups = "unit")
5450 public void testCustomList() throws Exception {
@@ -117,8 +113,8 @@
117113
118114 @Test(groups = "unit")
119115 public void test_ascii_vs_utf8() {
120- TypeCodec.AsciiCodec asciiCodec = TypeCodec.AsciiCodec.instance;
121- TypeCodec.VarcharCodec utf8Codec = TypeCodec.VarcharCodec.instance;
116+ TypeCodec<String> asciiCodec = TypeCodec.ascii();
117+ TypeCodec<String> utf8Codec = TypeCodec.varchar();
122118 String ascii = "The quick brown fox jumps over the lazy dog!";
123119 String utf8 = "Dès Noël, où un zéphyr haï me vêt de glaçons würmiens, je dîne d’exquis rôtis de bœuf au kir à l’aÿ d’âge mûr & cætera!";
124120 assertThat(asciiCodec)
@@ -143,17 +139,17 @@
143139
144140 @Test(groups = "unit")
145141 public void test_varchar_vs_text() {
146- assertThat(TypeCodec.VarcharCodec.instance)
142+ assertThat(TypeCodec.varchar())
147143 .accepts(String.class)
148144 .accepts(varchar())
149145 .accepts(text());
150- assertThat(new TypeCodec.ListCodec<String>(TypeCodec.VarcharCodec.instance))
146+ assertThat(TypeCodec.list(TypeCodec.varchar()))
151147 .accepts(list(varchar()))
152148 .accepts(list(text()));
153- assertThat(new TypeCodec.SetCodec<String>(TypeCodec.VarcharCodec.instance))
149+ assertThat(TypeCodec.set(TypeCodec.varchar()))
154150 .accepts(set(varchar()))
155151 .accepts(set(text()));
156- assertThat(new TypeCodec.MapCodec<String, String>(TypeCodec.VarcharCodec.instance, TypeCodec.VarcharCodec.instance))
152+ assertThat(TypeCodec.map(TypeCodec.varchar(), TypeCodec.varchar()))
157153 .accepts(map(varchar(), varchar()))
158154 .accepts(map(varchar(), text()))
159155 .accepts(map(text(), varchar()))
@@ -162,7 +158,7 @@
162158 TupleType t2 = new TupleType(newArrayList(text(), varchar()), V3, new CodecRegistry());
163159 TupleType t3 = new TupleType(newArrayList(varchar(), text()), V3, new CodecRegistry());
164160 TupleType t4 = new TupleType(newArrayList(text(), text()), V3, new CodecRegistry());
165- assertThat(new TypeCodec.TupleCodec(t1))
161+ assertThat(TypeCodec.tuple(t1))
166162 .accepts(t2)
167163 .accepts(t3)
168164 .accepts(t4);
@@ -170,7 +166,7 @@
170166 UserType u2 = new UserType("ks", "table", newArrayList(new Field("f1", text()), new Field("f2", varchar())), V3, new CodecRegistry());
171167 UserType u3 = new UserType("ks", "table", newArrayList(new Field("f1", varchar()), new Field("f2", text())), V3, new CodecRegistry());
172168 UserType u4 = new UserType("ks", "table", newArrayList(new Field("f1", text()), new Field("f2", text())), V3, new CodecRegistry());
173- assertThat(new UDTCodec(u1))
169+ assertThat(TypeCodec.userType(u1))
174170 .accepts(u2)
175171 .accepts(u3)
176172 .accepts(u4);
@@ -178,7 +174,7 @@
178174
179175 @Test(groups = "unit")
180176 public void test_enum() {
181- TypeCodec.EnumStringCodec<FooBarQix> codec = new TypeCodec.EnumStringCodec<FooBarQix>(FooBarQix.class);
177+ EnumStringCodec<FooBarQix> codec = new EnumStringCodec<FooBarQix>(FooBarQix.class);
182178 assertThat(codec)
183179 .canSerialize(FooBarQix.FOO);
184180 }
@@ -191,7 +187,10 @@
191187 assertThat(codecRegistry.codecFor(cint(), A.class)).isNotNull().isSameAs(aCodec);
192188 // inheritance works: B is assignable to A
193189 assertThat(codecRegistry.codecFor(cint(), B.class)).isNotNull().isSameAs(aCodec);
194- assertThat(codecRegistry.codecFor(list(cint()), new TypeToken<List<A>>(){})).isNotNull().isEqualTo(new TypeCodec.ListCodec<A>(aCodec));
190+ TypeCodec<List<A>> expected = TypeCodec.list(aCodec);
191+ TypeCodec<List<A>> actual = codecRegistry.codecFor(list(cint()), new TypeToken<List<A>>(){});
192+ assertThat(actual.getCqlType()).isEqualTo(expected.getCqlType());
193+ assertThat(actual.getJavaType()).isEqualTo(expected.getJavaType());
195194 // cannot work: List<B> is not assignable to List<A>
196195 try {
197196 codecRegistry.codecFor(list(cint()), new TypeToken<List<B>>(){});
@@ -215,7 +214,11 @@
215214 } catch (CodecNotFoundException e) {
216215 // ok
217216 }
218- assertThat(codecRegistry.codecFor(list(cint()), new TypeToken<List<B>>(){})).isNotNull().isEqualTo(new TypeCodec.ListCodec<B>(bCodec));
217+ TypeCodec<List<B>> expectedB = TypeCodec.list(bCodec);
218+ TypeCodec<List<B>> actualB = codecRegistry.codecFor(list(cint()), new TypeToken<List<B>>() {
219+ });
220+ assertThat(actualB.getCqlType()).isEqualTo(expectedB.getCqlType());
221+ assertThat(actualB.getJavaType()).isEqualTo(expectedB.getJavaType());
219222 }
220223
221224
@@ -240,7 +243,7 @@
240243 ), ProtocolVersion.NEWEST_SUPPORTED, codecRegistry);
241244 UDTValue expected = udt.newValue();
242245 expected.setString("t", null);
243- expected.setObject("i", null);
246+ expected.setToNull("i");
244247 expected.setList("l", null);
245248
246249 UDTValue actual = codecRegistry.codecFor(udt, UDTValue.class).deserialize(ByteBuffer.allocate(0), ProtocolVersion.NEWEST_SUPPORTED);
@@ -251,10 +254,10 @@
251254
252255 private class ListVarcharToListListInteger extends TypeCodec<List<List<Integer>>> {
253256
254- private final ListCodec<String> codec = new ListCodec<String>(VarcharCodec.instance);
257+ private final TypeCodec<List<String>> codec = TypeCodec.list(TypeCodec.varchar());
255258
256259 protected ListVarcharToListListInteger() {
257- super(list(varchar()), listOf(listOf(Integer.class)));
260+ super(DataType.list(DataType.varchar()), listOf(listOf(Integer.class)));
258261 }
259262
260263 @Override
@@ -357,7 +360,7 @@
357360 class ACodec extends TypeCodec<A> {
358361
359362 protected ACodec() {
360- super(cint(), A.class);
363+ super(DataType.cint(), A.class);
361364 }
362365
363366 @Override
@@ -385,7 +388,7 @@
385388 class BCodec extends TypeCodec<B> {
386389
387390 protected BCodec() {
388- super(cint(), B.class);
391+ super(DataType.cint(), B.class);
389392 }
390393
391394 @Override
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTupleIntegrationTest.java +4 −16
@@ -69,11 +69,6 @@
6969 rows = session.execute(selectQuery, uuid);
7070 row = rows.one();
7171 assertRow(row);
72- // bound with setObject
73- session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setObject(2, locationValue));
74- rows = session.execute(selectQuery, uuid);
75- row = rows.one();
76- assertRow(row);
7772 }
7873
7974 @Test(groups = "short")
@@ -95,11 +90,6 @@
9590 rows = session.execute(selectQuery, uuid);
9691 row = rows.one();
9792 assertPartialRow(row);
98- // bound with setObject
99- session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setObject(2, partialLocationValueInserted));
100- rows = session.execute(selectQuery, uuid);
101- row = rows.one();
102- assertPartialRow(row);
10393 }
10494
10595 @Test(groups = "short")
@@ -114,7 +104,7 @@
114104 Session session = cluster.connect(keyspace);
115105 setUpTupleTypes(cluster);
116106 codecRegistry
117- .register(new LocationCodec(new TypeCodec.TupleCodec(locationType)))
107+ .register(new LocationCodec(TypeCodec.tuple(locationType)))
118108 ;
119109 session.execute(insertQuery, uuid, "John Doe", locationValue);
120110 ResultSet rows = session.execute(selectQuery, uuid);
@@ -150,7 +140,7 @@
150140 Session session = cluster.connect(keyspace);
151141 setUpTupleTypes(cluster);
152142 codecRegistry
153- .register(new LocationCodec(new TypeCodec.TupleCodec(locationType)))
143+ .register(new LocationCodec(TypeCodec.tuple(locationType)))
154144 ;
155145 session.execute(insertQuery, uuid, "John Doe", partialLocationValueInserted);
156146 ResultSet rows = session.execute(selectQuery, uuid);
@@ -211,7 +201,7 @@
211201 partialLocation = new Location(37.387224f, 0.0f);
212202 }
213203
214- static class LocationCodec extends TypeCodec.MappingCodec<Location, TupleValue> {
204+ static class LocationCodec extends MappingCodec<Location, TupleValue> {
215205
216206 private final TupleType tupleType;
217207
@@ -251,9 +241,7 @@
251241
252242 Location location = (Location)o;
253243
254- if (Float.compare(location.latitude, latitude) != 0)
255- return false;
256- return Float.compare(location.longitude, longitude) == 0;
244+ return Float.compare(location.latitude, latitude) == 0 && Float.compare(location.longitude, longitude) == 0;
257245
258246 }
259247
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecUDTIntegrationTest.java +5 −10
@@ -70,11 +70,6 @@
7070 rows = session.execute(selectQuery, uuid);
7171 row = rows.one();
7272 assertRow(row);
73- // bound with setObject
74- session.execute(ps.bind().setUUID(0, uuid).setString(1, "John Doe").setObject(2, addressValue));
75- rows = session.execute(selectQuery, uuid);
76- row = rows.one();
77- assertRow(row);
7873 }
7974
8075 @Test(groups = "short")
@@ -88,8 +83,8 @@
8883 try {
8984 Session session = cluster.connect(keyspace);
9085 setUpUserTypes(cluster);
91- TypeCodec<UDTValue> addressTypeCodec = new TypeCodec.UDTCodec(addressType);
92- TypeCodec<UDTValue> phoneTypeCodec = new TypeCodec.UDTCodec(phoneType);
86+ TypeCodec<UDTValue> addressTypeCodec = TypeCodec.userType(addressType);
87+ TypeCodec<UDTValue> phoneTypeCodec = TypeCodec.userType(phoneType);
9388 codecRegistry
9489 .register(new AddressCodec(addressTypeCodec, Address.class))
9590 .register(new PhoneCodec(phoneTypeCodec, Phone.class))
@@ -136,14 +131,14 @@
136131 .setSet("tags", phone1.tags);
137132 UDTValue phone2Value = phoneType.newValue()
138133 .setString("number", phone2.number)
139- .setObject("tags", phone2.tags);
134+ .setSet("tags", phone2.tags);
140135 addressValue = addressType.newValue()
141136 .setString("street", address.street)
142137 .setInt(1, address.zipcode)
143138 .setList("phones", Lists.newArrayList(phone1Value, phone2Value));
144139 }
145140
146- static class AddressCodec extends TypeCodec.MappingCodec<Address, UDTValue> {
141+ static class AddressCodec extends MappingCodec<Address, UDTValue> {
147142
148143 private final UserType userType;
149144
@@ -163,7 +158,7 @@
163158 }
164159 }
165160
166- static class PhoneCodec extends TypeCodec.MappingCodec<Phone, UDTValue> {
161+ static class PhoneCodec extends MappingCodec<Phone, UDTValue> {
167162
168163 private final UserType userType;
169164
modified driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsTest.java +3 −4
@@ -24,7 +24,6 @@
2424 import static org.testng.Assert.assertEquals;
2525 import static org.testng.Assert.assertTrue;
2626
27-import com.datastax.driver.core.DataType;
2827 import com.datastax.driver.core.ProtocolVersion;
2928 import com.datastax.driver.core.TypeCodec;
3029
@@ -111,9 +110,9 @@
111110 }
112111
113112 private static void assertWithin(UUID uuid, UUID lowerBound, UUID upperBound) {
114- ByteBuffer uuidBytes = TypeCodec.UUIDCodec.instance.serialize(uuid, ProtocolVersion.V1);
115- ByteBuffer lb = TypeCodec.UUIDCodec.instance.serialize(lowerBound, ProtocolVersion.V1);
116- ByteBuffer ub = TypeCodec.UUIDCodec.instance.serialize(upperBound, ProtocolVersion.V1);
113+ ByteBuffer uuidBytes = TypeCodec.uuid().serialize(uuid, ProtocolVersion.V1);
114+ ByteBuffer lb = TypeCodec.uuid().serialize(lowerBound, ProtocolVersion.V1);
115+ ByteBuffer ub = TypeCodec.uuid().serialize(upperBound, ProtocolVersion.V1);
117116 assertTrue(compareTimestampBytes(lb, uuidBytes) <= 0);
118117 assertTrue(compareTimestampBytes(ub, uuidBytes) >= 0);
119118 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCustomCodecTest.java +35 −6
@@ -258,7 +258,7 @@
258258 @PartitionKey
259259 private int i;
260260
261- @Column(codec = TypeCodec.StringCodec.class)
261+ @Column(codec = NoDefaultConstructorCodec.class)
262262 private long l;
263263
264264 public int getI() {
@@ -345,7 +345,7 @@
345345
346346 @Query("update data1 set l = :l where i = :i")
347347 void setL(@Param("i") int i,
348- @Param(value = "l", codec = TypeCodec.StringCodec.class) long l);
348+ @Param(value = "l", codec = NoDefaultConstructorCodec.class) long l);
349349 }
350350
351351 @Accessor
@@ -469,12 +469,12 @@
469469
470470 @Override
471471 public ByteBuffer serialize(CustomInt value, ProtocolVersion protocolVersion) throws InvalidTypeException {
472- return TypeCodec.IntCodec.instance.serialize(value.value, protocolVersion);
472+ return TypeCodec.cint().serialize(value.value, protocolVersion);
473473 }
474474
475475 @Override
476476 public CustomInt deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
477- Integer i = TypeCodec.IntCodec.instance.deserialize(bytes, protocolVersion);
477+ Integer i = TypeCodec.cint().deserialize(bytes, protocolVersion);
478478 return new CustomInt(i);
479479 }
480480
@@ -518,12 +518,12 @@
518518
519519 @Override
520520 public ByteBuffer serialize(CustomLong value, ProtocolVersion protocolVersion) throws InvalidTypeException {
521- return TypeCodec.BigintCodec.instance.serialize(value.value, protocolVersion);
521+ return TypeCodec.bigint().serialize(value.value, protocolVersion);
522522 }
523523
524524 @Override
525525 public CustomLong deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
526- Long l = TypeCodec.BigintCodec.instance.deserialize(bytes, protocolVersion);
526+ Long l = TypeCodec.bigint().deserialize(bytes, protocolVersion);
527527 return new CustomLong(l);
528528 }
529529
@@ -555,4 +555,33 @@
555555 super(registry.codecFor(DataType.text(), String.class));
556556 }
557557 }
558+
559+ private static class NoDefaultConstructorCodec extends TypeCodec<String> {
560+
561+ public NoDefaultConstructorCodec(DataType cqlType, Class<String> javaClass) {
562+ super(cqlType, javaClass);
563+ }
564+
565+ @Override
566+ public ByteBuffer serialize(String value, ProtocolVersion protocolVersion) throws InvalidTypeException {
567+ return null;
568+ }
569+
570+ @Override
571+ public String deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
572+ return null;
573+ }
574+
575+ @Override
576+ public String parse(String value) throws InvalidTypeException {
577+ return null;
578+ }
579+
580+ @Override
581+ public String format(String value) throws InvalidTypeException {
582+ return null;
583+ }
584+
585+ }
586+
558587 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +2 −2
@@ -287,9 +287,9 @@
287287
288288 // Create a user.
289289 session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', zip_code: 89898, phones: {'8675309'}} " +
290- " WHERE user_id=" + TypeCodec.UUIDCodec.instance.format(userId));
290+ " WHERE user_id=" + TypeCodec.uuid().format(userId));
291291 session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', zip_code: 49553, phones: {'8675039'}} " +
292- " WHERE user_Id=" + TypeCodec.UUIDCodec.instance.format(userId));
292+ " WHERE user_Id=" + TypeCodec.uuid().format(userId));
293293
294294 // Get the user.
295295 Row row = session.execute("select * from users where user_id=?", userId).one();
modified features/custom_codecs/README.md +84 −29
@@ -61,53 +61,80 @@
6161 /**
6262 * A simple Json codec.
6363 */
64-public class JsonCodec<T> extends TypeCodec.StringParsingCodec<T> {
64+public class JsonCodec<T> extends TypeCodec<T> {
6565
66- private final ObjectMapper objectMapper;
66+ private final ObjectMapper objectMapper = new ObjectMapper();
6767
68- public JsonCodec(Class<T> javaType, ObjectMapper objectMapper) {
69- super(javaType);
70- this.objectMapper = objectMapper;
68+ public JsonCodec(Class<T> javaType) {
69+ super(DataType.varchar(), javaType);
7170 }
7271
7372 @Override
74- @SuppressWarnings("unchecked")
75- public T fromString(String value) {
73+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
7674 if (value == null)
7775 return null;
7876 try {
79- return (T) objectMapper.readValue(value, getJavaType().getRawType());
77+ return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
78+ } catch (JsonProcessingException e) {
79+ throw new InvalidTypeException(e.getMessage(), e);
80+ }
81+ }
82+
83+ @Override
84+ @SuppressWarnings("unchecked")
85+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
86+ if (bytes == null)
87+ return null;
88+ try {
89+ byte[] b = new byte[bytes.remaining()];
90+ bytes.duplicate().get(b);
91+ return (T)objectMapper.readValue(b, toJacksonJavaType());
8092 } catch (IOException e) {
8193 throw new InvalidTypeException(e.getMessage(), e);
8294 }
8395 }
8496
8597 @Override
86- public String toString(T value) {
98+ public String format(T value) throws InvalidTypeException {
8799 if (value == null)
100+ return NULL;
101+ String json;
102+ try {
103+ json = objectMapper.writeValueAsString(value);
104+ } catch (IOException e) {
105+ throw new InvalidTypeException(e.getMessage(), e);
106+ }
107+ return '\'' + json.replace("\'", "''") + '\'';
108+ }
109+
110+ @Override
111+ @SuppressWarnings("unchecked")
112+ public T parse(String value) throws InvalidTypeException {
113+ if (value == null || value.isEmpty() || value.equals(NULL))
88114 return null;
115+ if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
116+ throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
117+ String json = value.substring(1, value.length() - 1).replace("''", "'");
89118 try {
90- return objectMapper.writeValueAsString(value);
91- } catch (JsonProcessingException e) {
119+ return (T)objectMapper.readValue(json, toJacksonJavaType());
120+ } catch (IOException e) {
92121 throw new InvalidTypeException(e.getMessage(), e);
93122 }
94123 }
124+
125+ protected JavaType toJacksonJavaType() {
126+ return TypeFactory.defaultInstance().constructType(getJavaType().getType());
127+ }
128+
95129 }
96130 ```
97131
98-As you can see, the driver already provides a convenient base class: [StringParsingCodec][StringParsingCodec].
99-
100132 A few implementation guidelines:
101133
102134 * Your codecs should be thread-safe, or better yet, immutable;
103135 * Your codecs should be fast: do not forget that codecs are executed often and are usually very "hot" pieces of code;
104136 * Your codecs should never block.
105137
106-Note: the code above is an example and is not particularly efficient;
107-it suffers from the overhead of deserializing raw bytes into a String,
108-to only then parse the String into an object.
109-More advanced solutions that read the underlying byte stream directly are possible.
110-
111138 The second step is to register your codec with a `CodecRegistry` instance:
112139
113140 ```java
@@ -242,32 +269,59 @@
242269 }
243270 ```
244271
245-First of all, create a codec for this class:
272+First of all, create a codec that knows how to serialize this class; one possible solution
273+(but not necessarily the most efficient one) would be to convert `Address` instances into `UDTValue`
274+instances, then serialize them with another codec:
275+
246276
247277 ```java
248-public class AddressCodec extends TypeCodec.MappingCodec<Address, UDTValue> {
278+public class AddressCodec extends TypeCodec<Address> {
249279
280+ private final TypeCodec<UDTValue> innerCodec;
281+
250282 private final UserType userType;
251283
252284 public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) {
253- super(innerCodec, javaType);
254- userType = (UserType) innerCodec.getCqlType();
285+ super(innerCodec.getCqlType(), javaType);
286+ this.innerCodec = innerCodec;
287+ this.userType = (UserType)innerCodec.getCqlType();
288+ }
289+
290+ @Override
291+ public ByteBuffer serialize(Address value, ProtocolVersion protocolVersion) throws InvalidTypeException {
292+ return innerCodec.serialize(toUDTValue(value), protocolVersion);
293+ }
294+
295+ @Override
296+ public Address deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
297+ return toAddress(innerCodec.deserialize(bytes, protocolVersion));
255298 }
256299
257300 @Override
258- protected Address deserialize(UDTValue value) {
259- return value == null ? null : new Address(value.getString("street"), value.getInt("zipcode"));
301+ public Address parse(String value) throws InvalidTypeException {
302+ return value == null || value.isEmpty() || value.equals(NULL) ? null : toAddress(innerCodec.parse(value));
260303 }
261304
262305 @Override
263- protected UDTValue serialize(Address address) {
264- return address == null ? null : userType.newValue().setString("street", address.getStreet()).setInt("zipcode", address.getZipcode());
306+ public String format(Address value) throws InvalidTypeException {
307+ return value == null ? null : innerCodec.format(toUDTValue(value));
308+ }
309+
310+ protected Address toAddress(UDTValue value) {
311+ return value == null ? null : new Address(
312+ value.getString("street"),
313+ value.getInt("zipcode")
314+ );
315+ }
316+
317+ protected UDTValue toUDTValue(Address value) {
318+ return value == null ? null : userType.newValue()
319+ .setString("street", value.getStreet())
320+ .setInt("zipcode", value.getZipcode());
265321 }
266322 }
267323 ```
268324
269-Again, the driver provides a convenient base class: [MappingCodec].
270-
271325 Now (and only if you intend to use your own `CodecRegistry`),
272326 create it and register it on your `Cluster` instance:
273327
@@ -284,6 +338,7 @@
284338
285339 ```java
286340 UserType addressType = cluster.getMetadata().getKeyspace(...).getUserType("address");
341+TypeCodec<UDTValue> addressTypeCodec = codecRegistry.codecFor(addressType);
287342 ```
288343
289344 And finally, register your `AddressCodec` with the `CodecRegistry`. Note that
@@ -291,7 +346,7 @@
291346 user type values:
292347
293348 ```java
294-AddressCodec addressCodec = new AddressCodec(new TypeCodec.UDTCodec(addressType), Address.class);
349+AddressCodec addressCodec = new AddressCodec(addressTypeCodec, Address.class);
295350 codecRegistry.register(addressCodec);
296351 ```
297352