Elffuss BraidHub

kikocis/java-driver public

Merge pull request #485 from datastax/java931

TypeCodec improvements (JAVA-931)
Changeset7f3ccb3b2b46b9ddffd92dd350318dc9359104363bdac1b5011195dac6111684
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-10-14 22:38 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-10-14 22:38 +02:00
Parents16505233fda0, 2764f2e0c54f

Browse the files at this changeset

51 files changed

modified changelog/README.md +4 −0
@@ -11,6 +11,10 @@
1111 - [new feature] Add BoundStatement#unset (JAVA-930)
1212 - [bug] Make table metadata options class visible (JAVA-946)
1313 - [bug] Add crcCheckChance to TableOptionsMetadata#equals/hashCode (JAVA-939)
14+- [bug] Make TypeCodec return mutable collections (JAVA-922)
15+- [improvement] Limit visibility of codec internals (JAVA-932)
16+- [improvement] Warn if a custom codec collides with an existing one (JAVA-934)
17+- [improvement] Allow typed getters/setters to target any CQL type (JAVA-940)
1418
1519
1620 ### 3.0.0-alpha3
modified driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java +3 −58
@@ -27,7 +27,6 @@
2727 import static com.datastax.driver.core.CodecUtils.listOf;
2828 import static com.datastax.driver.core.CodecUtils.mapOf;
2929 import static com.datastax.driver.core.CodecUtils.setOf;
30-import static com.datastax.driver.core.DataType.Name.*;
3130
3231 abstract class AbstractAddressableByIndexData<T extends SettableByIndexData<T>> extends AbstractGettableByIndexData implements SettableByIndexData<T> {
3332
@@ -49,7 +48,6 @@
4948 }
5049
5150 public T setBool(int i, boolean v) {
52- checkType(i, BOOLEAN);
5351 TypeCodec<Boolean> codec = codecFor(i, Boolean.class);
5452 ByteBuffer bb;
5553 if(codec instanceof TypeCodec.PrimitiveBooleanCodec)
@@ -60,7 +58,6 @@
6058 }
6159
6260 public T setByte(int i, byte v) {
63- checkType(i, TINYINT);
6461 TypeCodec<Byte> codec = codecFor(i, Byte.class);
6562 ByteBuffer bb;
6663 if(codec instanceof TypeCodec.PrimitiveByteCodec)
@@ -71,7 +68,6 @@
7168 }
7269
7370 public T setShort(int i, short v) {
74- checkType(i, SMALLINT);
7571 TypeCodec<Short> codec = codecFor(i, Short.class);
7672 ByteBuffer bb;
7773 if(codec instanceof TypeCodec.PrimitiveShortCodec)
@@ -82,7 +78,6 @@
8278 }
8379
8480 public T setInt(int i, int v) {
85- checkType(i, INT);
8681 TypeCodec<Integer> codec = codecFor(i, Integer.class);
8782 ByteBuffer bb;
8883 if(codec instanceof TypeCodec.PrimitiveIntCodec)
@@ -93,7 +88,6 @@
9388 }
9489
9590 public T setLong(int i, long v) {
96- checkType(i, BIGINT, COUNTER);
9791 TypeCodec<Long> codec = codecFor(i, Long.class);
9892 ByteBuffer bb;
9993 if(codec instanceof TypeCodec.PrimitiveLongCodec)
@@ -104,17 +98,14 @@
10498 }
10599
106100 public T setTimestamp(int i, Date v) {
107- checkType(i, TIMESTAMP);
108101 return setValue(i, codecFor(i, Date.class).serialize(v, protocolVersion));
109102 }
110103
111104 public T setDate(int i, LocalDate v) {
112- checkType(i, DATE);
113105 return setValue(i, codecFor(i, LocalDate.class).serialize(v, protocolVersion));
114106 }
115107
116108 public T setTime(int i, long v) {
117- checkType(i, TIME);
118109 TypeCodec<Long> codec = codecFor(i, Long.class);
119110 ByteBuffer bb;
120111 if(codec instanceof TypeCodec.PrimitiveLongCodec)
@@ -125,7 +116,6 @@
125116 }
126117
127118 public T setFloat(int i, float v) {
128- checkType(i, FLOAT);
129119 TypeCodec<Float> codec = codecFor(i, Float.class);
130120 ByteBuffer bb;
131121 if(codec instanceof TypeCodec.PrimitiveFloatCodec)
@@ -136,7 +126,6 @@
136126 }
137127
138128 public T setDouble(int i, double v) {
139- checkType(i, DOUBLE);
140129 TypeCodec<Double> codec = codecFor(i, Double.class);
141130 ByteBuffer bb;
142131 if(codec instanceof TypeCodec.PrimitiveDoubleCodec)
@@ -147,12 +136,10 @@
147136 }
148137
149138 public T setString(int i, String v) {
150- checkType(i, VARCHAR, TEXT, ASCII);
151139 return setValue(i, codecFor(i, String.class).serialize(v, protocolVersion));
152140 }
153141
154142 public T setBytes(int i, ByteBuffer v) {
155- checkType(i, BLOB);
156143 return setValue(i, codecFor(i, ByteBuffer.class).serialize(v, protocolVersion));
157144 }
158145
@@ -161,37 +148,24 @@
161148 }
162149
163150 public T setVarint(int i, BigInteger v) {
164- checkType(i, VARINT);
165151 return setValue(i, codecFor(i, BigInteger.class).serialize(v, protocolVersion));
166152 }
167153
168154 public T setDecimal(int i, BigDecimal v) {
169- checkType(i, DECIMAL);
170155 return setValue(i, codecFor(i, BigDecimal.class).serialize(v, protocolVersion));
171156 }
172157
173158 public T setUUID(int i, UUID v) {
174- checkType(i, UUID, TIMEUUID);
175159 return setValue(i, codecFor(i, UUID.class).serialize(v, protocolVersion));
176160 }
177161
178162 public T setInet(int i, InetAddress v) {
179- checkType(i, INET);
180163 return setValue(i, codecFor(i, InetAddress.class).serialize(v, protocolVersion));
181164 }
182165
183166 @SuppressWarnings("unchecked")
184167 public <E> T setList(int i, List<E> v) {
185- checkType(i, LIST);
186- if(v == null || v.isEmpty()) {
187- // no runtime inspection possible, rely on the underlying metadata
188- return setValue(i, codecFor(i).serialize(v, protocolVersion));
189- } else {
190- // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java type
191- DataType eltCqlType = getType(i).getTypeArguments().get(0);
192- TypeToken<E> eltJavaType = getCodecRegistry().codecFor(eltCqlType, v.iterator().next()).getJavaType();
193- return setValue(i, codecFor(i, listOf(eltJavaType)).serialize(v, protocolVersion));
194- }
168+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
195169 }
196170
197171 @Override
@@ -206,19 +180,7 @@
206180
207181 @SuppressWarnings("unchecked")
208182 public <K, V> T setMap(int i, Map<K, V> v) {
209- checkType(i, MAP);
210- if(v == null || v.isEmpty()) {
211- // no runtime inspection possible, rely on the underlying metadata
212- return setValue(i, codecFor(i).serialize(v, protocolVersion));
213- } else {
214- // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java types for keys and values
215- DataType keysCqlType = getType(i).getTypeArguments().get(0);
216- DataType valuesCqlType = getType(i).getTypeArguments().get(1);
217- Map.Entry<K, V> entry = v.entrySet().iterator().next();
218- TypeToken<K> keysType = getCodecRegistry().codecFor(keysCqlType, entry.getKey()).getJavaType();
219- TypeToken<V> valuesType = getCodecRegistry().codecFor(valuesCqlType, entry.getValue()).getJavaType();
220- return setValue(i, codecFor(i, mapOf(keysType, valuesType)).serialize(v, protocolVersion));
221- }
183+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
222184 }
223185
224186 @Override
@@ -233,16 +195,7 @@
233195
234196 @SuppressWarnings("unchecked")
235197 public <E> T setSet(int i, Set<E> v) {
236- checkType(i, SET);
237- if(v == null || v.isEmpty()) {
238- // no runtime inspection possible, rely on the underlying metadata
239- return setValue(i, codecFor(i).serialize(v, protocolVersion));
240- } else {
241- // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java type
242- DataType eltCqlType = getType(i).getTypeArguments().get(0);
243- TypeToken<E> eltJavaType = getCodecRegistry().codecFor(eltCqlType, v.iterator().next()).getJavaType();
244- return setValue(i, codecFor(i, setOf(eltJavaType)).serialize(v, protocolVersion));
245- }
198+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
246199 }
247200
248201 @Override
@@ -256,21 +209,13 @@
256209 }
257210
258211 public T setUDTValue(int i, UDTValue v) {
259- checkType(i, UDT);
260212 return setValue(i, codecFor(i, UDTValue.class).serialize(v, protocolVersion));
261213 }
262214
263215 public T setTupleValue(int i, TupleValue v) {
264- checkType(i, TUPLE);
265216 return setValue(i, codecFor(i, TupleValue.class).serialize(v, protocolVersion));
266217 }
267218
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-
274219 @Override
275220 public <V> T set(int i, V v, Class<V> targetClass) {
276221 return set(i, v, codecFor(i, targetClass));
modified driver-core/src/main/java/com/datastax/driver/core/AbstractData.java +45 −66
@@ -27,7 +27,6 @@
2727 import static com.datastax.driver.core.CodecUtils.listOf;
2828 import static com.datastax.driver.core.CodecUtils.mapOf;
2929 import static com.datastax.driver.core.CodecUtils.setOf;
30-import static com.datastax.driver.core.DataType.Name.*;
3130
3231 // We don't want to expose this one: it's less useful externally and it's a bit ugly to expose anyway (but it's convenient).
3332 abstract class AbstractData<T extends SettableData<T>> extends AbstractGettableData implements SettableData<T> {
@@ -61,16 +60,18 @@
6160 return wrapped;
6261 }
6362
63+ @Override
6464 protected ByteBuffer getValue(int i) {
6565 return values[i];
6666 }
6767
68+ @Override
6869 protected int getIndexOf(String name) {
6970 return getAllIndexesOf(name)[0];
7071 }
7172
73+ @Override
7274 public T setBool(int i, boolean v) {
73- checkType(i, BOOLEAN);
7475 TypeCodec<Boolean> codec = codecFor(i, Boolean.class);
7576 ByteBuffer bb;
7677 if(codec instanceof TypeCodec.PrimitiveBooleanCodec)
@@ -80,6 +81,7 @@
8081 return setValue(i, bb);
8182 }
8283
84+ @Override
8385 public T setBool(String name, boolean v) {
8486 for (int i : getAllIndexesOf(name)) {
8587 setBool(i, v);
@@ -87,8 +89,8 @@
8789 return wrapped;
8890 }
8991
92+ @Override
9093 public T setByte(int i, byte v) {
91- checkType(i, TINYINT);
9294 TypeCodec<Byte> codec = codecFor(i, Byte.class);
9395 ByteBuffer bb;
9496 if(codec instanceof TypeCodec.PrimitiveByteCodec)
@@ -98,6 +100,7 @@
98100 return setValue(i, bb);
99101 }
100102
103+ @Override
101104 public T setByte(String name, byte v) {
102105 for (int i : getAllIndexesOf(name)) {
103106 setByte(i, v);
@@ -105,8 +108,8 @@
105108 return wrapped;
106109 }
107110
111+ @Override
108112 public T setShort(int i, short v) {
109- checkType(i, SMALLINT);
110113 TypeCodec<Short> codec = codecFor(i, Short.class);
111114 ByteBuffer bb;
112115 if(codec instanceof TypeCodec.PrimitiveShortCodec)
@@ -116,6 +119,7 @@
116119 return setValue(i, bb);
117120 }
118121
122+ @Override
119123 public T setShort(String name, short v) {
120124 for (int i : getAllIndexesOf(name)) {
121125 setShort(i, v);
@@ -123,8 +127,8 @@
123127 return wrapped;
124128 }
125129
130+ @Override
126131 public T setInt(int i, int v) {
127- checkType(i, INT);
128132 TypeCodec<Integer> codec = codecFor(i, Integer.class);
129133 ByteBuffer bb;
130134 if(codec instanceof TypeCodec.PrimitiveIntCodec)
@@ -134,6 +138,7 @@
134138 return setValue(i, bb);
135139 }
136140
141+ @Override
137142 public T setInt(String name, int v) {
138143 for (int i : getAllIndexesOf(name)) {
139144 setInt(i, v);
@@ -141,8 +146,8 @@
141146 return wrapped;
142147 }
143148
149+ @Override
144150 public T setLong(int i, long v) {
145- checkType(i, BIGINT, COUNTER);
146151 TypeCodec<Long> codec = codecFor(i, Long.class);
147152 ByteBuffer bb;
148153 if(codec instanceof TypeCodec.PrimitiveLongCodec)
@@ -152,6 +157,7 @@
152157 return setValue(i, bb);
153158 }
154159
160+ @Override
155161 public T setLong(String name, long v) {
156162 for (int i : getAllIndexesOf(name)) {
157163 setLong(i, v);
@@ -159,11 +165,12 @@
159165 return wrapped;
160166 }
161167
168+ @Override
162169 public T setTimestamp(int i, Date v) {
163- checkType(i, TIMESTAMP);
164170 return setValue(i, codecFor(i, Date.class).serialize(v, protocolVersion));
165171 }
166172
173+ @Override
167174 public T setTimestamp(String name, Date v) {
168175 for (int i : getAllIndexesOf(name)) {
169176 setTimestamp(i, v);
@@ -171,11 +178,12 @@
171178 return wrapped;
172179 }
173180
181+ @Override
174182 public T setDate(int i, LocalDate v) {
175- checkType(i, DATE);
176183 return setValue(i, codecFor(i, LocalDate.class).serialize(v, protocolVersion));
177184 }
178185
186+ @Override
179187 public T setDate(String name, LocalDate v) {
180188 for (int i : getAllIndexesOf(name)) {
181189 setDate(i, v);
@@ -183,8 +191,8 @@
183191 return wrapped;
184192 }
185193
194+ @Override
186195 public T setTime(int i, long v) {
187- checkType(i, TIME);
188196 TypeCodec<Long> codec = codecFor(i, Long.class);
189197 ByteBuffer bb;
190198 if(codec instanceof TypeCodec.PrimitiveLongCodec)
@@ -194,6 +202,7 @@
194202 return setValue(i, bb);
195203 }
196204
205+ @Override
197206 public T setTime(String name, long v) {
198207 for (int i : getAllIndexesOf(name)) {
199208 setTime(i, v);
@@ -201,8 +210,8 @@
201210 return wrapped;
202211 }
203212
213+ @Override
204214 public T setFloat(int i, float v) {
205- checkType(i, FLOAT);
206215 TypeCodec<Float> codec = codecFor(i, Float.class);
207216 ByteBuffer bb;
208217 if(codec instanceof TypeCodec.PrimitiveFloatCodec)
@@ -212,6 +221,7 @@
212221 return setValue(i, bb);
213222 }
214223
224+ @Override
215225 public T setFloat(String name, float v) {
216226 for (int i : getAllIndexesOf(name)) {
217227 setFloat(i, v);
@@ -219,8 +229,8 @@
219229 return wrapped;
220230 }
221231
232+ @Override
222233 public T setDouble(int i, double v) {
223- checkType(i, DOUBLE);
224234 TypeCodec<Double> codec = codecFor(i, Double.class);
225235 ByteBuffer bb;
226236 if(codec instanceof TypeCodec.PrimitiveDoubleCodec)
@@ -230,6 +240,7 @@
230240 return setValue(i, bb);
231241 }
232242
243+ @Override
233244 public T setDouble(String name, double v) {
234245 for (int i : getAllIndexesOf(name)) {
235246 setDouble(i, v);
@@ -237,11 +248,12 @@
237248 return wrapped;
238249 }
239250
251+ @Override
240252 public T setString(int i, String v) {
241- checkType(i, VARCHAR, TEXT, ASCII);
242253 return setValue(i, codecFor(i, String.class).serialize(v, protocolVersion));
243254 }
244255
256+ @Override
245257 public T setString(String name, String v) {
246258 for (int i : getAllIndexesOf(name)) {
247259 setString(i, v);
@@ -249,11 +261,12 @@
249261 return wrapped;
250262 }
251263
264+ @Override
252265 public T setBytes(int i, ByteBuffer v) {
253- checkType(i, BLOB);
254266 return setValue(i, codecFor(i, ByteBuffer.class).serialize(v, protocolVersion));
255267 }
256268
269+ @Override
257270 public T setBytes(String name, ByteBuffer v) {
258271 for (int i : getAllIndexesOf(name)) {
259272 setBytes(i, v);
@@ -261,10 +274,12 @@
261274 return wrapped;
262275 }
263276
277+ @Override
264278 public T setBytesUnsafe(int i, ByteBuffer v) {
265279 return setValue(i, v == null ? null : v.duplicate());
266280 }
267281
282+ @Override
268283 public T setBytesUnsafe(String name, ByteBuffer v) {
269284 ByteBuffer value = v == null ? null : v.duplicate();
270285 for (int i : getAllIndexesOf(name)) {
@@ -273,11 +288,12 @@
273288 return wrapped;
274289 }
275290
291+ @Override
276292 public T setVarint(int i, BigInteger v) {
277- checkType(i, VARINT);
278293 return setValue(i, codecFor(i, BigInteger.class).serialize(v, protocolVersion));
279294 }
280295
296+ @Override
281297 public T setVarint(String name, BigInteger v) {
282298 for (int i : getAllIndexesOf(name)) {
283299 setVarint(i, v);
@@ -285,11 +301,12 @@
285301 return wrapped;
286302 }
287303
304+ @Override
288305 public T setDecimal(int i, BigDecimal v) {
289- checkType(i, DECIMAL);
290306 return setValue(i, codecFor(i, BigDecimal.class).serialize(v, protocolVersion));
291307 }
292308
309+ @Override
293310 public T setDecimal(String name, BigDecimal v) {
294311 for (int i : getAllIndexesOf(name)) {
295312 setDecimal(i, v);
@@ -297,11 +314,12 @@
297314 return wrapped;
298315 }
299316
317+ @Override
300318 public T setUUID(int i, UUID v) {
301- checkType(i, UUID, TIMEUUID);
302319 return setValue(i, codecFor(i, UUID.class).serialize(v, protocolVersion));
303320 }
304321
322+ @Override
305323 public T setUUID(String name, UUID v) {
306324 for (int i : getAllIndexesOf(name)) {
307325 setUUID(i, v);
@@ -309,11 +327,12 @@
309327 return wrapped;
310328 }
311329
330+ @Override
312331 public T setInet(int i, InetAddress v) {
313- checkType(i, INET);
314332 return setValue(i, codecFor(i, InetAddress.class).serialize(v, protocolVersion));
315333 }
316334
335+ @Override
317336 public T setInet(String name, InetAddress v) {
318337 for (int i : getAllIndexesOf(name)) {
319338 setInet(i, v);
@@ -337,18 +356,10 @@
337356 return wrapped;
338357 }
339358
359+ @Override
340360 @SuppressWarnings("unchecked")
341361 public <E> T setList(int i, List<E> v) {
342- checkType(i, LIST);
343- if(v == null || v.isEmpty()) {
344- // no runtime inspection possible, rely on the underlying metadata
345- return setValue(i, codecFor(i).serialize(v, protocolVersion));
346- } else {
347- // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java type
348- DataType eltCqlType = getType(i).getTypeArguments().get(0);
349- TypeToken<E> eltJavaType = getCodecRegistry().codecFor(eltCqlType, v.iterator().next()).getJavaType();
350- return setValue(i, codecFor(i, listOf(eltJavaType)).serialize(v, protocolVersion));
351- }
362+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
352363 }
353364
354365 @Override
@@ -388,19 +399,7 @@
388399 @SuppressWarnings("unchecked")
389400 @Override
390401 public <K, V> T setMap(int i, Map<K, V> v) {
391- checkType(i, MAP);
392- if(v == null || v.isEmpty()) {
393- // no runtime inspection possible, rely on the underlying metadata
394- return setValue(i, codecFor(i).serialize(v, protocolVersion));
395- } else {
396- // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java types for keys and values
397- DataType keysCqlType = getType(i).getTypeArguments().get(0);
398- DataType valuesCqlType = getType(i).getTypeArguments().get(1);
399- Map.Entry<K, V> entry = v.entrySet().iterator().next();
400- TypeToken<K> keysType = getCodecRegistry().codecFor(keysCqlType, entry.getKey()).getJavaType();
401- TypeToken<V> valuesType = getCodecRegistry().codecFor(valuesCqlType, entry.getValue()).getJavaType();
402- return setValue(i, codecFor(i, mapOf(keysType, valuesType)).serialize(v, protocolVersion));
403- }
402+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
404403 }
405404
406405 @Override
@@ -437,18 +436,10 @@
437436 return wrapped;
438437 }
439438
439+ @Override
440440 @SuppressWarnings("unchecked")
441441 public <E> T setSet(int i, Set<E> v) {
442- checkType(i, SET);
443- if(v == null || v.isEmpty()) {
444- // no runtime inspection possible, rely on the underlying metadata
445- return setValue(i, codecFor(i).serialize(v, protocolVersion));
446- } else {
447- // inspect the first element and locate a codec that accepts both the underlying CQL type and the actual Java type
448- DataType eltCqlType = getType(i).getTypeArguments().get(0);
449- TypeToken<E> eltJavaType = getCodecRegistry().codecFor(eltCqlType, v.iterator().next()).getJavaType();
450- return setValue(i, codecFor(i, setOf(eltJavaType)).serialize(v, protocolVersion));
451- }
442+ return setValue(i, codecFor(i).serialize(v, protocolVersion));
452443 }
453444
454445 @Override
@@ -485,11 +476,12 @@
485476 return wrapped;
486477 }
487478
479+ @Override
488480 public T setUDTValue(int i, UDTValue v) {
489- checkType(i, UDT);
490481 return setValue(i, codecFor(i, UDTValue.class).serialize(v, protocolVersion));
491482 }
492483
484+ @Override
493485 public T setUDTValue(String name, UDTValue v) {
494486 for (int i : getAllIndexesOf(name)) {
495487 setUDTValue(i, v);
@@ -497,11 +489,12 @@
497489 return wrapped;
498490 }
499491
492+ @Override
500493 public T setTupleValue(int i, TupleValue v) {
501- checkType(i, TUPLE);
502494 return setValue(i, codecFor(i, TupleValue.class).serialize(v, protocolVersion));
503495 }
504496
497+ @Override
505498 public T setTupleValue(String name, TupleValue v) {
506499 for (int i : getAllIndexesOf(name)) {
507500 setTupleValue(i, v);
@@ -509,20 +502,6 @@
509502 return wrapped;
510503 }
511504
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-
526505 @Override
527506 public <V> T set(int i, V v, Class<V> targetClass) {
528507 return set(i, v, codecFor(i, targetClass));
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java +1 −47
@@ -19,23 +19,15 @@
1919 import java.math.BigInteger;
2020 import java.net.InetAddress;
2121 import java.nio.ByteBuffer;
22-import java.util.Date;
23-import java.util.List;
24-import java.util.Map;
25-import java.util.Set;
26-import java.util.UUID;
22+import java.util.*;
2723
2824 import com.google.common.reflect.TypeToken;
2925
30-import static com.google.common.collect.Sets.newHashSet;
31-import static com.google.common.collect.Sets.newLinkedHashSet;
32-
3326 import com.datastax.driver.core.exceptions.InvalidTypeException;
3427
3528 import static com.datastax.driver.core.CodecUtils.listOf;
3629 import static com.datastax.driver.core.CodecUtils.mapOf;
3730 import static com.datastax.driver.core.CodecUtils.setOf;
38-import static com.datastax.driver.core.DataType.Name.*;
3931
4032 abstract class AbstractGettableByIndexData implements GettableByIndexData {
4133
@@ -93,25 +85,12 @@
9385 return getCodecRegistry().codecFor(getType(i), value);
9486 }
9587
96- // Note: we avoid having a vararg method to avoid the array allocation that comes with it.
9788 protected void checkType(int i, DataType.Name actual) {
9889 DataType.Name expected = getType(i).getName();
9990 if (!actual.isCompatibleWith(expected))
10091 throw new InvalidTypeException(String.format("Value %s is of type %s, not %s", getName(i), expected, actual));
10192 }
10293
103- protected void checkType(int i, DataType.Name actual1, DataType.Name actual2) {
104- DataType.Name expected = getType(i).getName();
105- if (!actual1.isCompatibleWith(expected) && !actual2.isCompatibleWith(expected))
106- throw new InvalidTypeException(String.format("Value %s is of type %s, not any of [%s, %s]", getName(i), expected, actual1, actual2));
107- }
108-
109- protected void checkType(int i, DataType.Name actual1, DataType.Name actual2, DataType.Name actual3) {
110- DataType.Name expected = getType(i).getName();
111- if (!actual1.isCompatibleWith(expected) && !actual2.isCompatibleWith(expected) && !actual3.isCompatibleWith(expected))
112- throw new InvalidTypeException(String.format("Value %s is of type %s, not any of [%s, %s, %s]", getName(i), expected, actual1, actual2, actual3));
113- }
114-
11594 /**
11695 * {@inheritDoc}
11796 */
@@ -125,12 +104,7 @@
125104 */
126105 @Override
127106 public boolean getBool(int i) {
128- checkType(i, BOOLEAN);
129-
130107 ByteBuffer value = getValue(i);
131- if (value == null || value.remaining() == 0)
132- return false;
133-
134108 TypeCodec<Boolean> codec = codecFor(i, Boolean.class);
135109 if(codec instanceof TypeCodec.PrimitiveBooleanCodec)
136110 return ((TypeCodec.PrimitiveBooleanCodec) codec).deserializeNoBoxing(value, protocolVersion);
@@ -143,7 +117,6 @@
143117 */
144118 @Override
145119 public byte getByte(int i) {
146- checkType(i, TINYINT);
147120 ByteBuffer value = getValue(i);
148121 TypeCodec<Byte> codec = codecFor(i, Byte.class);
149122 if(codec instanceof TypeCodec.PrimitiveByteCodec)
@@ -157,7 +130,6 @@
157130 */
158131 @Override
159132 public short getShort(int i) {
160- checkType(i, SMALLINT);
161133 ByteBuffer value = getValue(i);
162134 TypeCodec<Short> codec = codecFor(i, Short.class);
163135 if(codec instanceof TypeCodec.PrimitiveShortCodec)
@@ -171,7 +143,6 @@
171143 */
172144 @Override
173145 public int getInt(int i) {
174- checkType(i, INT);
175146 ByteBuffer value = getValue(i);
176147 TypeCodec<Integer> codec = codecFor(i, Integer.class);
177148 if(codec instanceof TypeCodec.PrimitiveIntCodec)
@@ -185,7 +156,6 @@
185156 */
186157 @Override
187158 public long getLong(int i) {
188- checkType(i, BIGINT, COUNTER);
189159 ByteBuffer value = getValue(i);
190160 TypeCodec<Long> codec = codecFor(i, Long.class);
191161 if(codec instanceof TypeCodec.PrimitiveLongCodec)
@@ -199,7 +169,6 @@
199169 */
200170 @Override
201171 public Date getTimestamp(int i) {
202- checkType(i, TIMESTAMP);
203172 ByteBuffer value = getValue(i);
204173 return codecFor(i, Date.class).deserialize(value, protocolVersion);
205174 }
@@ -209,7 +178,6 @@
209178 */
210179 @Override
211180 public LocalDate getDate(int i) {
212- checkType(i, DATE);
213181 ByteBuffer value = getValue(i);
214182 return codecFor(i, LocalDate.class).deserialize(value, protocolVersion);
215183 }
@@ -219,7 +187,6 @@
219187 */
220188 @Override
221189 public long getTime(int i) {
222- checkType(i, TIME);
223190 ByteBuffer value = getValue(i);
224191 TypeCodec<Long> codec = codecFor(i, Long.class);
225192 if(codec instanceof TypeCodec.PrimitiveLongCodec)
@@ -233,7 +200,6 @@
233200 */
234201 @Override
235202 public float getFloat(int i) {
236- checkType(i, FLOAT);
237203 ByteBuffer value = getValue(i);
238204 TypeCodec<Float> codec = codecFor(i, Float.class);
239205 if(codec instanceof TypeCodec.PrimitiveFloatCodec)
@@ -247,7 +213,6 @@
247213 */
248214 @Override
249215 public double getDouble(int i) {
250- checkType(i, DOUBLE);
251216 ByteBuffer value = getValue(i);
252217 TypeCodec<Double> codec = codecFor(i, Double.class);
253218 if(codec instanceof TypeCodec.PrimitiveDoubleCodec)
@@ -272,7 +237,6 @@
272237 */
273238 @Override
274239 public ByteBuffer getBytes(int i) {
275- checkType(i, BLOB);
276240 ByteBuffer value = getValue(i);
277241 return codecFor(i, ByteBuffer.class).deserialize(value, protocolVersion);
278242 }
@@ -282,7 +246,6 @@
282246 */
283247 @Override
284248 public String getString(int i) {
285- checkType(i, VARCHAR, ASCII);
286249 ByteBuffer value = getValue(i);
287250 return codecFor(i, String.class).deserialize(value, protocolVersion);
288251 }
@@ -292,7 +255,6 @@
292255 */
293256 @Override
294257 public BigInteger getVarint(int i) {
295- checkType(i, VARINT);
296258 ByteBuffer value = getValue(i);
297259 return codecFor(i, BigInteger.class).deserialize(value, protocolVersion);
298260 }
@@ -302,7 +264,6 @@
302264 */
303265 @Override
304266 public BigDecimal getDecimal(int i) {
305- checkType(i, DECIMAL);
306267 ByteBuffer value = getValue(i);
307268 return codecFor(i, BigDecimal.class).deserialize(value, protocolVersion);
308269 }
@@ -312,7 +273,6 @@
312273 */
313274 @Override
314275 public UUID getUUID(int i) {
315- checkType(i, UUID, TIMEUUID);
316276 ByteBuffer value = getValue(i);
317277 return codecFor(i, UUID.class).deserialize(value, protocolVersion);
318278 }
@@ -322,7 +282,6 @@
322282 */
323283 @Override
324284 public InetAddress getInet(int i) {
325- checkType(i, INET);
326285 ByteBuffer value = getValue(i);
327286 return codecFor(i, InetAddress.class).deserialize(value, protocolVersion);
328287 }
@@ -342,7 +301,6 @@
342301 @Override
343302 @SuppressWarnings("unchecked")
344303 public <T> List<T> getList(int i, TypeToken<T> elementsType) {
345- checkType(i, LIST);
346304 ByteBuffer value = getValue(i);
347305 TypeToken<List<T>> javaType = listOf(elementsType);
348306 return codecFor(i, javaType).deserialize(value, protocolVersion);
@@ -363,7 +321,6 @@
363321 @Override
364322 @SuppressWarnings("unchecked")
365323 public <T> Set<T> getSet(int i, TypeToken<T> elementsType) {
366- checkType(i, SET);
367324 ByteBuffer value = getValue(i);
368325 TypeToken<Set<T>> javaType = setOf(elementsType);
369326 return codecFor(i, javaType).deserialize(value, protocolVersion);
@@ -384,7 +341,6 @@
384341 @Override
385342 @SuppressWarnings("unchecked")
386343 public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) {
387- checkType(i, MAP);
388344 ByteBuffer value = getValue(i);
389345 TypeToken<Map<K, V>> javaType = mapOf(keysType, valuesType);
390346 return codecFor(i, javaType).deserialize(value, protocolVersion);
@@ -396,7 +352,6 @@
396352 @Override
397353 @SuppressWarnings("unchecked")
398354 public UDTValue getUDTValue(int i) {
399- checkType(i, UDT);
400355 ByteBuffer value = getValue(i);
401356 return codecFor(i, UDTValue.class).deserialize(value, protocolVersion);
402357 }
@@ -407,7 +362,6 @@
407362 @Override
408363 @SuppressWarnings("unchecked")
409364 public TupleValue getTupleValue(int i) {
410- checkType(i, TUPLE);
411365 ByteBuffer value = getValue(i);
412366 return codecFor(i, TupleValue.class).deserialize(value, protocolVersion);
413367 }
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 +169 −126
@@ -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,32 +302,50 @@
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)
286- .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
289313 .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+ .weigher(new TypeCodecWeigher());
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 /**
301322 * Register the given codec with this registry.
323+ * <p>
324+ * This method will log a warning and ignore the codec if it collides with a previously registered one.
325+ * Note that this check is not done in a completely thread-safe manner; codecs should typically be registered
326+ * at application startup, not in a highly concurrent context (if a race condition occurs, the worst outcome
327+ * is that no warning gets logged, and the codec gets registered but will never actually be used).
302328 *
303- * @param codec The codec to add to the registry.
329+ * @param newCodec The codec to add to the registry.
304330 * @return this CodecRegistry (for method chaining).
305331 */
306- public CodecRegistry register(TypeCodec<?> codec) {
307- return register(Collections.singleton(codec));
332+ public CodecRegistry register(TypeCodec<?> newCodec) {
333+ for (TypeCodec<?> oldCodec : codecs) {
334+ if (oldCodec.accepts(newCodec.getCqlType()) && oldCodec.accepts(newCodec.getJavaType())) {
335+ logger.warn("Ignoring codec {} because it collides with previously registered codec {}", newCodec, oldCodec);
336+ return this;
337+ }
338+ }
339+
340+ CacheKey key = new CacheKey(newCodec.getCqlType(), newCodec.getJavaType());
341+ TypeCodec<?> existing = cache.getIfPresent(key);
342+ if (existing != null) {
343+ logger.warn("Ignoring codec {} because it collides with previously generated codec {}", newCodec, existing);
344+ return this;
345+ }
346+
347+ this.codecs.add(newCodec);
348+ return this;
308349 }
309350
310351 /**
@@ -312,9 +353,13 @@
312353 *
313354 * @param codecs The codecs to add to the registry.
314355 * @return this Builder (for method chaining).
356+ *
357+ * @see #register(TypeCodec)
315358 */
316359 public CodecRegistry register(TypeCodec<?>... codecs) {
317- return register(Arrays.asList(codecs));
360+ for (TypeCodec<?> codec : codecs)
361+ register(codec);
362+ return this;
318363 }
319364
320365 /**
@@ -322,11 +367,12 @@
322367 *
323368 * @param codecs The codecs to add to the registry.
324369 * @return this Builder (for method chaining).
370+ *
371+ * @see #register(TypeCodec)
325372 */
326373 public CodecRegistry register(Iterable<? extends TypeCodec<?>> codecs) {
327- for (TypeCodec<?> codec : codecs) {
328- this.codecs.add(codec);
329- }
374+ for (TypeCodec<?> codec : codecs)
375+ register(codec);
330376 return this;
331377 }
332378
@@ -355,9 +401,7 @@
355401 * @throws CodecNotFoundException if a suitable codec cannot be found.
356402 */
357403 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;
404+ return findCodec(null, value);
361405 }
362406
363407 /**
@@ -394,7 +438,7 @@
394438 * Codecs returned by this method are cached.
395439 *
396440 * @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}.
441+ * @param javaType The Java type the codec should accept; can be {@code null}.
398442 * @return A suitable codec.
399443 * @throws CodecNotFoundException if a suitable codec cannot be found.
400444 */
@@ -416,13 +460,11 @@
416460 * Codecs returned by this method are cached.
417461 *
418462 * @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}.
463+ * @param javaType The {@link TypeToken Java type} the codec should accept; can be {@code null}.
420464 * @return A suitable codec.
421465 * @throws CodecNotFoundException if a suitable codec cannot be found.
422466 */
423467 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");
426468 return lookupCodec(cqlType, javaType);
427469 }
428470
@@ -438,24 +480,23 @@
438480 * <p>
439481 * Codecs returned by this method are <em>NOT</em> cached.
440482 *
441- * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
483+ * @param cqlType The {@link DataType CQL type} the codec should accept; can be {@code null}.
442484 * @param value The value the codec should accept; must not be {@code null}.
443485 * @return A suitable codec.
444486 * @throws CodecNotFoundException if a suitable codec cannot be found.
445487 */
446488 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");
449489 return findCodec(cqlType, value);
450490 }
451491
492+ @SuppressWarnings("unchecked")
452493 private <T> TypeCodec<T> lookupCodec(DataType cqlType, TypeToken<T> javaType) {
453494 checkNotNull(cqlType, "Parameter cqlType cannot be null");
454- logger.trace("Querying cache for codec [{} <-> {}]", cqlType, javaType);
495+ logger.trace("Querying cache for codec [{} <-> {}]", cqlType, javaType == null ? "ANY" : javaType);
455496 CacheKey cacheKey = new CacheKey(cqlType, javaType);
456497 try {
457498 TypeCodec<?> codec = cache.get(cacheKey);
458- logger.trace("Returning cached codec [{} <-> {}]", cqlType, javaType);
499+ logger.trace("Returning cached codec {}", codec);
459500 return (TypeCodec<T>)codec;
460501 } catch (UncheckedExecutionException e) {
461502 if(e.getCause() instanceof CodecNotFoundException) {
@@ -467,13 +508,12 @@
467508 }
468509 }
469510
511+ @SuppressWarnings("unchecked")
470512 private <T> TypeCodec<T> findCodec(DataType cqlType, TypeToken<T> javaType) {
471513 checkNotNull(cqlType, "Parameter cqlType cannot be null");
472- logger.trace("Looking for codec [{} <-> {}]",
473- cqlType == null ? "ANY" : cqlType,
474- javaType == null ? "ANY" : javaType);
514+ logger.trace("Looking for codec [{} <-> {}]", cqlType, javaType == null ? "ANY" : javaType);
475515 for (TypeCodec<?> codec : codecs) {
476- if ((cqlType == null || codec.accepts(cqlType)) && (javaType == null || codec.accepts(javaType))) {
516+ if (codec.accepts(cqlType) && (javaType == null || codec.accepts(javaType))) {
477517 logger.trace("Codec found: {}", codec);
478518 return (TypeCodec<T>)codec;
479519 }
@@ -481,6 +521,7 @@
481521 return createCodec(cqlType, javaType);
482522 }
483523
524+ @SuppressWarnings("unchecked")
484525 private <T> TypeCodec<T> findCodec(DataType cqlType, T value) {
485526 checkNotNull(value, "Parameter value cannot be null");
486527 logger.trace("Looking for codec [{} <-> {}]", cqlType == null ? "ANY" : cqlType, value.getClass());
@@ -496,10 +537,10 @@
496537 private <T> TypeCodec<T> createCodec(DataType cqlType, TypeToken<T> javaType) {
497538 TypeCodec<T> codec = maybeCreateCodec(cqlType, javaType);
498539 if (codec == null)
499- throw newException(cqlType, javaType);
540+ throw notFound(cqlType, javaType);
500541 // double-check that the created codec satisfies the initial request
501542 if (!codec.accepts(cqlType) || (javaType != null && !codec.accepts(javaType)))
502- throw newException(cqlType, javaType);
543+ throw notFound(cqlType, javaType);
503544 logger.trace("Codec created: {}", codec);
504545 return codec;
505546 }
@@ -507,21 +548,18 @@
507548 private <T> TypeCodec<T> createCodec(DataType cqlType, T value) {
508549 TypeCodec<T> codec = maybeCreateCodec(cqlType, value);
509550 if(codec == null)
510- throw newException(cqlType, TypeToken.of(value.getClass()));
551+ throw notFound(cqlType, TypeToken.of(value.getClass()));
511552 // double-check that the created codec satisfies the initial request
512553 if((cqlType != null && !codec.accepts(cqlType)) || !codec.accepts(value))
513- throw newException(cqlType, TypeToken.of(value.getClass()));
554+ throw notFound(cqlType, TypeToken.of(value.getClass()));
514555 logger.trace("Codec created: {}", codec);
515556 return codec;
516557 }
517558
559+ @SuppressWarnings("unchecked")
518560 private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, TypeToken<T> javaType) {
519561 checkNotNull(cqlType);
520562
521- if ((cqlType.getName() == VARCHAR || cqlType.getName() == TEXT) && javaType != null && Enum.class.isAssignableFrom(javaType.getRawType())) {
522- return new EnumStringCodec(javaType.getRawType());
523- }
524-
525563 if (cqlType.getName() == LIST && (javaType == null || List.class.isAssignableFrom(javaType.getRawType()))) {
526564 TypeToken<?> elementType = null;
527565 if (javaType != null && javaType.getType() instanceof ParameterizedType) {
@@ -529,7 +567,7 @@
529567 elementType = TypeToken.of(typeArguments[0]);
530568 }
531569 TypeCodec<?> eltCodec = findCodec(cqlType.getTypeArguments().get(0), elementType);
532- return new ListCodec(eltCodec);
570+ return (TypeCodec<T>)TypeCodec.list(eltCodec);
533571 }
534572
535573 if (cqlType.getName() == SET && (javaType == null || Set.class.isAssignableFrom(javaType.getRawType()))) {
@@ -539,7 +577,7 @@
539577 elementType = TypeToken.of(typeArguments[0]);
540578 }
541579 TypeCodec<?> eltCodec = findCodec(cqlType.getTypeArguments().get(0), elementType);
542- return new SetCodec(eltCodec);
580+ return (TypeCodec<T>)TypeCodec.set(eltCodec);
543581 }
544582
545583 if (cqlType.getName() == MAP && (javaType == null || Map.class.isAssignableFrom(javaType.getRawType()))) {
@@ -552,39 +590,40 @@
552590 }
553591 TypeCodec<?> keyCodec = findCodec(cqlType.getTypeArguments().get(0), keyType);
554592 TypeCodec<?> valueCodec = findCodec(cqlType.getTypeArguments().get(1), valueType);
555- return new MapCodec(keyCodec, valueCodec);
593+ return (TypeCodec<T>)TypeCodec.map(keyCodec, valueCodec);
556594 }
557595
558596 if (cqlType instanceof TupleType && (javaType == null || TupleValue.class.isAssignableFrom(javaType.getRawType()))) {
559- return (TypeCodec<T>)new TupleCodec((TupleType)cqlType);
597+ return (TypeCodec<T>)TypeCodec.tuple((TupleType)cqlType);
560598 }
561599
562600 if (cqlType instanceof UserType && (javaType == null || UDTValue.class.isAssignableFrom(javaType.getRawType()))) {
563- return (TypeCodec<T>)new UDTCodec((UserType)cqlType);
601+ return (TypeCodec<T>)TypeCodec.userType((UserType)cqlType);
602+ }
603+
604+ if(cqlType instanceof DataType.CustomType && (javaType == null || ByteBuffer.class.isAssignableFrom(javaType.getRawType()))) {
605+ return (TypeCodec<T>)TypeCodec.custom((DataType.CustomType)cqlType);
564606 }
565607
566608 return null;
567609 }
568610
611+ @SuppressWarnings("unchecked")
569612 private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, T value) {
570613 checkNotNull(value);
571614
572- if ((cqlType == null || cqlType.getName() == VARCHAR || cqlType.getName() == TEXT) && value instanceof Enum) {
573- return new EnumStringCodec(value.getClass());
574- }
575-
576615 if ((cqlType == null || cqlType.getName() == LIST) && value instanceof List) {
577616 List list = (List)value;
578617 if (list.isEmpty()) {
579618 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
580619 ? DataType.blob()
581620 : cqlType.getTypeArguments().get(0);
582- return new ListCodec(findCodec(elementType, (TypeToken)null));
621+ return TypeCodec.list(findCodec(elementType, (TypeToken)null));
583622 } else {
584623 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
585624 ? null
586625 : cqlType.getTypeArguments().get(0);
587- return new ListCodec(findCodec(elementType, list.iterator().next()));
626+ return (TypeCodec<T>)TypeCodec.list(findCodec(elementType, list.iterator().next()));
588627 }
589628 }
590629
@@ -594,12 +633,12 @@
594633 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
595634 ? DataType.blob()
596635 : cqlType.getTypeArguments().get(0);
597- return new SetCodec(findCodec(elementType, (TypeToken)null));
636+ return TypeCodec.set(findCodec(elementType, (TypeToken)null));
598637 } else {
599638 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
600639 ? null
601640 : cqlType.getTypeArguments().get(0);
602- return new SetCodec(findCodec(elementType, set.iterator().next()));
641+ return (TypeCodec<T>)TypeCodec.set(findCodec(elementType, set.iterator().next()));
603642 }
604643 }
605644
@@ -612,7 +651,7 @@
612651 DataType valueType = (cqlType == null || cqlType.getTypeArguments().size() < 2)
613652 ? DataType.blob() :
614653 cqlType.getTypeArguments().get(1);
615- return new MapCodec(
654+ return TypeCodec.map(
616655 findCodec(keyType, (TypeToken)null),
617656 findCodec(valueType, (TypeToken)null));
618657 } else {
@@ -623,24 +662,28 @@
623662 ? null
624663 : cqlType.getTypeArguments().get(1);
625664 Map.Entry entry = (Map.Entry)map.entrySet().iterator().next();
626- return new MapCodec(
665+ return (TypeCodec<T>)TypeCodec.map(
627666 findCodec(keyType, entry.getKey()),
628667 findCodec(valueType, entry.getValue()));
629668 }
630669 }
631670
632671 if ((cqlType == null || cqlType.getName() == DataType.Name.TUPLE) && value instanceof TupleValue) {
633- return (TypeCodec<T>)new TupleCodec(cqlType == null ? ((TupleValue)value).getType() : (TupleType) cqlType);
672+ return (TypeCodec<T>)TypeCodec.tuple(cqlType == null ? ((TupleValue)value).getType() : (TupleType)cqlType);
634673 }
635674
636675 if ((cqlType == null || cqlType.getName() == DataType.Name.UDT) && value instanceof UDTValue) {
637- return (TypeCodec<T>)new UDTCodec(cqlType == null ? ((UDTValue)value).getType() : (UserType) cqlType);
676+ return (TypeCodec<T>)TypeCodec.userType(cqlType == null ? ((UDTValue)value).getType() : (UserType)cqlType);
677+ }
678+
679+ if((cqlType != null && cqlType instanceof DataType.CustomType) && value instanceof ByteBuffer) {
680+ return (TypeCodec<T>)TypeCodec.custom((DataType.CustomType)cqlType);
638681 }
639682
640683 return null;
641684 }
642685
643- private static CodecNotFoundException newException(DataType cqlType, TypeToken<?> javaType) {
686+ private static CodecNotFoundException notFound(DataType cqlType, TypeToken<?> javaType) {
644687 String msg = String.format("Codec not found for requested operation: [%s <-> %s]",
645688 cqlType == null ? "ANY" : cqlType,
646689 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/DataType.java +4 −2
@@ -47,6 +47,7 @@
4747 INET (16),
4848 INT (9),
4949 TEXT (10){
50+ @Override
5051 public boolean isCompatibleWith(Name that) {
5152 return this == that || that == VARCHAR;
5253 }
@@ -54,6 +55,7 @@
5455 TIMESTAMP (11),
5556 UUID (12),
5657 VARCHAR (13){
58+ @Override
5759 public boolean isCompatibleWith(Name that) {
5860 return this == that || that == TEXT;
5961 }
@@ -637,7 +639,7 @@
637639
638640 @Override
639641 public final int hashCode() {
640- return Arrays.hashCode(new Object[]{ name, typeArguments });
642+ return Objects.hashCode(name, typeArguments);
641643 }
642644
643645 @Override
@@ -682,7 +684,7 @@
682684
683685 @Override
684686 public final int hashCode() {
685- return Arrays.hashCode(new Object[]{ name, customClassName });
687+ return Objects.hashCode(name, customClassName);
686688 }
687689
688690 @Override
modified driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java +81 −67
@@ -49,7 +49,6 @@
4949 * value is NULL, {@code false} is returned.
5050 *
5151 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
52- * @throws InvalidTypeException if value {@code i} is not of type BOOLEAN.
5352 */
5453 public boolean getBool(int i);
5554
@@ -61,7 +60,6 @@
6160 * value is NULL, {@code 0} is returned.
6261 *
6362 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
64- * @throws InvalidTypeException if value {@code i} is not of type TINYINT.
6563 */
6664 public byte getByte(int i);
6765
@@ -73,7 +71,6 @@
7371 * value is NULL, {@code 0} is returned.
7472 *
7573 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
76- * @throws InvalidTypeException if value {@code i} is not of type SMALLINT.
7774 */
7875 public short getShort(int i);
7976
@@ -85,7 +82,6 @@
8582 * value is NULL, {@code 0} is returned.
8683 *
8784 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
88- * @throws InvalidTypeException if value {@code i} is not of type INT.
8985 */
9086 public int getInt(int i);
9187
@@ -97,7 +93,6 @@
9793 * value is NULL, {@code 0L} is returned.
9894 *
9995 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
100- * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
10196 */
10297 public long getLong(int i);
10398
@@ -109,7 +104,6 @@
109104 * value is NULL, {@code null} is returned.
110105 *
111106 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
112- * @throws InvalidTypeException if value {@code i} is not of type TIMESTAMP.
113107 */
114108 public Date getTimestamp(int i);
115109
@@ -121,7 +115,6 @@
121115 * value is NULL, {@code null} is returned.
122116 *
123117 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
124- * @throws InvalidTypeException if value {@code i} is not of type DATE.
125118 */
126119 public LocalDate getDate(int i);
127120
@@ -133,7 +126,6 @@
133126 * value is NULL, {@code 0L} is returned.
134127 *
135128 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
136- * @throws InvalidTypeException if value {@code i} is not of type TIME.
137129 */
138130 public long getTime(int i);
139131
@@ -145,7 +137,6 @@
145137 * value is NULL, {@code 0.0f} is returned.
146138 *
147139 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
148- * @throws InvalidTypeException if value {@code i} is not of type FLOAT.
149140 */
150141 public float getFloat(int i);
151142
@@ -157,7 +148,6 @@
157148 * value is NULL, {@code 0.0} is returned.
158149 *
159150 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
160- * @throws InvalidTypeException if value {@code i} is not of type DOUBLE.
161151 */
162152 public double getDouble(int i);
163153
@@ -188,7 +178,6 @@
188178 * value is NULL, {@code null} is returned.
189179 *
190180 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
191- * @throws InvalidTypeException if value {@code i} type is not of type BLOB.
192181 */
193182 public ByteBuffer getBytes(int i);
194183
@@ -200,8 +189,6 @@
200189 * value is NULL, {@code null} is returned.
201190 *
202191 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
203- * @throws InvalidTypeException if value {@code i} type is none of:
204- * VARCHAR, TEXT or ASCII.
205192 */
206193 public String getString(int i);
207194
@@ -213,7 +200,6 @@
213200 * length integer. If the value is NULL, {@code null} is returned.
214201 *
215202 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
216- * @throws InvalidTypeException if value {@code i} is not of type VARINT.
217203 */
218204 public BigInteger getVarint(int i);
219205
@@ -225,7 +211,6 @@
225211 * length decimal. If the value is NULL, {@code null} is returned.
226212 *
227213 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
228- * @throws InvalidTypeException if value {@code i} is not of type DECIMAL.
229214 */
230215 public BigDecimal getDecimal(int i);
231216
@@ -237,8 +222,6 @@
237222 * If the value is NULL, {@code null} is returned.
238223 *
239224 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
240- * @throws InvalidTypeException if value {@code i} is not of type UUID
241- * or TIMEUUID.
242225 */
243226 public UUID getUUID(int i);
244227
@@ -250,7 +233,6 @@
250233 * If the value is NULL, {@code null} is returned.
251234 *
252235 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
253- * @throws InvalidTypeException if value {@code i} is not of type INET.
254236 */
255237 public InetAddress getInet(int i);
256238
@@ -258,17 +240,21 @@
258240 * Returns the {@code i}th value as a list.
259241 * <p>
260242 * If the type of the elements is generic, use {@link #getList(int, TypeToken)}.
243+ * <p>
244+ * Implementation note: the actual {@link List} implementation will depend
245+ * on the {@link TypeCodec codec} being used; therefore, callers should
246+ * make no assumptions concerning its mutability nor its thread-safety.
247+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
248+ * codec-dependent. By default, the driver will return mutable instances, and
249+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
250+ * makes no distinction between {@code NULL} and an empty collection).
261251 *
262252 * @param i the index ({@code 0 <= i < size()}) to retrieve.
263253 * @param elementsClass the class for the elements of the list to retrieve.
264254 * @return the value of the {@code i}th element as a list of
265- * {@code T} objects. If the value is NULL, an empty list is
266- * returned (note that Cassandra makes no difference between an empty list
267- * and column of type list that is not set). The returned list is immutable.
255+ * {@code T} objects.
268256 *
269257 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
270- * @throws InvalidTypeException if value {@code i} is not a list or if its
271- * elements are not of class {@code T}.
272258 */
273259 public <T> List<T> getList(int i, Class<T> elementsClass);
274260
@@ -279,17 +265,21 @@
279265 * <pre>
280266 * {@code List<List<String>> l = row.getList(1, new TypeToken<List<String>>() {});}
281267 * </pre>
268+ * <p>
269+ * Implementation note: the actual {@link List} implementation will depend
270+ * on the {@link TypeCodec codec} being used; therefore, callers should
271+ * make no assumptions concerning its mutability nor its thread-safety.
272+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
273+ * codec-dependent. By default, the driver will return mutable instances, and
274+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
275+ * makes no distinction between {@code NULL} and an empty collection).
282276 *
283277 * @param i the index ({@code 0 <= i < size()}) to retrieve.
284278 * @param elementsType the type of the elements of the list to retrieve.
285279 * @return the value of the {@code i}th element as a list of
286- * {@code T} objects. If the value is NULL, an empty list is
287- * returned (note that Cassandra makes no difference between an empty list
288- * and column of type list that is not set). The returned list is immutable.
280+ * {@code T} objects.
289281 *
290282 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
291- * @throws InvalidTypeException if value {@code i} is not a list or if its
292- * elements are not of class {@code T}.
293283 */
294284 public <T> List<T> getList(int i, TypeToken<T> elementsType);
295285
@@ -297,17 +287,21 @@
297287 * Returns the {@code i}th value as a set.
298288 * <p>
299289 * If the type of the elements is generic, use {@link #getSet(int, TypeToken)}.
290+ * <p>
291+ * Implementation note: the actual {@link Set} implementation will depend
292+ * on the {@link TypeCodec codec} being used; therefore, callers should
293+ * make no assumptions concerning its mutability nor its thread-safety.
294+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
295+ * codec-dependent. By default, the driver will return mutable instances, and
296+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
297+ * makes no distinction between {@code NULL} and an empty collection).
300298 *
301299 * @param i the index ({@code 0 <= i < size()}) to retrieve.
302300 * @param elementsClass the class for the elements of the set to retrieve.
303301 * @return the value of the {@code i}th element as a set of
304- * {@code T} objects. If the value is NULL, an empty set is
305- * returned (note that Cassandra makes no difference between an empty set
306- * and column of type set that is not set). The returned set is immutable.
302+ * {@code T} objects.
307303 *
308304 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
309- * @throws InvalidTypeException if value {@code i} is not a set or if its
310- * elements are not of class {@code T}.
311305 */
312306 public <T> Set<T> getSet(int i, Class<T> elementsClass);
313307
@@ -318,17 +312,21 @@
318312 * <pre>
319313 * {@code Set<List<String>> l = row.getSet(1, new TypeToken<List<String>>() {});}
320314 * </pre>
315+ * <p>
316+ * Implementation note: the actual {@link Set} implementation will depend
317+ * on the {@link TypeCodec codec} being used; therefore, callers should
318+ * make no assumptions concerning its mutability nor its thread-safety.
319+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
320+ * codec-dependent. By default, the driver will return mutable instances, and
321+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
322+ * makes no distinction between {@code NULL} and an empty collection).
321323 *
322324 * @param i the index ({@code 0 <= i < size()}) to retrieve.
323325 * @param elementsType the type for the elements of the set to retrieve.
324326 * @return the value of the {@code i}th element as a set of
325- * {@code T} objects. If the value is NULL, an empty set is
326- * returned (note that Cassandra makes no difference between an empty set
327- * and column of type set that is not set). The returned set is immutable.
327+ * {@code T} objects.
328328 *
329329 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
330- * @throws InvalidTypeException if value {@code i} is not a set or if its
331- * elements are not of class {@code T}.
332330 */
333331 public <T> Set<T> getSet(int i, TypeToken<T> elementsType);
334332
@@ -336,20 +334,22 @@
336334 * Returns the {@code i}th value as a map.
337335 * <p>
338336 * If the type of the keys and/or values is generic, use {@link #getMap(int, TypeToken, TypeToken)}.
337+ * <p>
338+ * Implementation note: the actual {@link Map} implementation will depend
339+ * on the {@link TypeCodec codec} being used; therefore, callers should
340+ * make no assumptions concerning its mutability nor its thread-safety.
341+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
342+ * codec-dependent. By default, the driver will return mutable instances, and
343+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
344+ * makes no distinction between {@code NULL} and an empty collection).
339345 *
340346 * @param i the index ({@code 0 <= i < size()}) to retrieve.
341347 * @param keysClass the class for the keys of the map to retrieve.
342348 * @param valuesClass the class for the values of the map to retrieve.
343349 * @return the value of the {@code i}th element as a map of
344- * {@code K} to {@code V} objects. If the value is NULL,
345- * an empty map is returned (note that Cassandra makes no difference
346- * between an empty map and column of type map that is not set). The
347- * returned map is immutable.
350+ * {@code K} to {@code V} objects.
348351 *
349352 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
350- * @throws InvalidTypeException if value {@code i} is not a map, if its
351- * keys are not of class {@code K} or if its values are not of
352- * class {@code V}.
353353 */
354354 public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass);
355355
@@ -361,20 +361,22 @@
361361 * <pre>
362362 * {@code Map<Int, List<String>> l = row.getMap(1, TypeToken.of(Integer.class), new TypeToken<List<String>>() {});}
363363 * </pre>
364+ * <p>
365+ * Implementation note: the actual {@link Map} implementation will depend
366+ * on the {@link TypeCodec codec} being used; therefore, callers should
367+ * make no assumptions concerning its mutability nor its thread-safety.
368+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
369+ * codec-dependent. By default, the driver will return mutable instances, and
370+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
371+ * makes no distinction between {@code NULL} and an empty collection).
364372 *
365373 * @param i the index ({@code 0 <= i < size()}) to retrieve.
366374 * @param keysType the type for the keys of the map to retrieve.
367375 * @param valuesType the type for the values of the map to retrieve.
368376 * @return the value of the {@code i}th element as a map of
369- * {@code K} to {@code V} objects. If the value is NULL,
370- * an empty map is returned (note that Cassandra makes no difference
371- * between an empty map and column of type map that is not set). The
372- * returned map is immutable.
377+ * {@code K} to {@code V} objects.
373378 *
374379 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
375- * @throws InvalidTypeException if value {@code i} is not a map, if its
376- * keys are not of class {@code K} or if its values are not of
377- * class {@code V}.
378380 */
379381 public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType);
380382
@@ -386,7 +388,6 @@
386388 * then {@code null} will be returned.
387389 *
388390 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
389- * @throws InvalidTypeException if value {@code i} is not a UDT value.
390391 */
391392 public UDTValue getUDTValue(int i);
392393
@@ -398,25 +399,21 @@
398399 * then {@code null} will be returned.
399400 *
400401 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
401- * @throws InvalidTypeException if value {@code i} is not a tuple value.
402402 */
403403 public TupleValue getTupleValue(int i);
404404
405405 /**
406406 * Returns the {@code i}th value as the Java type matching its CQL type.
407407 * <p>
408- * This method uses the default codec for the underlying CQL type
409- * to perform deserialization, and is safe to be used
410- * <em>as long as only default codecs are in use</em>.
411- * If a second, custom codec for the same CQL type is registered, which one will
412- * be used is unspecified; in such cases, it is preferable to use
413- * the more deterministic methods {@link #get(int, Class)} or {@link #get(int, TypeToken)} instead.
408+ * Note: if two or more codecs are available
409+ * for the underlying CQL type, <em>the one that will be used will be
410+ * the first one to be registered.</em>.
411+ * <p>
412+ * For these reasons, it is generally preferable to use the more
413+ * deterministic methods {@link #get(int, Class)} or {@link #get(int, TypeToken)} instead.
414414 *
415415 * @param i the index to retrieve.
416416 * @return the value of the {@code i}th value as the Java type matching its CQL type.
417- * If the value is NULL and is a simple type, UDT or tuple, {@code null} is returned.
418- * If it is NULL and is a collection type, an empty (immutable) collection is returned.
419- *
420417 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
421418 */
422419 public Object getObject(int i);
@@ -431,12 +428,17 @@
431428 * where more than one codec is registered for the same CQL type; specifying the Java class
432429 * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
433430 * thus avoiding any risk of ambiguity.
431+ * <p>
432+ * Implementation note: the actual object returned by this method will depend
433+ * on the {@link TypeCodec codec} being used; therefore, callers should
434+ * make no assumptions concerning its mutability nor its thread-safety.
435+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
436+ * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
437+ * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
434438 *
435439 * @param i the index to retrieve.
436440 * @param targetClass The Java type the value should be converted to.
437441 * @return the value of the {@code i}th value converted to the given Java type.
438- * If the CQL value is {@code NULL}, this method will return {@code null}
439- * for a simple type, UDT or tuple, and an empty (immutable) collection for collection types.
440442 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
441443 * @throws com.datastax.driver.core.exceptions.CodecNotFoundException
442444 * if no {@link TypeCodec} instance for {@code targetClass} could be found
@@ -454,12 +456,17 @@
454456 * where more than one codec is registered for the same CQL type; specifying the Java class
455457 * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
456458 * thus avoiding any risk of ambiguity.
459+ * <p>
460+ * Implementation note: the actual object returned by this method will depend
461+ * on the {@link TypeCodec codec} being used; therefore, callers should
462+ * make no assumptions concerning its mutability nor its thread-safety.
463+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
464+ * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
465+ * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
457466 *
458467 * @param i the index to retrieve.
459468 * @param targetType The Java type the value should be converted to.
460469 * @return the value of the {@code i}th value converted to the given Java type.
461- * If the CQL value is {@code NULL}, the default set of codecs will return {@code null}
462- * for a simple type, UDT or tuple, and an empty (immutable) collection for collection types.
463470 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
464471 * @throws com.datastax.driver.core.exceptions.CodecNotFoundException
465472 * if no {@link TypeCodec} instance for {@code targetType} could be found
@@ -475,6 +482,13 @@
475482 * <p>
476483 * It is the caller's responsibility to ensure that the given codec {@link TypeCodec#accepts(DataType) accepts}
477484 * the underlying CQL type; failing to do so may result in {@link InvalidTypeException}s being thrown.
485+ * <p>
486+ * Implementation note: the actual object returned by this method will depend
487+ * on the {@link TypeCodec codec} being used; therefore, callers should
488+ * make no assumptions concerning its mutability nor its thread-safety.
489+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
490+ * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
491+ * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
478492 *
479493 * @param i the index to retrieve.
480494 * @param codec The {@link TypeCodec} to use to deserialize the value; may not be {@code null}.
modified driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java +82 −64
@@ -48,7 +48,6 @@
4848 * {@code false} is returned.
4949 *
5050 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
51- * @throws InvalidTypeException if value {@code name} is not of type BOOLEAN.
5251 */
5352 public boolean getBool(String name);
5453
@@ -60,7 +59,6 @@
6059 * {@code 0} is returned.
6160 *
6261 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
63- * @throws InvalidTypeException if value {@code name} is not of type TINYINT.
6462 */
6563 public byte getByte(String name);
6664
@@ -72,7 +70,6 @@
7270 * {@code 0} is returned.
7371 *
7472 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
75- * @throws InvalidTypeException if value {@code name} is not of type SMALLINT.
7673 */
7774 public short getShort(String name);
7875
@@ -84,7 +81,6 @@
8481 * {@code 0} is returned.
8582 *
8683 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
87- * @throws InvalidTypeException if value {@code name} is not of type INT.
8884 */
8985 public int getInt(String name);
9086
@@ -96,7 +92,6 @@
9692 * {@code 0L} is returned.
9793 *
9894 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
99- * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
10095 */
10196 public long getLong(String name);
10297
@@ -108,7 +103,6 @@
108103 * {@code null} is returned.
109104 *
110105 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
111- * @throws InvalidTypeException if value {@code name} is not of type TIMESTAMP.
112106 */
113107 public Date getTimestamp(String name);
114108
@@ -120,7 +114,6 @@
120114 * {@code null} is returned.
121115 *
122116 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
123- * @throws InvalidTypeException if value {@code name} is not of type DATE.
124117 */
125118 public LocalDate getDate(String name);
126119
@@ -132,7 +125,6 @@
132125 * {@code 0L} is returned.
133126 *
134127 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
135- * @throws InvalidTypeException if value {@code name} is not of type TIME.
136128 */
137129 public long getTime(String name);
138130
@@ -144,7 +136,6 @@
144136 * {@code 0.0f} is returned.
145137 *
146138 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
147- * @throws InvalidTypeException if value {@code name} is not of type FLOAT.
148139 */
149140 public float getFloat(String name);
150141
@@ -156,7 +147,6 @@
156147 * {@code 0.0} is returned.
157148 *
158149 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
159- * @throws InvalidTypeException if value {@code name} is not of type DOUBLE.
160150 */
161151 public double getDouble(String name);
162152
@@ -187,7 +177,6 @@
187177 * {@code null} is returned.
188178 *
189179 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
190- * @throws InvalidTypeException if value {@code i} type is not of type BLOB.
191180 */
192181 public ByteBuffer getBytes(String name);
193182
@@ -199,8 +188,6 @@
199188 * {@code null} is returned.
200189 *
201190 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
202- * @throws InvalidTypeException if value {@code name} type is none of:
203- * VARCHAR, TEXT or ASCII.
204191 */
205192 public String getString(String name);
206193
@@ -212,7 +199,6 @@
212199 * If the value is NULL, {@code null} is returned.
213200 *
214201 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
215- * @throws InvalidTypeException if value {@code name} is not of type VARINT.
216202 */
217203 public BigInteger getVarint(String name);
218204
@@ -224,7 +210,6 @@
224210 * If the value is NULL, {@code null} is returned.
225211 *
226212 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
227- * @throws InvalidTypeException if value {@code name} is not of type DECIMAL.
228213 */
229214 public BigDecimal getDecimal(String name);
230215
@@ -236,8 +221,6 @@
236221 * If the value is NULL, {@code null} is returned.
237222 *
238223 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
239- * @throws InvalidTypeException if value {@code name} is not of type
240- * UUID or TIMEUUID.
241224 */
242225 public UUID getUUID(String name);
243226
@@ -249,8 +232,6 @@
249232 * If the value is NULL, {@code null} is returned.
250233 *
251234 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
252- * @throws InvalidTypeException if value {@code name} is not of type
253- * INET.
254235 */
255236 public InetAddress getInet(String name);
256237
@@ -258,17 +239,21 @@
258239 * Returns the value for {@code name} as a list.
259240 * <p>
260241 * If the type of the elements is generic, use {@link #getList(String, TypeToken)}.
242+ * <p>
243+ * Implementation note: the actual {@link List} implementation will depend
244+ * on the {@link TypeCodec codec} being used; therefore, callers should
245+ * make no assumptions concerning its mutability nor its thread-safety.
246+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
247+ * codec-dependent. By default, the driver will return mutable instances, and
248+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
249+ * makes no distinction between {@code NULL} and an empty collection).
261250 *
262251 * @param name the name to retrieve.
263252 * @param elementsClass the class for the elements of the list to retrieve.
264253 * @return the value of the {@code i}th element as a list of
265- * {@code T} objects. If the value is NULL, an empty list is
266- * returned (note that Cassandra makes no difference between an empty list
267- * and column of type list that is not set). The returned list is immutable.
254+ * {@code T} objects.
268255 *
269256 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
270- * @throws InvalidTypeException if value {@code name} is not a list or if its
271- * elements are not of class {@code T}.
272257 */
273258 public <T> List<T> getList(String name, Class<T> elementsClass);
274259
@@ -279,17 +264,21 @@
279264 * <pre>
280265 * {@code List<List<String>> l = row.getList("theColumn", new TypeToken<List<String>>() {});}
281266 * </pre>
267+ * <p>
268+ * Implementation note: the actual {@link List} implementation will depend
269+ * on the {@link TypeCodec codec} being used; therefore, callers should
270+ * make no assumptions concerning its mutability nor its thread-safety.
271+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
272+ * codec-dependent. By default, the driver will return mutable instances, and
273+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
274+ * makes no distinction between {@code NULL} and an empty collection).
282275 *
283276 * @param name the name to retrieve.
284277 * @param elementsType the type for the elements of the list to retrieve.
285278 * @return the value of the {@code i}th element as a list of
286- * {@code T} objects. If the value is NULL, an empty list is
287- * returned (note that Cassandra makes no difference between an empty list
288- * and column of type list that is not set). The returned list is immutable.
279+ * {@code T} objects.
289280 *
290281 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
291- * @throws InvalidTypeException if value {@code name} is not a list or if its
292- * elements are not of class {@code T}.
293282 */
294283 public <T> List<T> getList(String name, TypeToken<T> elementsType);
295284
@@ -297,17 +286,21 @@
297286 * Returns the value for {@code name} as a set.
298287 * <p>
299288 * If the type of the elements is generic, use {@link #getSet(String, TypeToken)}.
289+ * <p>
290+ * Implementation note: the actual {@link Set} implementation will depend
291+ * on the {@link TypeCodec codec} being used; therefore, callers should
292+ * make no assumptions concerning its mutability nor its thread-safety.
293+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
294+ * codec-dependent. By default, the driver will return mutable instances, and
295+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
296+ * makes no distinction between {@code NULL} and an empty collection).
300297 *
301298 * @param name the name to retrieve.
302299 * @param elementsClass the class for the elements of the set to retrieve.
303300 * @return the value of the {@code i}th element as a set of
304- * {@code T} objects. If the value is NULL, an empty set is
305- * returned (note that Cassandra makes no difference between an empty set
306- * and column of type set that is not set). The returned set is immutable.
301+ * {@code T} objects.
307302 *
308303 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
309- * @throws InvalidTypeException if value {@code name} is not a set or if its
310- * elements are not of class {@code T}.
311304 */
312305 public <T> Set<T> getSet(String name, Class<T> elementsClass);
313306
@@ -318,17 +311,21 @@
318311 * <pre>
319312 * {@code Set<List<String>> l = row.getSet("theColumn", new TypeToken<List<String>>() {});}
320313 * </pre>
314+ * <p>
315+ * Implementation note: the actual {@link Set} implementation will depend
316+ * on the {@link TypeCodec codec} being used; therefore, callers should
317+ * make no assumptions concerning its mutability nor its thread-safety.
318+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
319+ * codec-dependent. By default, the driver will return mutable instances, and
320+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
321+ * makes no distinction between {@code NULL} and an empty collection).
321322 *
322323 * @param name the name to retrieve.
323324 * @param elementsType the type for the elements of the set to retrieve.
324325 * @return the value of the {@code i}th element as a set of
325- * {@code T} objects. If the value is NULL, an empty set is
326- * returned (note that Cassandra makes no difference between an empty set
327- * and column of type set that is not set). The returned set is immutable.
326+ * {@code T} objects.
328327 *
329328 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
330- * @throws InvalidTypeException if value {@code name} is not a set or if its
331- * elements are not of class {@code T}.
332329 */
333330 public <T> Set<T> getSet(String name, TypeToken<T> elementsType);
334331
@@ -336,20 +333,22 @@
336333 * Returns the value for {@code name} as a map.
337334 * <p>
338335 * If the type of the keys and/or values is generic, use {@link #getMap(String, TypeToken, TypeToken)}.
336+ * <p>
337+ * Implementation note: the actual {@link Map} implementation will depend
338+ * on the {@link TypeCodec codec} being used; therefore, callers should
339+ * make no assumptions concerning its mutability nor its thread-safety.
340+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
341+ * codec-dependent. By default, the driver will return mutable instances, and
342+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
343+ * makes no distinction between {@code NULL} and an empty collection).
339344 *
340345 * @param name the name to retrieve.
341346 * @param keysClass the class for the keys of the map to retrieve.
342347 * @param valuesClass the class for the values of the map to retrieve.
343348 * @return the value of {@code name} as a map of
344- * {@code K} to {@code V} objects. If the value is NULL,
345- * an empty map is returned (note that Cassandra makes no difference
346- * between an empty map and column of type map that is not set). The
347- * returned map is immutable.
349+ * {@code K} to {@code V} objects.
348350 *
349351 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
350- * @throws InvalidTypeException if value {@code name} is not a map, if its
351- * keys are not of class {@code K} or if its values are not of
352- * class {@code V}.
353352 */
354353 public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass);
355354
@@ -360,20 +359,22 @@
360359 * <pre>
361360 * {@code Map<Int, List<String>> l = row.getMap("theColumn", TypeToken.of(Integer.class), new TypeToken<List<String>>() {});}
362361 * </pre>
362+ * <p>
363+ * Implementation note: the actual {@link Map} implementation will depend
364+ * on the {@link TypeCodec codec} being used; therefore, callers should
365+ * make no assumptions concerning its mutability nor its thread-safety.
366+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
367+ * codec-dependent. By default, the driver will return mutable instances, and
368+ * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
369+ * makes no distinction between {@code NULL} and an empty collection).
363370 *
364371 * @param name the name to retrieve.
365372 * @param keysType the class for the keys of the map to retrieve.
366373 * @param valuesType the class for the values of the map to retrieve.
367374 * @return the value of {@code name} as a map of
368- * {@code K} to {@code V} objects. If the value is NULL,
369- * an empty map is returned (note that Cassandra makes no difference
370- * between an empty map and column of type map that is not set). The
371- * returned map is immutable.
375+ * {@code K} to {@code V} objects.
372376 *
373377 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
374- * @throws InvalidTypeException if value {@code name} is not a map, if its
375- * keys are not of class {@code K} or if its values are not of
376- * class {@code V}.
377378 */
378379 public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType);
379380
@@ -385,7 +386,6 @@
385386 * then {@code null} will be returned.
386387 *
387388 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
388- * @throws InvalidTypeException if value {@code i} is not a UDT value.
389389 */
390390 public UDTValue getUDTValue(String name);
391391
@@ -397,22 +397,21 @@
397397 * then {@code null} will be returned.
398398 *
399399 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
400- * @throws InvalidTypeException if value {@code i} is not a tuple value.
401400 */
402401 public TupleValue getTupleValue(String name);
403402
404403 /**
405404 * Returns the value for {@code name} as the Java type matching its CQL type.
406405 * <p>
407- * This method uses the default codec for the underlying CQL type
408- * to perform deserialization, and is safe to be used
409- * <em>as long as only default codecs are in use</em>.
410- * If a second, custom codec for the same CQL type is registered, which one will
411- * be used is unspecified; in such cases, it is preferable to use
412- * the more deterministic methods {@link #get(String, Class)} or {@link #get(String, TypeToken)} instead.
406+ * Note: if two or more codecs are available
407+ * for the underlying CQL type, <em>the one that will be used will be
408+ * the first one to be registered.</em>.
409+ * <p>
410+ * For these reasons, it is generally preferable to use the more
411+ * deterministic methods {@link #get(String, Class)} or {@link #get(String, TypeToken)} instead.
413412 *
414413 * @param name the name to retrieve.
415- * @return the value of the {@code i}th value as the Java type matching its CQL type.
414+ * @return the value of {@code name} as the Java type matching its CQL type.
416415 * If the value is NULL and is a simple type, UDT or tuple, {@code null} is returned.
417416 * If it is NULL and is a collection type, an empty (immutable) collection is returned.
418417 *
@@ -430,11 +429,17 @@
430429 * where more than one codec is registered for the same CQL type; specifying the Java class
431430 * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
432431 * thus avoiding any risk of ambiguity.
432+ * <p>
433+ * Implementation note: the actual object returned by this method will depend
434+ * on the {@link TypeCodec codec} being used; therefore, callers should
435+ * make no assumptions concerning its mutability nor its thread-safety.
436+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
437+ * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
438+ * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
433439 *
434440 * @param name the name to retrieve.
435441 * @param targetClass The Java type the value should be converted to.
436442 * @return the value for {@code name} value converted to the given Java type.
437- * If the CQL value is {@code NULL}, then {@code null} is returned.
438443 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
439444 * @throws com.datastax.driver.core.exceptions.CodecNotFoundException
440445 * if no {@link TypeCodec} instance for {@code targetClass} could be found
@@ -452,11 +457,17 @@
452457 * where more than one codec is registered for the same CQL type; specifying the Java class
453458 * allows the {@link CodecRegistry} to narrow down the search and return only an exactly-matching codec (if any),
454459 * thus avoiding any risk of ambiguity.
460+ * <p>
461+ * Implementation note: the actual object returned by this method will depend
462+ * on the {@link TypeCodec codec} being used; therefore, callers should
463+ * make no assumptions concerning its mutability nor its thread-safety.
464+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
465+ * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
466+ * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
455467 *
456468 * @param name the name to retrieve.
457469 * @param targetType The Java type the value should be converted to.
458470 * @return the value for {@code name} value converted to the given Java type.
459- * If the CQL value is {@code NULL}, then {@code null} is returned.
460471 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
461472 * @throws com.datastax.driver.core.exceptions.CodecNotFoundException
462473 * if no {@link TypeCodec} instance for {@code targetType} could be found
@@ -472,6 +483,13 @@
472483 * <p>
473484 * It is the caller's responsibility to ensure that the given codec {@link TypeCodec#accepts(DataType) accepts}
474485 * the underlying CQL type; failing to do so may result in {@link InvalidTypeException}s being thrown.
486+ * <p>
487+ * Implementation note: the actual object returned by this method will depend
488+ * on the {@link TypeCodec codec} being used; therefore, callers should
489+ * make no assumptions concerning its mutability nor its thread-safety.
490+ * Furthermore, the behavior of this method in respect to CQL {@code NULL} values is also
491+ * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
492+ * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
475493 *
476494 * @param name the name to retrieve.
477495 * @param codec The {@link TypeCodec} to use to deserialize the value; may not be {@code null}.
modified driver-core/src/main/java/com/datastax/driver/core/Row.java +0 −624
@@ -15,12 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.math.BigDecimal;
19-import java.math.BigInteger;
20-import java.net.InetAddress;
21-import java.nio.ByteBuffer;
22-import java.util.*;
23-
2418 import com.datastax.driver.core.exceptions.InvalidTypeException;
2519
2620 /**
@@ -31,7 +25,6 @@
3125 * rules explained in {@link ColumnDefinitions}.
3226 */
3327 public interface Row extends GettableData {
34- // Note that we re-include all the methods of GettableData just for the sake of better javadoc
3528
3629 /**
3730 * Returns the columns contained in this Row.
@@ -40,505 +33,6 @@
4033 */
4134 public ColumnDefinitions getColumnDefinitions();
4235
43- /**
44- * Returns whether the {@code i}th value of this row is NULL.
45- *
46- * @param i the index ({@code 0 <= i < size()}) of the column to check.
47- * @return whether the {@code i}th value of this row is NULL.
48- *
49- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
50- */
51- @Override
52- public boolean isNull(int i);
53-
54- /**
55- * Returns whether the value for column {@code name} in this row is NULL.
56- *
57- * @param name the name of the column to check.
58- * @return whether the value of column {@code name} is NULL.
59- *
60- * @throws IllegalArgumentException if {@code name} is not part of the
61- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
62- */
63- @Override
64- public boolean isNull(String name);
65-
66- /**
67- * Returns the {@code i}th value of this row as a boolean.
68- *
69- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
70- * @return the boolean value of the {@code i}th column in this row. If the
71- * value is NULL, {@code false} is returned.
72- *
73- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
74- * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
75- */
76- @Override
77- public boolean getBool(int i);
78-
79- /**
80- * Returns the value of column {@code name} as a boolean.
81- *
82- * @param name the name of the column to retrieve.
83- * @return the boolean value of column {@code name}. If the value is NULL,
84- * {@code false} is returned.
85- *
86- * @throws IllegalArgumentException if {@code name} is not part of the
87- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
88- * @throws InvalidTypeException if column {@code name} is not of type BOOLEAN.
89- */
90- @Override
91- public boolean getBool(String name);
92-
93- /**
94- * Returns the {@code i}th value of this row as a byte.
95- *
96- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
97- * @return the value of the {@code i}th column in this row as a byte. If the
98- * value is NULL, {@code 0} is returned.
99- *
100- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
101- * @throws InvalidTypeException if column {@code i} is not of type TINYINT.
102- */
103- @Override
104- public byte getByte(int i);
105-
106- /**
107- * Returns the value of column {@code name} as a byte.
108- *
109- * @param name the name of the column to retrieve.
110- * @return the value of column {@code name} as a byte. If the value is NULL,
111- * {@code 0} is returned.
112- *
113- * @throws IllegalArgumentException if {@code name} is not part of the
114- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
115- * @throws InvalidTypeException if column {@code name} is not of type TINYINT.
116- */
117- @Override
118- public byte getByte(String name);
119-
120- /**
121- * Returns the {@code i}th value of this row as a short.
122- *
123- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
124- * @return the value of the {@code i}th column in this row as a short. If the
125- * value is NULL, {@code 0} is returned.
126- *
127- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
128- * @throws InvalidTypeException if column {@code i} is not of type SMALLINT.
129- */
130- @Override
131- public short getShort(int i);
132-
133- /**
134- * Returns the value of column {@code name} as a short.
135- *
136- * @param name the name of the column to retrieve.
137- * @return the value of column {@code name} as a short. If the value is NULL,
138- * {@code 0} is returned.
139- *
140- * @throws IllegalArgumentException if {@code name} is not part of the
141- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
142- * @throws InvalidTypeException if column {@code name} is not of type SMALLINT.
143- */
144- @Override
145- public short getShort(String name);
146-
147- /**
148- * Returns the {@code i}th value of this row as an integer.
149- *
150- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
151- * @return the value of the {@code i}th column in this row as an integer. If the
152- * value is NULL, {@code 0} is returned.
153- *
154- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
155- * @throws InvalidTypeException if column {@code i} is not of type INT.
156- */
157- @Override
158- public int getInt(int i);
159-
160- /**
161- * Returns the value of column {@code name} as an integer.
162- *
163- * @param name the name of the column to retrieve.
164- * @return the value of column {@code name} as an integer. If the value is NULL,
165- * {@code 0} is returned.
166- *
167- * @throws IllegalArgumentException if {@code name} is not part of the
168- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
169- * @throws InvalidTypeException if column {@code name} is not of type INT.
170- */
171- @Override
172- public int getInt(String name);
173-
174- /**
175- * Returns the {@code i}th value of this row as a long.
176- *
177- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
178- * @return the value of the {@code i}th column in this row as a long. If the
179- * value is NULL, {@code 0L} is returned.
180- *
181- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
182- * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
183- */
184- @Override
185- public long getLong(int i);
186-
187- /**
188- * Returns the value of column {@code name} as a long.
189- *
190- * @param name the name of the column to retrieve.
191- * @return the value of column {@code name} as a long. If the value is NULL,
192- * {@code 0L} is returned.
193- *
194- * @throws IllegalArgumentException if {@code name} is not part of the
195- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
196- * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
197- */
198- @Override
199- public long getLong(String name);
200-
201- /**
202- * Returns the {@code i}th value of this row as a date.
203- *
204- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
205- * @return the value of the {@code i}th column in this row as a data. If the
206- * value is NULL, {@code null} is returned.
207- *
208- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
209- * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
210- */
211- @Override
212- public Date getTimestamp(int i);
213-
214- /**
215- * Returns the value of column {@code name} as a date.
216- *
217- * @param name the name of the column to retrieve.
218- * @return the value of column {@code name} as a date. If the value is NULL,
219- * {@code null} is returned.
220- *
221- * @throws IllegalArgumentException if {@code name} is not part of the
222- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
223- * @throws InvalidTypeException if column {@code name} is not of type TIMESTAMP.
224- */
225- @Override
226- public Date getTimestamp(String name);
227-
228- /**
229- * Returns the {@code i}th value as a date (without time).
230- *
231- * @param i the index ({@code 0 <= i < size()}) to retrieve.
232- * @return the value of the {@code i}th element as a date. If the
233- * value is NULL, {@code null} is returned.
234- *
235- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
236- * @throws InvalidTypeException if value {@code i} is not of type DATE.
237- */
238- @Override
239- public LocalDate getDate(int i);
240-
241- /**
242- * Returns the value for {@code name} as a date (without time).
243- *
244- * @param name the name to retrieve.
245- * @return the value for {@code name} as a date. If the value is NULL,
246- * {@code null} is returned.
247- *
248- * @throws IllegalArgumentException if {@code name} is not valid name for this object.
249- * @throws InvalidTypeException if value {@code name} is not of type DATE.
250- */
251- @Override
252- public LocalDate getDate(String name);
253-
254- /**
255- * Returns the {@code i}th value as a long in nanoseconds since midnight.
256- *
257- * @param i the index ({@code 0 <= i < size()}) to retrieve.
258- * @return the value of the {@code i}th element as a long. If the
259- * value is NULL, {@code 0L} is returned.
260- *
261- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
262- * @throws InvalidTypeException if value {@code i} is not of type TIME.
263- */
264- @Override
265- public long getTime(int i);
266-
267- /**
268- * Returns the value for {@code name} as a long in nanoseconds since midnight.
269- *
270- * @param name the name to retrieve.
271- * @return the value for {@code name} as a long. If the value is NULL,
272- * {@code 0L} is returned.
273- *
274- * @throws IllegalArgumentException if {@code name} is not valid name for this object.
275- * @throws InvalidTypeException if value {@code name} is not of type TIME.
276- */
277- @Override
278- public long getTime(String name);
279-
280- /**
281- * Returns the {@code i}th value of this row as a float.
282- *
283- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
284- * @return the value of the {@code i}th column in this row as a float. If the
285- * value is NULL, {@code 0.0f} is returned.
286- *
287- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
288- * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
289- */
290- @Override
291- public float getFloat(int i);
292-
293- /**
294- * Returns the value of column {@code name} as a float.
295- *
296- * @param name the name of the column to retrieve.
297- * @return the value of column {@code name} as a float. If the value is NULL,
298- * {@code 0.0f} is returned.
299- *
300- * @throws IllegalArgumentException if {@code name} is not part of the
301- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
302- * @throws InvalidTypeException if column {@code name} is not of type FLOAT.
303- */
304- @Override
305- public float getFloat(String name);
306-
307- /**
308- * Returns the {@code i}th value of this row as a double.
309- *
310- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
311- * @return the value of the {@code i}th column in this row as a double. If the
312- * value is NULL, {@code 0.0} is returned.
313- *
314- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
315- * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
316- */
317- @Override
318- public double getDouble(int i);
319-
320- /**
321- * Returns the value of column {@code name} as a double.
322- *
323- * @param name the name of the column to retrieve.
324- * @return the value of column {@code name} as a double. If the value is NULL,
325- * {@code 0.0} is returned.
326- *
327- * @throws IllegalArgumentException if {@code name} is not part of the
328- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
329- * @throws InvalidTypeException if column {@code name} is not of type DOUBLE.
330- */
331- @Override
332- public double getDouble(String name);
333-
334- /**
335- * Returns the {@code i}th value of this row as a ByteBuffer.
336- *
337- * Note: this method always return the bytes composing the value, even if
338- * the column is not of type BLOB. That is, this method never throw an
339- * InvalidTypeException. However, if the type is not BLOB, it is up to the
340- * caller to handle the returned value correctly.
341- *
342- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
343- * @return the value of the {@code i}th column in this row as a ByteBuffer. If the
344- * value is NULL, {@code null} is returned.
345- *
346- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
347- */
348- @Override
349- public ByteBuffer getBytesUnsafe(int i);
350-
351- /**
352- * Returns the value of column {@code name} as a ByteBuffer.
353- *
354- * Note: this method always return the bytes composing the value, even if
355- * the column is not of type BLOB. That is, this method never throw an
356- * InvalidTypeException. However, if the type is not BLOB, it is up to the
357- * caller to handle the returned value correctly.
358- *
359- * @param name the name of the column to retrieve.
360- * @return the value of column {@code name} as a ByteBuffer. If the value is NULL,
361- * {@code null} is returned.
362- *
363- * @throws IllegalArgumentException if {@code name} is not part of the
364- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
365- */
366- @Override
367- public ByteBuffer getBytesUnsafe(String name);
368-
369- /**
370- * Returns the {@code i}th value of this row as a byte array.
371- * <p>
372- * Note that this method validate that the column is of type BLOB. If you want to retrieve
373- * the bytes for any type of columns, use {@link #getBytesUnsafe(int)} instead.
374- *
375- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
376- * @return the value of the {@code i}th column in this row as a byte array. If the
377- * value is NULL, {@code null} is returned.
378- *
379- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
380- * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
381- */
382- @Override
383- public ByteBuffer getBytes(int i);
384-
385- /**
386- * Returns the value of column {@code name} as a byte array.
387- * <p>
388- * Note that this method validate that the column is of type BLOB. If you want to retrieve
389- * the bytes for any type of columns, use {@link #getBytesUnsafe(String)} instead.
390- *
391- * @param name the name of the column to retrieve.
392- * @return the value of column {@code name} as a byte array. If the value is NULL,
393- * {@code null} is returned.
394- *
395- * @throws IllegalArgumentException if {@code name} is not part of the
396- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
397- * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
398- */
399- @Override
400- public ByteBuffer getBytes(String name);
401-
402- /**
403- * Returns the {@code i}th value of this row as a string.
404- *
405- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
406- * @return the value of the {@code i}th column in this row as a string. If the
407- * value is NULL, {@code null} is returned.
408- *
409- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
410- * @throws InvalidTypeException if column {@code i} type is none of:
411- * VARCHAR, TEXT or ASCII.
412- */
413- @Override
414- public String getString(int i);
415-
416- /**
417- * Returns the value of column {@code name} as a string.
418- *
419- * @param name the name of the column to retrieve.
420- * @return the value of column {@code name} as a string. If the value is NULL,
421- * {@code null} is returned.
422- *
423- * @throws IllegalArgumentException if {@code name} is not part of the
424- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
425- * @throws InvalidTypeException if column {@code name} type is none of:
426- * VARCHAR, TEXT or ASCII.
427- */
428- @Override
429- public String getString(String name);
430-
431- /**
432- * Returns the {@code i}th value of this row as a variable length integer.
433- *
434- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
435- * @return the value of the {@code i}th column in this row as a variable
436- * length integer. If the value is NULL, {@code null} is returned.
437- *
438- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
439- * @throws InvalidTypeException if column {@code i} is not of type VARINT.
440- */
441- @Override
442- public BigInteger getVarint(int i);
443-
444- /**
445- * Returns the value of column {@code name} as a variable length integer.
446- *
447- * @param name the name of the column to retrieve.
448- * @return the value of column {@code name} as a variable length integer.
449- * If the value is NULL, {@code null} is returned.
450- *
451- * @throws IllegalArgumentException if {@code name} is not part of the
452- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
453- * @throws InvalidTypeException if column {@code name} is not of type VARINT.
454- */
455- @Override
456- public BigInteger getVarint(String name);
457-
458- /**
459- * Returns the {@code i}th value of this row as a variable length decimal.
460- *
461- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
462- * @return the value of the {@code i}th column in this row as a variable
463- * length decimal. If the value is NULL, {@code null} is returned.
464- *
465- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
466- * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
467- */
468- @Override
469- public BigDecimal getDecimal(int i);
470-
471- /**
472- * Returns the value of column {@code name} as a variable length decimal.
473- *
474- * @param name the name of the column to retrieve.
475- * @return the value of column {@code name} as a variable length decimal.
476- * If the value is NULL, {@code null} is returned.
477- *
478- * @throws IllegalArgumentException if {@code name} is not part of the
479- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
480- * @throws InvalidTypeException if column {@code name} is not of type DECIMAL.
481- */
482- @Override
483- public BigDecimal getDecimal(String name);
484-
485- /**
486- * Returns the {@code i}th value of this row as a UUID.
487- *
488- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
489- * @return the value of the {@code i}th column in this row as a UUID.
490- * If the value is NULL, {@code null} is returned.
491- *
492- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
493- * @throws InvalidTypeException if column {@code i} is not of type UUID
494- * or TIMEUUID.
495- */
496- @Override
497- public UUID getUUID(int i);
498-
499- /**
500- * Returns the value of column {@code name} as a UUID.
501- *
502- * @param name the name of the column to retrieve.
503- * @return the value of column {@code name} as a UUID.
504- * If the value is NULL, {@code null} is returned.
505- *
506- * @throws IllegalArgumentException if {@code name} is not part of the
507- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
508- * @throws InvalidTypeException if column {@code name} is not of type
509- * UUID or TIMEUUID.
510- */
511- @Override
512- public UUID getUUID(String name);
513-
514- /**
515- * Returns the {@code i}th value of this row as an InetAddress.
516- *
517- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
518- * @return the value of the {@code i}th column in this row as an InetAddress.
519- * If the value is NULL, {@code null} is returned.
520- *
521- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
522- * @throws InvalidTypeException if column {@code i} is not of type INET.
523- */
524- @Override
525- public InetAddress getInet(int i);
526-
527- /**
528- * Returns the value of column {@code name} as an InetAddress.
529- *
530- * @param name the name of the column to retrieve.
531- * @return the value of column {@code name} as an InetAddress.
532- * If the value is NULL, {@code null} is returned.
533- *
534- * @throws IllegalArgumentException if {@code name} is not part of the
535- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
536- * @throws InvalidTypeException if column {@code name} is not of type
537- * INET.
538- */
539- @Override
540- public InetAddress getInet(String name);
541-
54236 /**
54337 * Returns the {@code i}th value of this row as a {@link Token}.
54438 * <p>
@@ -593,122 +87,4 @@
59387 */
59488 public Token getPartitionKeyToken();
59589
596- /**
597- * Returns the {@code i}th value of this row as a list.
598- *
599- * @param <T> the type of the elements of the list to return.
600- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
601- * @param elementsClass the class for the elements of the list to retrieve.
602- * @return the value of the {@code i}th column in this row as a list of
603- * {@code elementsClass} objects. If the value is NULL, an empty list is
604- * returned (note that Cassandra makes no difference between an empty list
605- * and column of type list that is not set). The returned list is immutable.
606- *
607- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
608- * @throws InvalidTypeException if column {@code i} is not a list or if its
609- * elements are not of class {@code elementsClass}.
610- */
611- @Override
612- public <T> List<T> getList(int i, Class<T> elementsClass);
613-
614- /**
615- * Returns the value of column {@code name} as a list.
616- *
617- * @param <T> the type of the elements of the list to return.
618- * @param name the name of the column to retrieve.
619- * @param elementsClass the class for the elements of the list to retrieve.
620- * @return the value of the {@code i}th column in this row as a list of
621- * {@code elementsClass} objects. If the value is NULL, an empty list is
622- * returned (note that Cassandra makes no difference between an empty list
623- * and column of type list that is not set). The returned list is immutable.
624- *
625- * @throws IllegalArgumentException if {@code name} is not part of the
626- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
627- * @throws InvalidTypeException if column {@code name} is not a list or if its
628- * elements are not of class {@code elementsClass}.
629- */
630- @Override
631- public <T> List<T> getList(String name, Class<T> elementsClass);
632-
633- /**
634- * Returns the {@code i}th value of this row as a set.
635- *
636- * @param <T> the type of the elements of the set to return.
637- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
638- * @param elementsClass the class for the elements of the set to retrieve.
639- * @return the value of the {@code i}th column in this row as a set of
640- * {@code elementsClass} objects. If the value is NULL, an empty set is
641- * returned (note that Cassandra makes no difference between an empty set
642- * and column of type set that is not set). The returned set is immutable.
643- *
644- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
645- * @throws InvalidTypeException if column {@code i} is not a set or if its
646- * elements are not of class {@code elementsClass}.
647- */
648- @Override
649- public <T> Set<T> getSet(int i, Class<T> elementsClass);
650-
651- /**
652- * Returns the value of column {@code name} as a set.
653- *
654- * @param <T> the type of the elements of the set to return.
655- * @param name the name of the column to retrieve.
656- * @param elementsClass the class for the elements of the set to retrieve.
657- * @return the value of the {@code i}th column in this row as a set of
658- * {@code elementsClass} objects. If the value is NULL, an empty set is
659- * returned (note that Cassandra makes no difference between an empty set
660- * and column of type set that is not set). The returned set is immutable.
661- *
662- * @throws IllegalArgumentException if {@code name} is not part of the
663- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
664- * @throws InvalidTypeException if column {@code name} is not a set or if its
665- * elements are not of class {@code elementsClass}.
666- */
667- @Override
668- public <T> Set<T> getSet(String name, Class<T> elementsClass);
669-
670- /**
671- * Returns the {@code i}th value of this row as a map.
672- *
673- * @param <K> the type of the keys of the map to return.
674- * @param <V> the type of the values of the map to return.
675- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
676- * @param keysClass the class for the keys of the map to retrieve.
677- * @param valuesClass the class for the values of the map to retrieve.
678- * @return the value of the {@code i}th column in this row as a map of
679- * {@code keysClass} to {@code valuesClass} objects. If the value is NULL,
680- * an empty map is returned (note that Cassandra makes no difference
681- * between an empty map and column of type map that is not set). The
682- * returned map is immutable.
683- *
684- * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
685- * @throws InvalidTypeException if column {@code i} is not a map, if its
686- * keys are not of class {@code keysClass} or if its values are not of
687- * class {@code valuesClass}.
688- */
689- @Override
690- public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass);
691-
692- /**
693- * Returns the value of column {@code name} as a map.
694- *
695- * @param <K> the type of the keys of the map to return.
696- * @param <V> the type of the values of the map to return.
697- * @param name the name of the column to retrieve.
698- * @param keysClass the class for the keys of the map to retrieve.
699- * @param valuesClass the class for the values of the map to retrieve.
700- * @return the value of the {@code i}th column in this row as a map of
701- * {@code keysClass} to {@code valuesClass} objects. If the value is NULL,
702- * an empty map is returned (note that Cassandra makes no difference
703- * between an empty map and column of type map that is not set). The
704- * returned map is immutable.
705- *
706- * @throws IllegalArgumentException if {@code name} is not part of the
707- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
708- * @throws InvalidTypeException if column {@code name} is not a map, if its
709- * keys are not of class {@code keysClass} or if its values are not of
710- * class {@code valuesClass}.
711- */
712- @Override
713- public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass);
71490 }
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 +9 −105
@@ -38,7 +38,6 @@
3838 * @return this object.
3939 *
4040 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
41- * @throws InvalidTypeException if value {@code i} is not of type BOOLEAN.
4241 */
4342 public T setBool(int i, boolean v);
4443
@@ -50,7 +49,6 @@
5049 * @return this object.
5150 *
5251 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
53- * @throws InvalidTypeException if value {@code i} is not of type TINYINT.
5452 */
5553 public T setByte(int i, byte v);
5654
@@ -62,7 +60,6 @@
6260 * @return this object.
6361 *
6462 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
65- * @throws InvalidTypeException if value {@code i} is not of type SMALLINT.
6663 */
6764 public T setShort(int i, short v);
6865
@@ -74,7 +71,6 @@
7471 * @return this object.
7572 *
7673 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
77- * @throws InvalidTypeException if value {@code i} is not of type INT.
7874 */
7975 public T setInt(int i, int v);
8076
@@ -86,7 +82,6 @@
8682 * @return this object.
8783 *
8884 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
89- * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
9085 */
9186 public T setLong(int i, long v);
9287
@@ -98,7 +93,6 @@
9893 * @return this object.
9994 *
10095 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
101- * @throws InvalidTypeException if value {@code i} is not of type TIMESTAMP.
10296 */
10397 public T setTimestamp(int i, Date v);
10498
@@ -110,7 +104,6 @@
110104 * @return this object.
111105 *
112106 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
113- * @throws InvalidTypeException if value {@code i} is not of type DATE.
114107 */
115108 public T setDate(int i, LocalDate v);
116109
@@ -122,7 +115,6 @@
122115 * @return this object.
123116 *
124117 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
125- * @throws InvalidTypeException if value {@code i} is not of type TIME.
126118 */
127119 public T setTime(int i, long v);
128120
@@ -134,7 +126,6 @@
134126 * @return this object.
135127 *
136128 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
137- * @throws InvalidTypeException if value {@code i} is not of type FLOAT.
138129 */
139130 public T setFloat(int i, float v);
140131
@@ -146,7 +137,6 @@
146137 * @return this object.
147138 *
148139 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
149- * @throws InvalidTypeException if value {@code i} is not of type DOUBLE.
150140 */
151141 public T setDouble(int i, double v);
152142
@@ -158,8 +148,6 @@
158148 * @return this object.
159149 *
160150 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
161- * @throws InvalidTypeException if value {@code i} is of neither of the
162- * following types: VARCHAR, TEXT or ASCII.
163151 */
164152 public T setString(int i, String v);
165153
@@ -175,7 +163,6 @@
175163 * @return this object.
176164 *
177165 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
178- * @throws InvalidTypeException if value {@code i} is not of type BLOB.
179166 */
180167 public T setBytes(int i, ByteBuffer v);
181168
@@ -203,7 +190,6 @@
203190 * @return this object.
204191 *
205192 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
206- * @throws InvalidTypeException if value {@code i} is not of type VARINT.
207193 */
208194 public T setVarint(int i, BigInteger v);
209195
@@ -215,7 +201,6 @@
215201 * @return this object.
216202 *
217203 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
218- * @throws InvalidTypeException if value {@code i} is not of type DECIMAL.
219204 */
220205 public T setDecimal(int i, BigDecimal v);
221206
@@ -227,9 +212,6 @@
227212 * @return this object.
228213 *
229214 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
230- * @throws InvalidTypeException if value {@code i} is not of type UUID or
231- * TIMEUUID, or if value {@code i} is of type TIMEUUID but {@code v} is
232- * not a type 1 UUID.
233215 */
234216 public T setUUID(int i, UUID v);
235217
@@ -241,7 +223,6 @@
241223 * @return this object.
242224 *
243225 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
244- * @throws InvalidTypeException if value {@code i} is not of type INET.
245226 */
246227 public T setInet(int i, InetAddress v);
247228
@@ -250,12 +231,9 @@
250231 * <p>
251232 * Please note that {@code null} values inside collections are not supported by CQL.
252233 * <p>
253- * Note about performance: this method must perform a runtime inspection of the provided list,
254- * in order to guess the best codec to serialize the list elements.
255- * <p>
256- * Furthermore, if two or more codecs are available
257- * for the underlying CQL type ({@code list}), <em>which one will be used will depend
258- * on the actual object being serialized</em>.
234+ * Note: if two or more codecs are available
235+ * for the underlying CQL type, <em>the one that will be used will be
236+ * the first one to be registered.</em>.
259237 * <p>
260238 * For these reasons, it is generally preferable to use the more
261239 * deterministic methods {@link #setList(int, List, Class)} or
@@ -266,9 +244,6 @@
266244 * @return this object.
267245 *
268246 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
269- * @throws InvalidTypeException if value {@code i} is not a list type or
270- * if the elements of {@code v} are not of the type of the elements of
271- * column {@code i}.
272247 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
273248 * by CQL.
274249 */
@@ -290,9 +265,6 @@
290265 * @return this object.
291266 *
292267 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
293- * @throws InvalidTypeException if value {@code i} is not a list type or
294- * if the elements of {@code v} are not of the type of the elements of
295- * column {@code i}.
296268 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
297269 * by CQL.
298270 */
@@ -314,9 +286,6 @@
314286 * @return this object.
315287 *
316288 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
317- * @throws InvalidTypeException if value {@code i} is not a list type or
318- * if the elements of {@code v} are not of the type of the elements of
319- * column {@code i}.
320289 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
321290 * by CQL.
322291 */
@@ -327,14 +296,9 @@
327296 * <p>
328297 * Please note that {@code null} values are not supported inside collection by CQL.
329298 * <p>
330- * Note about performance: this method must perform a runtime inspection of the provided map,
331- * in order to guess the best codec to serialize the map entries.
332- * The result of such inspection cannot be cached and thus must be performed for each invocation
333- * of this method, which may incur in a performance penalty.
334- * <p>
335- * Furthermore, if two or more codecs are available
336- * for the underlying CQL type ({@code map}), <em>which one will be used will depend
337- * on the actual object being serialized</em>.
299+ * Note: if two or more codecs are available
300+ * for the underlying CQL type, <em>the one that will be used will be
301+ * the first one to be registered.</em>.
338302 * <p>
339303 * For these reasons, it is generally preferable to use the more
340304 * deterministic methods {@link #setMap(int, Map, Class, Class)} or
@@ -345,9 +309,6 @@
345309 * @return this object.
346310 *
347311 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
348- * @throws InvalidTypeException if value {@code i} is not a map type or
349- * if the elements (keys or values) of {@code v} are not of the type of the
350- * elements of column {@code i}.
351312 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
352313 * by CQL.
353314 */
@@ -370,9 +331,6 @@
370331 * @return this object.
371332 *
372333 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
373- * @throws InvalidTypeException if value {@code i} is not a map type or
374- * if the elements of {@code v} are not of the type of the elements of
375- * column {@code i}.
376334 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
377335 * by CQL.
378336 */
@@ -395,9 +353,6 @@
395353 * @return this object.
396354 *
397355 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
398- * @throws InvalidTypeException if value {@code i} is not a map type or
399- * if the elements of {@code v} are not of the type of the elements of
400- * column {@code i}.
401356 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
402357 * by CQL.
403358 */
@@ -408,14 +363,9 @@
408363 * <p>
409364 * Please note that {@code null} values are not supported inside collection by CQL.
410365 * <p>
411- * Note about performance: this method must perform a runtime inspection of the provided set,
412- * in order to guess the best codec to serialize the set elements.
413- * The result of such inspection cannot be cached and thus must be performed for each invocation
414- * of this method, which may incur in a performance penalty.
415- * <p>
416- * Furthermore, if two or more codecs are available
417- * for the underlying CQL type ({@code set}), <em>which one will be used will depend
418- * on the actual object being serialized</em>.
366+ * Note: if two or more codecs are available
367+ * for the underlying CQL type, <em>the one that will be used will be
368+ * the first one to be registered.</em>.
419369 * <p>
420370 * For these reasons, it is generally preferable to use the more
421371 * deterministic methods {@link #setSet(int, Set, Class)} or
@@ -426,9 +376,6 @@
426376 * @return this object.
427377 *
428378 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
429- * @throws InvalidTypeException if value {@code i} is not a set type or
430- * if the elements of {@code v} are not of the type of the elements of
431- * column {@code i}.
432379 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
433380 * by CQL.
434381 */
@@ -450,9 +397,6 @@
450397 * @return this object.
451398 *
452399 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
453- * @throws InvalidTypeException if value {@code i} is not a set type or
454- * if the elements of {@code v} are not of the type of the elements of
455- * column {@code i}.
456400 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
457401 * by CQL.
458402 */
@@ -474,9 +418,6 @@
474418 * @return this object.
475419 *
476420 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
477- * @throws InvalidTypeException if value {@code i} is not a set type or
478- * if the elements of {@code v} are not of the type of the elements of
479- * column {@code i}.
480421 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
481422 * by CQL.
482423 */
@@ -490,8 +431,6 @@
490431 * @return this object.
491432 *
492433 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
493- * @throws InvalidTypeException if value {@code i} is not a UDT value or if its definition
494- * does not correspond to the one of {@code v}.
495434 */
496435 public T setUDTValue(int i, UDTValue v);
497436
@@ -503,8 +442,6 @@
503442 * @return this object.
504443 *
505444 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
506- * @throws InvalidTypeException if value {@code i} is not a tuple value or if its types
507- * do not correspond to the ones of {@code v}.
508445 */
509446 public T setTupleValue(int i, TupleValue v);
510447
@@ -519,39 +456,11 @@
519456 */
520457 public T setToNull(int i);
521458
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-
545459 /**
546460 * Sets the {@code i}th value to the provided value of the provided Java class.
547461 * <p>
548462 * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
549463 * 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.
555464 *
556465 * @param i the index of the value to set.
557466 * @param v the value to set; may be {@code null}.
@@ -566,11 +475,6 @@
566475 * <p>
567476 * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
568477 * 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.
574478 *
575479 * @param i the index of the value to set.
576480 * @param v the value to set; may be {@code null}.
modified driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java +14 −125
@@ -40,7 +40,6 @@
4040 * @return this object.
4141 *
4242 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
43- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type BOOLEAN.
4443 */
4544 public T setBool(String name, boolean v);
4645
@@ -54,7 +53,6 @@
5453 * @return this object.
5554 *
5655 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
57- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type TINYINT.
5856 */
5957 public T setByte(String name, byte v);
6058
@@ -68,7 +66,6 @@
6866 * @return this object.
6967 *
7068 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
71- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type SMALLINT.
7269 */
7370 public T setShort(String name, short v);
7471
@@ -82,7 +79,6 @@
8279 * @return this object.
8380 *
8481 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
85- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type INT.
8682 */
8783 public T setInt(String name, int v);
8884
@@ -96,8 +92,6 @@
9692 * @return this object.
9793 *
9894 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
99- * @throws InvalidTypeException if (any occurrence of) {@code name} is
100- * not of type BIGINT or COUNTER.
10195 */
10296 public T setLong(String name, long v);
10397
@@ -111,8 +105,6 @@
111105 * @return this object.
112106 *
113107 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
114- * @throws InvalidTypeException if (any occurrence of) {@code name} is
115- * not of type TIMESTAMP.
116108 */
117109 public T setTimestamp(String name, Date v);
118110
@@ -126,8 +118,6 @@
126118 * @return this object.
127119 *
128120 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
129- * @throws InvalidTypeException if (any occurrence of) {@code name} is
130- * not of type DATE.
131121 */
132122 public T setDate(String name, LocalDate v);
133123
@@ -141,8 +131,6 @@
141131 * @return this object.
142132 *
143133 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
144- * @throws InvalidTypeException if (any occurrence of) {@code name} is
145- * not of type TIME.
146134 */
147135 public T setTime(String name, long v);
148136
@@ -156,8 +144,6 @@
156144 * @return this object.
157145 *
158146 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
159- * @throws InvalidTypeException if (any occurrence of) {@code name} is
160- * not of type FLOAT.
161147 */
162148 public T setFloat(String name, float v);
163149
@@ -171,8 +157,6 @@
171157 * @return this object.
172158 *
173159 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
174- * @throws InvalidTypeException if (any occurrence of) {@code name} is
175- * not of type DOUBLE.
176160 */
177161 public T setDouble(String name, double v);
178162
@@ -186,8 +170,6 @@
186170 * @return this object.
187171 *
188172 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
189- * @throws InvalidTypeException if (any occurrence of) {@code name} is
190- * of neither of the following types: VARCHAR, TEXT or ASCII.
191173 */
192174 public T setString(String name, String v);
193175
@@ -205,7 +187,6 @@
205187 * @return this object.
206188 *
207189 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
208- * @throws InvalidTypeException if (any occurrence of) {@code name} is not of type BLOB.
209190 */
210191 public T setBytes(String name, ByteBuffer v);
211192
@@ -237,8 +218,6 @@
237218 * @return this object.
238219 *
239220 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
240- * @throws InvalidTypeException if (any occurrence of) {@code name} is
241- * not of type VARINT.
242221 */
243222 public T setVarint(String name, BigInteger v);
244223
@@ -252,8 +231,6 @@
252231 * @return this object.
253232 *
254233 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
255- * @throws InvalidTypeException if (any occurrence of) {@code name} is
256- * not of type DECIMAL.
257234 */
258235 public T setDecimal(String name, BigDecimal v);
259236
@@ -267,9 +244,6 @@
267244 * @return this object.
268245 *
269246 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
270- * @throws InvalidTypeException if (any occurrence of) {@code name} is
271- * not of type UUID or TIMEUUID, or if value {@code name} is of type
272- * TIMEUUID but {@code v} is not a type 1 UUID.
273247 */
274248 public T setUUID(String name, UUID v);
275249
@@ -283,8 +257,6 @@
283257 * @return this object.
284258 *
285259 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
286- * @throws InvalidTypeException if (any occurrence of) {@code name} is
287- * not of type INET.
288260 */
289261 public T setInet(String name, InetAddress v);
290262
@@ -294,14 +266,9 @@
294266 * <p>
295267 * Please note that {@code null} values inside collections are not supported by CQL.
296268 * <p>
297- * Note about performance: this method must perform a runtime inspection of the provided list,
298- * in order to guess the best codec to serialize the list elements.
299- * The result of such inspection cannot be cached and thus must be performed for each invocation
300- * of this method, which may incur in a performance penalty.
301- * <p>
302- * Furthermore, if two or more codecs are available
303- * for the underlying CQL type ({@code list}), <em>which one will be used will depend
304- * on the actual object being serialized</em>.
269+ * Note: if two or more codecs are available
270+ * for the underlying CQL type, <em>the one that will be used will be
271+ * the first one to be registered.</em>.
305272 * <p>
306273 * For these reasons, it is generally preferable to use the more
307274 * deterministic methods {@link #setList(String, List, Class)} or
@@ -313,9 +280,6 @@
313280 * @return this object.
314281 *
315282 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
316- * @throws InvalidTypeException if (any occurrence of) {@code name} is
317- * not a list type or if the elements of {@code v} are not of the type of
318- * the elements of column {@code name}.
319283 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
320284 * by CQL.
321285 */
@@ -336,10 +300,7 @@
336300 * @param elementsClass the class for the elements of the list.
337301 * @return this object.
338302 *
339- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
340- * @throws InvalidTypeException if value {@code i} is not a list type or
341- * if the elements of {@code v} are not of the type of the elements of
342- * column {@code i}.
303+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
343304 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
344305 * by CQL.
345306 */
@@ -360,10 +321,7 @@
360321 * @param elementsType the type for the elements of the list.
361322 * @return this object.
362323 *
363- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
364- * @throws InvalidTypeException if value {@code i} is not a list type or
365- * if the elements of {@code v} are not of the type of the elements of
366- * column {@code i}.
324+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
367325 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
368326 * by CQL.
369327 */
@@ -375,14 +333,10 @@
375333 * <p>
376334 * Please note that {@code null} values are not supported inside collection by CQL.
377335 * <p>
378- * Note about performance: this method must perform a runtime inspection of the provided map,
379- * in order to guess the best codec to serialize the map entries.
380- * The result of such inspection cannot be cached and thus must be performed for each invocation
381- * of this method, which may incur in a performance penalty.
382336 * <p>
383- * Furthermore, if two or more codecs are available
384- * for the underlying CQL type ({@code map}), <em>which one will be used will depend
385- * on the actual object being serialized</em>.
337+ * Note: if two or more codecs are available
338+ * for the underlying CQL type, <em>the one that will be used will be
339+ * the first one to be registered.</em>.
386340 * <p>
387341 * For these reasons, it is generally preferable to use the more
388342 * deterministic methods {@link #setMap(String, Map, Class, Class)} or
@@ -394,9 +348,6 @@
394348 * @return this object.
395349 *
396350 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
397- * @throws InvalidTypeException if (any occurrence of) {@code name} is
398- * not a map type or if the elements (keys or values) of {@code v} are not of
399- * the type of the elements of column {@code name}.
400351 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
401352 * by CQL.
402353 */
@@ -420,9 +371,6 @@
420371 * @return this object.
421372 *
422373 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
423- * @throws InvalidTypeException if (any occurrence of) {@code name} is
424- * not a map type or if the elements (keys or values) of {@code v} are not of
425- * the type of the elements of column {@code name}.
426374 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
427375 * by CQL.
428376 */
@@ -446,9 +394,6 @@
446394 * @return this object.
447395 *
448396 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
449- * @throws InvalidTypeException if (any occurrence of) {@code name} is
450- * not a map type or if the elements (keys or values) of {@code v} are not of
451- * the type of the elements of column {@code name}.
452397 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
453398 * by CQL.
454399 */
@@ -460,14 +405,9 @@
460405 * <p>
461406 * Please note that {@code null} values are not supported inside collection by CQL.
462407 * <p>
463- * Note about performance: this method must perform a runtime inspection of the provided map,
464- * in order to guess the best codec to serialize the set elements.
465- * The result of such inspection cannot be cached and thus must be performed for each invocation
466- * of this method, which may incur in a performance penalty.
467- * <p>
468- * Furthermore, if two or more codecs are available
469- * for the underlying CQL type ({@code set}), <em>which one will be used will depend
470- * on the actual object being serialized</em>.
408+ * Note: if two or more codecs are available
409+ * for the underlying CQL type, <em>the one that will be used will be
410+ * the first one to be registered.</em>.
471411 * <p>
472412 * For these reasons, it is generally preferable to use the more
473413 * deterministic methods {@link #setSet(String, Set, Class)} or
@@ -479,9 +419,6 @@
479419 * @return this object.
480420 *
481421 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
482- * @throws InvalidTypeException if (any occurrence of) {@code name} is
483- * not a map type or if the elements of {@code v} are not of the type of
484- * the elements of column {@code name}.
485422 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
486423 * by CQL.
487424 */
@@ -503,9 +440,6 @@
503440 * @return this object.
504441 *
505442 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
506- * @throws InvalidTypeException if (any occurrence of) {@code name} is
507- * not a map type or if the elements (keys or values) of {@code v} are not of
508- * the type of the elements of column {@code name}.
509443 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
510444 * by CQL.
511445 */
@@ -527,9 +461,6 @@
527461 * @return this object.
528462 *
529463 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
530- * @throws InvalidTypeException if (any occurrence of) {@code name} is
531- * not a map type or if the elements (keys or values) of {@code v} are not of
532- * the type of the elements of column {@code name}.
533464 * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
534465 * by CQL.
535466 */
@@ -545,11 +476,6 @@
545476 * @return this object.
546477 *
547478 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
548- * @throws InvalidTypeException if value {@code i} is not a UDT value or if its definition
549- * does not correspond to the one of {@code v}.
550- * @throws InvalidTypeException if (any occurrence of) {@code name} is
551- * not a UDT value or if the definition of column {@code name} does not correspond to
552- * the one of {@code v}.
553479 */
554480 public T setUDTValue(String name, UDTValue v);
555481
@@ -563,9 +489,6 @@
563489 * @return this object.
564490 *
565491 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
566- * @throws InvalidTypeException if (any occurrence of) {@code name} is
567- * not a tuple value or if the types of column {@code name} do not correspond to
568- * the ones of {@code v}.
569492 */
570493 public T setTupleValue(String name, TupleValue v);
571494
@@ -581,46 +504,18 @@
581504 */
582505 public T setToNull(String name);
583506
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-
607507 /**
608508 * Sets the value for (all occurrences of) variable {@code name} to the provided value of the provided Java class.
609509 * <p>
610510 * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
611511 * 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.
617512 *
618513 * @param name the name of the value to set; if {@code name} is present multiple
619514 * times, all its values are set.
620515 * @param v the value to set; may be {@code null}.
621516 * @param targetClass The Java class to convert to; must not be {@code null};
622517 * @return this object.
623- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
518+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
624519 */
625520 <V> T set(String name, V v, Class<V> targetClass);
626521
@@ -629,18 +524,13 @@
629524 * <p>
630525 * A suitable {@link TypeCodec} instance for the underlying CQL type and the provided class must
631526 * 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.
637527 *
638528 * @param name the name of the value to set; if {@code name} is present multiple
639529 * times, all its values are set.
640530 * @param v the value to set; may be {@code null}.
641531 * @param targetType The Java type to convert to; must not be {@code null};
642532 * @return this object.
643- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
533+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
644534 */
645535 <V> T set(String name, V v, TypeToken<V> targetType);
646536
@@ -660,9 +550,8 @@
660550 * @param codec The {@link TypeCodec} to use to serialize the value; may not be {@code null}.
661551 * @return this object.
662552 * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
663- * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
553+ * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
664554 */
665555 <V> T set(String name, V v, TypeCodec<V> codec);
666556
667-
668557 }
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 +549 −496
@@ -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
@@ -192,9 +455,13 @@
192455 * <li>Null or empty buffers should be gracefully handled and no exception should be raised;
193456 * these should be considered as the equivalent of a NULL CQL value and, in most cases, should
194457 * map to {@code null} or a default value for the corresponding Java type, if applicable;</li>
195- * <li>Codecs for CQL collection types should return unmodifiable collections;</li>
458+ * <li>Codecs for CQL collection types should clearly document whether they return immutable collections or not
459+ * (note that the driver's default collection codecs return <em>mutable</em> collections);</li>
196460 * <li>Codecs for CQL collection types should avoid returning {@code null};
197- * they should return empty collections instead.</li>
461+ * 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>
198465 * </ol>
199466 *
200467 * @param bytes A {@link ByteBuffer} instance containing the serialized form of T;
@@ -248,7 +515,7 @@
248515 */
249516 public boolean accepts(TypeToken javaType) {
250517 checkNotNull(javaType);
251- if(javaType.isPrimitive()) {
518+ if (javaType.isPrimitive()) {
252519 javaType = primitiveToWrapperMap.get(javaType);
253520 }
254521 // TODO accept generics type covariance, i.e. a codec for List<Number> should accept List<Integer>
@@ -301,119 +568,203 @@
301568 return accepts(TypeToken.of(value.getClass()));
302569 }
303570
304- @Override
305- public boolean equals(Object o) {
306- if (this == o)
307- return true;
308- if (!(o instanceof TypeCodec))
309- return false;
310- TypeCodec<?> typeCodec = (TypeCodec<?>)o;
311- return Objects.equal(javaType, typeCodec.javaType) && Objects.equal(cqlType, typeCodec.cqlType);
312- }
313-
314- @Override
315- public int hashCode() {
316- return Objects.hashCode(javaType, cqlType);
317- }
318-
319571 @Override
320572 public String toString() {
321573 return String.format("%s [%s <-> %s]", this.getClass().getSimpleName(), cqlType, javaType);
322574 }
323575
324576 /**
325- * An interface for codecs that are capable of handling primitive booleans,
577+ * A codec that is capable of handling primitive booleans,
326578 * thus avoiding the overhead of boxing and unboxing such primitives.
327579 */
328- 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);
329587
330- ByteBuffer serializeNoBoxing(boolean v, ProtocolVersion protocolVersion);
331- boolean deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
588+ public abstract boolean deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
332589
590+ @Override
591+ public ByteBuffer serialize(Boolean value, ProtocolVersion protocolVersion) {
592+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
593+ }
594+
595+ @Override
596+ public Boolean deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
597+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
598+ }
333599 }
334600
335601 /**
336- * An interface for codecs that are capable of handling primitive bytes,
602+ * A codec that is capable of handling primitive bytes,
337603 * thus avoiding the overhead of boxing and unboxing such primitives.
338604 */
339- public interface PrimitiveByteCodec {
605+ public static abstract class PrimitiveByteCodec extends TypeCodec<Byte> {
606+
607+ protected PrimitiveByteCodec(DataType cqlType) {
608+ super(cqlType, Byte.class);
609+ }
340610
341- ByteBuffer serializeNoBoxing(byte v, ProtocolVersion protocolVersion);
342- byte deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
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+ }
343619
620+ @Override
621+ public Byte deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
622+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
623+ }
344624 }
345625
346626 /**
347- * An interface for codecs that are capable of handling primitive shorts,
627+ * A codec that is capable of handling primitive shorts,
348628 * thus avoiding the overhead of boxing and unboxing such primitives.
349629 */
350- public interface PrimitiveShortCodec {
630+ public static abstract class PrimitiveShortCodec extends TypeCodec<Short>{
631+
632+ protected PrimitiveShortCodec(DataType cqlType) {
633+ super(cqlType, Short.class);
634+ }
635+
636+ public abstract ByteBuffer serializeNoBoxing(short v, ProtocolVersion protocolVersion);
637+
638+ public abstract short deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
351639
352- ByteBuffer serializeNoBoxing(short v, ProtocolVersion protocolVersion);
353- short deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
640+ @Override
641+ public ByteBuffer serialize(Short value, ProtocolVersion protocolVersion) {
642+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
643+ }
354644
645+ @Override
646+ public Short deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
647+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
648+ }
355649 }
356650
357651 /**
358- * An interface for codecs that are capable of handling primitive ints,
652+ * A codec that is capable of handling primitive ints,
359653 * thus avoiding the overhead of boxing and unboxing such primitives.
360654 */
361- public interface PrimitiveIntCodec {
655+ public static abstract class PrimitiveIntCodec extends TypeCodec<Integer> {
362656
363- ByteBuffer serializeNoBoxing(int v, ProtocolVersion protocolVersion);
364- int deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
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);
664+
665+ @Override
666+ public ByteBuffer serialize(Integer value, ProtocolVersion protocolVersion) {
667+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
668+ }
365669
670+ @Override
671+ public Integer deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
672+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
673+ }
366674 }
367675
368676 /**
369- * An interface for codecs that are capable of handling primitive longs,
677+ * A codec that is capable of handling primitive longs,
370678 * thus avoiding the overhead of boxing and unboxing such primitives.
371679 */
372- public interface PrimitiveLongCodec {
680+ public static abstract class PrimitiveLongCodec extends TypeCodec<Long> {
373681
374- ByteBuffer serializeNoBoxing(long v, ProtocolVersion protocolVersion);
375- long deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
682+ protected PrimitiveLongCodec(DataType cqlType) {
683+ super(cqlType, Long.class);
684+ }
685+
686+ public abstract ByteBuffer serializeNoBoxing(long v, ProtocolVersion protocolVersion);
687+
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+ }
376694
695+ @Override
696+ public Long deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
697+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
698+ }
377699 }
378700
379701 /**
380- * An interface for codecs that are capable of handling primitive floats,
702+ * A codec that is capable of handling primitive floats,
381703 * thus avoiding the overhead of boxing and unboxing such primitives.
382704 */
383- 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);
712+
713+ public abstract float deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
384714
385- ByteBuffer serializeNoBoxing(float v, ProtocolVersion protocolVersion);
386- float deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
715+ @Override
716+ public ByteBuffer serialize(Float value, ProtocolVersion protocolVersion) {
717+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
718+ }
387719
720+ @Override
721+ public Float deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
722+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
723+ }
388724 }
389725
390726 /**
391- * An interface for codecs that are capable of handling primitive doubles,
727+ * A codec that is capable of handling primitive doubles,
392728 * thus avoiding the overhead of boxing and unboxing such primitives.
393729 */
394- public interface PrimitiveDoubleCodec {
730+ public static abstract class PrimitiveDoubleCodec extends TypeCodec<Double> {
731+
732+ protected PrimitiveDoubleCodec(DataType cqlType) {
733+ super(cqlType, Double.class);
734+ }
735+
736+ public abstract ByteBuffer serializeNoBoxing(double v, ProtocolVersion protocolVersion);
395737
396- ByteBuffer serializeNoBoxing(double v, ProtocolVersion protocolVersion);
397- double deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
738+ public abstract double deserializeNoBoxing(ByteBuffer v, ProtocolVersion protocolVersion);
398739
740+ @Override
741+ public ByteBuffer serialize(Double value, ProtocolVersion protocolVersion) {
742+ return value == null ? null : serializeNoBoxing(value, protocolVersion);
743+ }
744+
745+ @Override
746+ public Double deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
747+ return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
748+ }
399749 }
400750
401751 /**
402752 * Base class for codecs handling CQL string types such as {@link DataType#varchar()},
403753 * {@link DataType#text()} or {@link DataType#ascii()}.
404754 */
405- public static abstract class StringCodec extends TypeCodec<String> {
755+ private static abstract class StringCodec extends TypeCodec<String> {
406756
407757 private final Charset charset;
408758
409- public StringCodec(DataType cqlType, Charset charset) {
759+ private StringCodec(DataType cqlType, Charset charset) {
410760 super(cqlType, String.class);
411761 this.charset = charset;
412762 }
413763
414764 @Override
415765 public String parse(String value) {
416- if (value == null || value.isEmpty() || value.equals(NULL)) return null;
766+ if (value == null || value.isEmpty() || value.equals("NULL"))
767+ return null;
417768 if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
418769 throw new InvalidTypeException("text or varchar values must be enclosed by single quotes");
419770
@@ -423,13 +774,13 @@
423774 @Override
424775 public String format(String value) {
425776 if (value == null)
426- return NULL;
777+ return "NULL";
427778 return '\'' + replace(value, '\'', "''") + '\'';
428779 }
429780
430781 // Simple method to replace a single character. String.replace is a bit too
431782 // inefficient (see JAVA-67)
432- static String replace(String text, char search, String replacement) {
783+ private static String replace(String text, char search, String replacement) {
433784 if (text == null || text.isEmpty())
434785 return text;
435786
@@ -474,7 +825,7 @@
474825 public String deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
475826 if (bytes == null)
476827 return null;
477- if(bytes.remaining() == 0)
828+ if (bytes.remaining() == 0)
478829 return "";
479830 return new String(Bytes.getArray(bytes), charset);
480831 }
@@ -485,12 +836,12 @@
485836 * Note that this codec also handles {@link DataType#text()}, which is merely
486837 * an alias for {@link DataType#varchar()}.
487838 */
488- public static class VarcharCodec extends StringCodec {
839+ private static class VarcharCodec extends StringCodec {
489840
490- public static final VarcharCodec instance = new VarcharCodec();
841+ private static final VarcharCodec instance = new VarcharCodec();
491842
492843 private VarcharCodec() {
493- super(varchar(), Charset.forName("UTF-8"));
844+ super(DataType.varchar(), Charset.forName("UTF-8"));
494845 }
495846
496847 }
@@ -498,22 +849,19 @@
498849 /**
499850 * This codec maps a CQL {@link DataType#ascii()} to a Java {@link String}.
500851 */
501- public static class AsciiCodec extends StringCodec {
852+ private static class AsciiCodec extends StringCodec {
502853
503- public static final AsciiCodec instance = new AsciiCodec();
854+ private static final AsciiCodec instance = new AsciiCodec();
504855
505856 private static final Pattern ASCII_PATTERN = Pattern.compile("^\\p{ASCII}*$");
506857
507858 private AsciiCodec() {
508- super(ascii(), Charset.forName("US-ASCII"));
859+ super(DataType.ascii(), Charset.forName("US-ASCII"));
509860 }
510861
511862 @Override
512863 public boolean accepts(Object value) {
513- if (value instanceof String) {
514- return ASCII_PATTERN.matcher((String)value).matches();
515- }
516- return false;
864+ return value instanceof String && ASCII_PATTERN.matcher((String)value).matches();
517865 }
518866
519867 }
@@ -522,16 +870,16 @@
522870 * Base class for codecs handling CQL 8-byte integer types such as {@link DataType#bigint()},
523871 * {@link DataType#counter()} or {@link DataType#time()}.
524872 */
525- public abstract static class LongCodec extends TypeCodec<Long> implements PrimitiveLongCodec {
873+ private abstract static class LongCodec extends PrimitiveLongCodec {
526874
527- public LongCodec(DataType cqlType) {
528- super(cqlType, Long.class);
875+ private LongCodec(DataType cqlType) {
876+ super(cqlType);
529877 }
530878
531879 @Override
532880 public Long parse(String value) {
533881 try {
534- 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);
535883 } catch (NumberFormatException e) {
536884 throw new InvalidTypeException(String.format("Cannot parse 64-bits long value from \"%s\"", value));
537885 }
@@ -540,15 +888,10 @@
540888 @Override
541889 public String format(Long value) {
542890 if (value == null)
543- return NULL;
891+ return "NULL";
544892 return Long.toString(value);
545893 }
546894
547- @Override
548- public ByteBuffer serialize(Long value, ProtocolVersion protocolVersion) {
549- return value == null ? null : serializeNoBoxing(value, protocolVersion);
550- }
551-
552895 @Override
553896 public ByteBuffer serializeNoBoxing(long value, ProtocolVersion protocolVersion) {
554897 ByteBuffer bb = ByteBuffer.allocate(8);
@@ -556,11 +899,6 @@
556899 return bb;
557900 }
558901
559- @Override
560- public Long deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
561- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
562- }
563-
564902 @Override
565903 public long deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
566904 if (bytes == null || bytes.remaining() == 0)
@@ -575,12 +913,12 @@
575913 /**
576914 * This codec maps a CQL {@link DataType#bigint()} to a Java {@link Long}.
577915 */
578- public static class BigintCodec extends LongCodec {
916+ private static class BigintCodec extends LongCodec {
579917
580- public static final BigintCodec instance = new BigintCodec();
918+ private static final BigintCodec instance = new BigintCodec();
581919
582920 private BigintCodec() {
583- super(bigint());
921+ super(DataType.bigint());
584922 }
585923
586924 }
@@ -588,12 +926,12 @@
588926 /**
589927 * This codec maps a CQL {@link DataType#counter()} to a Java {@link Long}.
590928 */
591- public static class CounterCodec extends LongCodec {
929+ private static class CounterCodec extends LongCodec {
592930
593- public static final CounterCodec instance = new CounterCodec();
931+ private static final CounterCodec instance = new CounterCodec();
594932
595933 private CounterCodec() {
596- super(counter());
934+ super(DataType.counter());
597935 }
598936
599937 }
@@ -601,23 +939,23 @@
601939 /**
602940 * This codec maps a CQL {@link DataType#blob()} to a Java {@link ByteBuffer}.
603941 */
604- public static class BlobCodec extends TypeCodec<ByteBuffer> {
942+ private static class BlobCodec extends TypeCodec<ByteBuffer> {
605943
606- public static final BlobCodec instance = new BlobCodec();
944+ private static final BlobCodec instance = new BlobCodec();
607945
608946 private BlobCodec() {
609- super(blob(), ByteBuffer.class);
947+ super(DataType.blob(), ByteBuffer.class);
610948 }
611949
612950 @Override
613951 public ByteBuffer parse(String value) {
614- 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);
615953 }
616954
617955 @Override
618956 public String format(ByteBuffer value) {
619957 if (value == null)
620- return NULL;
958+ return "NULL";
621959 return Bytes.toHexString(value);
622960 }
623961
@@ -633,26 +971,26 @@
633971 }
634972
635973 /**
636- * 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}.
637975 * Note that no instance of this codec is part of the default set of codecs used by the Java driver;
638976 * instances of this codec must be manually registered.
639977 */
640- public static class CustomCodec extends TypeCodec<ByteBuffer> {
978+ private static class CustomCodec extends TypeCodec<ByteBuffer> {
641979
642- public CustomCodec(DataType custom) {
980+ private CustomCodec(DataType custom) {
643981 super(custom, ByteBuffer.class);
644982 assert custom.getName() == Name.CUSTOM;
645983 }
646984
647985 @Override
648986 public ByteBuffer parse(String value) {
649- 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);
650988 }
651989
652990 @Override
653991 public String format(ByteBuffer value) {
654992 if (value == null)
655- return NULL;
993+ return "NULL";
656994 return Bytes.toHexString(value);
657995 }
658996
@@ -670,20 +1008,20 @@
6701008 /**
6711009 * This codec maps a CQL {@link DataType#cboolean()} to a Java {@link Boolean}.
6721010 */
673- public static class BooleanCodec extends TypeCodec<Boolean> implements PrimitiveBooleanCodec {
1011+ private static class BooleanCodec extends PrimitiveBooleanCodec {
6741012
6751013 private static final ByteBuffer TRUE = ByteBuffer.wrap(new byte[]{ 1 });
6761014 private static final ByteBuffer FALSE = ByteBuffer.wrap(new byte[]{ 0 });
6771015
678- public static final BooleanCodec instance = new BooleanCodec();
1016+ private static final BooleanCodec instance = new BooleanCodec();
6791017
6801018 private BooleanCodec() {
681- super(cboolean(), Boolean.class);
1019+ super(DataType.cboolean());
6821020 }
6831021
6841022 @Override
6851023 public Boolean parse(String value) {
686- if (value == null || value.isEmpty() || value.equals(NULL))
1024+ if (value == null || value.isEmpty() || value.equals("NULL"))
6871025 return null;
6881026 if (value.equalsIgnoreCase(Boolean.FALSE.toString()))
6891027 return false;
@@ -696,25 +1034,15 @@
6961034 @Override
6971035 public String format(Boolean value) {
6981036 if (value == null)
699- return NULL;
1037+ return "NULL";
7001038 return value ? "true" : "false";
7011039 }
7021040
703- @Override
704- public ByteBuffer serialize(Boolean value, ProtocolVersion protocolVersion) {
705- return value == null ? null : serializeNoBoxing(value, protocolVersion);
706- }
707-
7081041 @Override
7091042 public ByteBuffer serializeNoBoxing(boolean value, ProtocolVersion protocolVersion) {
7101043 return value ? TRUE.duplicate() : FALSE.duplicate();
7111044 }
7121045
713- @Override
714- public Boolean deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
715- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
716- }
717-
7181046 @Override
7191047 public boolean deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
7201048 if (bytes == null || bytes.remaining() == 0)
@@ -729,18 +1057,18 @@
7291057 /**
7301058 * This codec maps a CQL {@link DataType#decimal()} to a Java {@link BigDecimal}.
7311059 */
732- public static class DecimalCodec extends TypeCodec<BigDecimal> {
1060+ private static class DecimalCodec extends TypeCodec<BigDecimal> {
7331061
734- public static final DecimalCodec instance = new DecimalCodec();
1062+ private static final DecimalCodec instance = new DecimalCodec();
7351063
7361064 private DecimalCodec() {
737- super(decimal(), BigDecimal.class);
1065+ super(DataType.decimal(), BigDecimal.class);
7381066 }
7391067
7401068 @Override
7411069 public BigDecimal parse(String value) {
7421070 try {
743- 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);
7441072 } catch (NumberFormatException e) {
7451073 throw new InvalidTypeException(String.format("Cannot parse decimal value from \"%s\"", value));
7461074 }
@@ -749,7 +1077,7 @@
7491077 @Override
7501078 public String format(BigDecimal value) {
7511079 if (value == null)
752- return NULL;
1080+ return "NULL";
7531081 return value.toString();
7541082 }
7551083
@@ -788,18 +1116,18 @@
7881116 /**
7891117 * This codec maps a CQL {@link DataType#cdouble()} to a Java {@link Double}.
7901118 */
791- public static class DoubleCodec extends TypeCodec<Double> implements PrimitiveDoubleCodec {
1119+ private static class DoubleCodec extends PrimitiveDoubleCodec {
7921120
793- public static final DoubleCodec instance = new DoubleCodec();
1121+ private static final DoubleCodec instance = new DoubleCodec();
7941122
7951123 private DoubleCodec() {
796- super(cdouble(), Double.class);
1124+ super(DataType.cdouble());
7971125 }
7981126
7991127 @Override
8001128 public Double parse(String value) {
8011129 try {
802- 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);
8031131 } catch (NumberFormatException e) {
8041132 throw new InvalidTypeException(String.format("Cannot parse 64-bits double value from \"%s\"", value));
8051133 }
@@ -808,15 +1136,10 @@
8081136 @Override
8091137 public String format(Double value) {
8101138 if (value == null)
811- return NULL;
1139+ return "NULL";
8121140 return Double.toString(value);
8131141 }
8141142
815- @Override
816- public ByteBuffer serialize(Double value, ProtocolVersion protocolVersion) {
817- return value == null ? null : serializeNoBoxing(value, protocolVersion);
818- }
819-
8201143 @Override
8211144 public ByteBuffer serializeNoBoxing(double value, ProtocolVersion protocolVersion) {
8221145 ByteBuffer bb = ByteBuffer.allocate(8);
@@ -824,11 +1147,6 @@
8241147 return bb;
8251148 }
8261149
827- @Override
828- public Double deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
829- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
830- }
831-
8321150 @Override
8331151 public double deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
8341152 if (bytes == null || bytes.remaining() == 0)
@@ -843,18 +1161,18 @@
8431161 /**
8441162 * This codec maps a CQL {@link DataType#cfloat()} to a Java {@link Float}.
8451163 */
846- public static class FloatCodec extends TypeCodec<Float> implements PrimitiveFloatCodec {
1164+ private static class FloatCodec extends PrimitiveFloatCodec {
8471165
848- public static final FloatCodec instance = new FloatCodec();
1166+ private static final FloatCodec instance = new FloatCodec();
8491167
8501168 private FloatCodec() {
851- super(cfloat(), Float.class);
1169+ super(DataType.cfloat());
8521170 }
8531171
8541172 @Override
8551173 public Float parse(String value) {
8561174 try {
857- 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);
8581176 } catch (NumberFormatException e) {
8591177 throw new InvalidTypeException(String.format("Cannot parse 32-bits float value from \"%s\"", value));
8601178 }
@@ -863,15 +1181,10 @@
8631181 @Override
8641182 public String format(Float value) {
8651183 if (value == null)
866- return NULL;
1184+ return "NULL";
8671185 return Float.toString(value);
8681186 }
8691187
870- @Override
871- public ByteBuffer serialize(Float value, ProtocolVersion protocolVersion) {
872- return value == null ? null : serializeNoBoxing(value, protocolVersion);
873- }
874-
8751188 @Override
8761189 public ByteBuffer serializeNoBoxing(float value, ProtocolVersion protocolVersion) {
8771190 ByteBuffer bb = ByteBuffer.allocate(4);
@@ -879,11 +1192,6 @@
8791192 return bb;
8801193 }
8811194
882- @Override
883- public Float deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
884- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
885- }
886-
8871195 @Override
8881196 public float deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
8891197 if (bytes == null || bytes.remaining() == 0)
@@ -898,17 +1206,17 @@
8981206 /**
8991207 * This codec maps a CQL {@link DataType#inet()} to a Java {@link InetAddress}.
9001208 */
901- public static class InetCodec extends TypeCodec<InetAddress> {
1209+ private static class InetCodec extends TypeCodec<InetAddress> {
9021210
903- public static final InetCodec instance = new InetCodec();
1211+ private static final InetCodec instance = new InetCodec();
9041212
9051213 private InetCodec() {
906- super(inet(), InetAddress.class);
1214+ super(DataType.inet(), InetAddress.class);
9071215 }
9081216
9091217 @Override
9101218 public InetAddress parse(String value) {
911- if (value == null || value.isEmpty() || value.equals(NULL))
1219+ if (value == null || value.isEmpty() || value.equals("NULL"))
9121220 return null;
9131221
9141222 value = value.trim();
@@ -924,7 +1232,7 @@
9241232 @Override
9251233 public String format(InetAddress value) {
9261234 if (value == null)
927- return NULL;
1235+ return "NULL";
9281236 return "'" + value.getHostAddress() + "'";
9291237 }
9301238
@@ -948,18 +1256,18 @@
9481256 /**
9491257 * This codec maps a CQL {@link DataType#tinyint()} to a Java {@link Byte}.
9501258 */
951- public static class TinyIntCodec extends TypeCodec<Byte> implements PrimitiveByteCodec {
1259+ private static class TinyIntCodec extends PrimitiveByteCodec {
9521260
953- public static final TinyIntCodec instance = new TinyIntCodec();
1261+ private static final TinyIntCodec instance = new TinyIntCodec();
9541262
9551263 private TinyIntCodec() {
956- super(tinyint(), Byte.class);
1264+ super(tinyint());
9571265 }
9581266
9591267 @Override
9601268 public Byte parse(String value) {
9611269 try {
962- 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);
9631271 } catch (NumberFormatException e) {
9641272 throw new InvalidTypeException(String.format("Cannot parse 8-bits int value from \"%s\"", value));
9651273 }
@@ -968,15 +1276,10 @@
9681276 @Override
9691277 public String format(Byte value) {
9701278 if (value == null)
971- return NULL;
1279+ return "NULL";
9721280 return Byte.toString(value);
9731281 }
9741282
975- @Override
976- public ByteBuffer serialize(Byte value, ProtocolVersion protocolVersion) {
977- return value == null ? null : serializeNoBoxing(value, protocolVersion);
978- }
979-
9801283 @Override
9811284 public ByteBuffer serializeNoBoxing(byte value, ProtocolVersion protocolVersion) {
9821285 ByteBuffer bb = ByteBuffer.allocate(1);
@@ -984,11 +1287,6 @@
9841287 return bb;
9851288 }
9861289
987- @Override
988- public Byte deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
989- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
990- }
991-
9921290 @Override
9931291 public byte deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
9941292 if (bytes == null || bytes.remaining() == 0)
@@ -1003,18 +1301,18 @@
10031301 /**
10041302 * This codec maps a CQL {@link DataType#smallint()} to a Java {@link Short}.
10051303 */
1006- public static class SmallIntCodec extends TypeCodec<Short> implements PrimitiveShortCodec {
1304+ private static class SmallIntCodec extends PrimitiveShortCodec {
10071305
1008- public static final SmallIntCodec instance = new SmallIntCodec();
1306+ private static final SmallIntCodec instance = new SmallIntCodec();
10091307
10101308 private SmallIntCodec() {
1011- super(smallint(), Short.class);
1309+ super(smallint());
10121310 }
10131311
10141312 @Override
10151313 public Short parse(String value) {
10161314 try {
1017- 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);
10181316 } catch (NumberFormatException e) {
10191317 throw new InvalidTypeException(String.format("Cannot parse 16-bits int value from \"%s\"", value));
10201318 }
@@ -1023,15 +1321,10 @@
10231321 @Override
10241322 public String format(Short value) {
10251323 if (value == null)
1026- return NULL;
1324+ return "NULL";
10271325 return Short.toString(value);
10281326 }
10291327
1030- @Override
1031- public ByteBuffer serialize(Short value, ProtocolVersion protocolVersion) {
1032- return value == null ? null : serializeNoBoxing(value, protocolVersion);
1033- }
1034-
10351328 @Override
10361329 public ByteBuffer serializeNoBoxing(short value, ProtocolVersion protocolVersion) {
10371330 ByteBuffer bb = ByteBuffer.allocate(2);
@@ -1039,11 +1332,6 @@
10391332 return bb;
10401333 }
10411334
1042- @Override
1043- public Short deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1044- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
1045- }
1046-
10471335 @Override
10481336 public short deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
10491337 if (bytes == null || bytes.remaining() == 0)
@@ -1058,18 +1346,18 @@
10581346 /**
10591347 * This codec maps a CQL {@link DataType#cint()} to a Java {@link Integer}.
10601348 */
1061- public static class IntCodec extends TypeCodec<Integer> implements PrimitiveIntCodec {
1349+ private static class IntCodec extends PrimitiveIntCodec {
10621350
1063- public static final IntCodec instance = new IntCodec();
1351+ private static final IntCodec instance = new IntCodec();
10641352
10651353 private IntCodec() {
1066- super(cint(), Integer.class);
1354+ super(DataType.cint());
10671355 }
10681356
10691357 @Override
10701358 public Integer parse(String value) {
10711359 try {
1072- 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);
10731361 } catch (NumberFormatException e) {
10741362 throw new InvalidTypeException(String.format("Cannot parse 32-bits int value from \"%s\"", value));
10751363 }
@@ -1078,15 +1366,10 @@
10781366 @Override
10791367 public String format(Integer value) {
10801368 if (value == null)
1081- return NULL;
1369+ return "NULL";
10821370 return Integer.toString(value);
10831371 }
10841372
1085- @Override
1086- public ByteBuffer serialize(Integer value, ProtocolVersion protocolVersion) {
1087- return value == null ? null : serializeNoBoxing(value, protocolVersion);
1088- }
1089-
10901373 @Override
10911374 public ByteBuffer serializeNoBoxing(int value, ProtocolVersion protocolVersion) {
10921375 ByteBuffer bb = ByteBuffer.allocate(4);
@@ -1094,11 +1377,6 @@
10941377 return bb;
10951378 }
10961379
1097- @Override
1098- public Integer deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1099- return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes, protocolVersion);
1100- }
1101-
11021380 @Override
11031381 public int deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
11041382 if (bytes == null || bytes.remaining() == 0)
@@ -1113,7 +1391,7 @@
11131391 /**
11141392 * This codec maps a CQL {@link DataType#timestamp()} to a Java {@link Date}.
11151393 */
1116- public static class TimestampCodec extends TypeCodec<Date> {
1394+ private static class TimestampCodec extends TypeCodec<Date> {
11171395
11181396 private static final String[] iso8601Patterns = new String[]{
11191397 "yyyy-MM-dd HH:mm",
@@ -1132,12 +1410,12 @@
11321410 "yyyy-MM-ddZ"
11331411 };
11341412
1135- public static final TimestampCodec instance = new TimestampCodec();
1413+ private static final TimestampCodec instance = new TimestampCodec();
11361414
11371415 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
11381416
11391417 private TimestampCodec() {
1140- super(timestamp(), Date.class);
1418+ super(DataType.timestamp(), Date.class);
11411419 }
11421420
11431421 /*
@@ -1151,14 +1429,12 @@
11511429
11521430 ParsePosition pos = new ParsePosition(0);
11531431 for (String parsePattern : parsePatterns) {
1154- String pattern = parsePattern;
11551432
1156- parser.applyPattern(pattern);
1433+ parser.applyPattern(parsePattern);
11571434 pos.setIndex(0);
11581435
1159- String str2 = str;
1160- Date date = parser.parse(str2, pos);
1161- if (date != null && pos.getIndex() == str2.length()) {
1436+ Date date = parser.parse(str, pos);
1437+ if (date != null && pos.getIndex() == str.length()) {
11621438 return date;
11631439 }
11641440 }
@@ -1167,7 +1443,7 @@
11671443
11681444 @Override
11691445 public Date parse(String value) {
1170- if (value == null || value.isEmpty() || value.equals(NULL))
1446+ if (value == null || value.isEmpty() || value.equals("NULL"))
11711447 return null;
11721448
11731449 // strip enclosing single quotes, if any
@@ -1192,7 +1468,7 @@
11921468 @Override
11931469 public String format(Date value) {
11941470 if (value == null)
1195- return NULL;
1471+ return "NULL";
11961472 return Long.toString(value.getTime());
11971473 }
11981474
@@ -1210,9 +1486,9 @@
12101486 /**
12111487 * This codec maps a CQL {@link DataType#date()} to the custom {@link LocalDate} class.
12121488 */
1213- public static class DateCodec extends TypeCodec<LocalDate> {
1489+ private static class DateCodec extends TypeCodec<LocalDate> {
12141490
1215- public static final DateCodec instance = new DateCodec();
1491+ private static final DateCodec instance = new DateCodec();
12161492
12171493 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
12181494 private static final String pattern = "yyyy-MM-dd";
@@ -1220,12 +1496,12 @@
12201496 private static final long EPOCH_AS_CQL_LONG = (1L << 31);
12211497
12221498 private DateCodec() {
1223- super(date(), LocalDate.class);
1499+ super(DataType.date(), LocalDate.class);
12241500 }
12251501
12261502 @Override
12271503 public LocalDate parse(String value) {
1228- if (value == null || value.isEmpty() || value.equals(NULL))
1504+ if (value == null || value.isEmpty() || value.equals("NULL"))
12291505 return null;
12301506
12311507 // strip enclosing single quotes, if any
@@ -1251,7 +1527,6 @@
12511527 return LocalDate.fromDaysSinceEpoch(days);
12521528 }
12531529
1254-
12551530 SimpleDateFormat parser = new SimpleDateFormat(pattern);
12561531 parser.setLenient(false);
12571532 parser.setTimeZone(TimeZone.getTimeZone("UTC"));
@@ -1268,7 +1543,7 @@
12681543 @Override
12691544 public String format(LocalDate value) {
12701545 if (value == null)
1271- return NULL;
1546+ return "NULL";
12721547 return "'" + value.toString() + "'";
12731548 }
12741549
@@ -1297,14 +1572,14 @@
12971572 /**
12981573 * This codec maps a CQL {@link DataType#time()} to a Java {@link Long}.
12991574 */
1300- public static class TimeCodec extends LongCodec {
1575+ private static class TimeCodec extends LongCodec {
13011576
13021577 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
13031578
1304- public static final TimeCodec instance = new TimeCodec();
1579+ private static final TimeCodec instance = new TimeCodec();
13051580
13061581 private TimeCodec() {
1307- super(time());
1582+ super(DataType.time());
13081583 }
13091584
13101585 // Time specific parsing loosely based on java.sql.Timestamp
@@ -1370,7 +1645,7 @@
13701645
13711646 @Override
13721647 public Long parse(String value) {
1373- if (value == null || value.isEmpty() || value.equals(NULL))
1648+ if (value == null || value.isEmpty() || value.equals("NULL"))
13741649 return null;
13751650
13761651 // enclosing single quotes required, even for long literals
@@ -1396,7 +1671,7 @@
13961671 @Override
13971672 public String format(Long value) {
13981673 if (value == null)
1399- return NULL;
1674+ return "NULL";
14001675 int nano = (int)(value % 1000000000);
14011676 value -= nano;
14021677 value /= 1000000000;
@@ -1409,7 +1684,7 @@
14091684 int hours = (int)(value % 24);
14101685 value -= hours;
14111686 value /= 24;
1412- assert(value == 0);
1687+ assert (value == 0);
14131688 StringBuilder sb = new StringBuilder("'");
14141689 leftPadZeros(hours, 2, sb);
14151690 sb.append(":");
@@ -1431,7 +1706,7 @@
14311706 /**
14321707 * Base class for codecs handling CQL UUID types such as {@link DataType#uuid()} and {@link DataType#timeuuid()}.
14331708 */
1434- public static abstract class AbstractUUIDCodec extends TypeCodec<UUID> {
1709+ private static abstract class AbstractUUIDCodec extends TypeCodec<UUID> {
14351710
14361711 private AbstractUUIDCodec(DataType cqlType) {
14371712 super(cqlType, UUID.class);
@@ -1440,7 +1715,7 @@
14401715 @Override
14411716 public UUID parse(String value) {
14421717 try {
1443- 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);
14441719 } catch (IllegalArgumentException e) {
14451720 throw new InvalidTypeException(String.format("Cannot parse UUID value from \"%s\"", value));
14461721 }
@@ -1449,13 +1724,13 @@
14491724 @Override
14501725 public String format(UUID value) {
14511726 if (value == null)
1452- return NULL;
1727+ return "NULL";
14531728 return value.toString();
14541729 }
14551730
14561731 @Override
14571732 public ByteBuffer serialize(UUID value, ProtocolVersion protocolVersion) {
1458- if(value == null)
1733+ if (value == null)
14591734 return null;
14601735 ByteBuffer bb = ByteBuffer.allocate(16);
14611736 bb.putLong(0, value.getMostSignificantBits());
@@ -1472,12 +1747,12 @@
14721747 /**
14731748 * This codec maps a CQL {@link DataType#uuid()} to a Java {@link UUID}.
14741749 */
1475- public static class UUIDCodec extends AbstractUUIDCodec {
1750+ private static class UUIDCodec extends AbstractUUIDCodec {
14761751
1477- public static final UUIDCodec instance = new UUIDCodec();
1752+ private static final UUIDCodec instance = new UUIDCodec();
14781753
14791754 private UUIDCodec() {
1480- super(uuid());
1755+ super(DataType.uuid());
14811756 }
14821757
14831758 }
@@ -1485,9 +1760,9 @@
14851760 /**
14861761 * This codec maps a CQL {@link DataType#timeuuid()} to a Java {@link UUID}.
14871762 */
1488- public static class TimeUUIDCodec extends AbstractUUIDCodec {
1763+ private static class TimeUUIDCodec extends AbstractUUIDCodec {
14891764
1490- public static final TimeUUIDCodec instance = new TimeUUIDCodec();
1765+ private static final TimeUUIDCodec instance = new TimeUUIDCodec();
14911766
14921767 private TimeUUIDCodec() {
14931768 super(timeuuid());
@@ -1495,17 +1770,14 @@
14951770
14961771 @Override
14971772 public boolean accepts(Object value) {
1498- if (super.accepts(value)) {
1499- // only accept time-based uuids
1500- return ((UUID)value).version() == 1;
1501- }
1502- return false;
1773+ // only accept time-based uuids
1774+ return super.accepts(value) && ((UUID)value).version() == 1;
15031775 }
15041776
15051777 @Override
15061778 public String format(UUID value) {
15071779 if (value == null)
1508- return NULL;
1780+ return "NULL";
15091781 if (value.version() != 1)
15101782 throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", value));
15111783 return super.format(value);
@@ -1513,7 +1785,7 @@
15131785
15141786 @Override
15151787 public ByteBuffer serialize(UUID value, ProtocolVersion protocolVersion) {
1516- if(value == null)
1788+ if (value == null)
15171789 return null;
15181790 if (value.version() != 1)
15191791 throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", value));
@@ -1524,18 +1796,18 @@
15241796 /**
15251797 * This codec maps a CQL {@link DataType#varint()} to a Java {@link BigInteger}.
15261798 */
1527- public static class VarintCodec extends TypeCodec<BigInteger> {
1799+ private static class VarintCodec extends TypeCodec<BigInteger> {
15281800
1529- public static final VarintCodec instance = new VarintCodec();
1801+ private static final VarintCodec instance = new VarintCodec();
15301802
15311803 private VarintCodec() {
1532- super(varint(), BigInteger.class);
1804+ super(DataType.varint(), BigInteger.class);
15331805 }
15341806
15351807 @Override
15361808 public BigInteger parse(String value) {
15371809 try {
1538- 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);
15391811 } catch (NumberFormatException e) {
15401812 throw new InvalidTypeException(String.format("Cannot parse varint value from \"%s\"", value));
15411813 }
@@ -1544,7 +1816,7 @@
15441816 @Override
15451817 public String format(BigInteger value) {
15461818 if (value == null)
1547- return NULL;
1819+ return "NULL";
15481820 return value.toString();
15491821 }
15501822
@@ -1564,18 +1836,18 @@
15641836 * or {@link DataType#set(DataType)}.
15651837 * Note that for practical reasons, {@link MapCodec} does not inherit from this class.
15661838 */
1567- 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> {
15681840
15691841 protected final TypeCodec<E> eltCodec;
15701842
1571- public CollectionCodec(CollectionType cqlType, TypeToken<C> javaType, TypeCodec<E> eltCodec) {
1843+ private CollectionCodec(CollectionType cqlType, TypeToken<C> javaType, TypeCodec<E> eltCodec) {
15721844 super(cqlType, javaType);
15731845 this.eltCodec = eltCodec;
15741846 }
15751847
15761848 @Override
15771849 public ByteBuffer serialize(C value, ProtocolVersion protocolVersion) {
1578- if(value == null)
1850+ if (value == null)
15791851 return null;
15801852 List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(value.size());
15811853 for (E elt : value) {
@@ -1598,7 +1870,7 @@
15981870 @Override
15991871 public C deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
16001872 if (bytes == null || bytes.remaining() == 0)
1601- return unmodifiable(newInstance(0));
1873+ return newInstance(0);
16021874 try {
16031875 ByteBuffer input = bytes.duplicate();
16041876 int n = CodecUtils.readCollectionSize(input, protocolVersion);
@@ -1607,7 +1879,7 @@
16071879 ByteBuffer databb = CodecUtils.readCollectionValue(input, protocolVersion);
16081880 coll.add(eltCodec.deserialize(databb, protocolVersion));
16091881 }
1610- return unmodifiable(coll);
1882+ return coll;
16111883 } catch (BufferUnderflowException e) {
16121884 throw new InvalidTypeException("Not enough bytes to deserialize list");
16131885 }
@@ -1616,7 +1888,7 @@
16161888 @Override
16171889 public String format(C value) {
16181890 if (value == null)
1619- return NULL;
1891+ return "NULL";
16201892 StringBuilder sb = new StringBuilder();
16211893 sb.append(getOpeningChar());
16221894 int i = 0;
@@ -1631,7 +1903,7 @@
16311903
16321904 @Override
16331905 public C parse(String value) {
1634- if (value == null || value.isEmpty() || value.equals(NULL))
1906+ if (value == null || value.isEmpty() || value.equals("NULL"))
16351907 return null;
16361908
16371909 int idx = ParseUtils.skipSpaces(value, 0);
@@ -1681,8 +1953,6 @@
16811953
16821954 protected abstract C newInstance(int capacity);
16831955
1684- protected abstract C unmodifiable(C coll);
1685-
16861956 protected abstract char getOpeningChar();
16871957
16881958 protected abstract char getClosingChar();
@@ -1691,11 +1961,12 @@
16911961
16921962 /**
16931963 * This codec maps a CQL {@link DataType#list(DataType) list type} to a Java {@link List}.
1964+ * 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
@@ -1703,11 +1974,6 @@
17031974 return new ArrayList<T>(capacity);
17041975 }
17051976
1706- @Override
1707- protected List<T> unmodifiable(List<T> coll) {
1708- return Collections.unmodifiableList(coll);
1709- }
1710-
17111977 @Override
17121978 protected char getOpeningChar() {
17131979 return '[';
@@ -1722,11 +1988,12 @@
17221988
17231989 /**
17241990 * This codec maps a CQL {@link DataType#set(DataType) set type} to a Java {@link Set}.
1991+ * Implementation note: this codec returns mutable, non thread-safe {@link LinkedHashSet} instances.
17251992 */
1726- public static class SetCodec<T> extends CollectionCodec<T, Set<T>> {
1993+ private static class SetCodec<T> extends CollectionCodec<T, Set<T>> {
17271994
1728- public SetCodec(TypeCodec<T> eltCodec) {
1729- super(set(eltCodec.cqlType), setOf(eltCodec.getJavaType()), eltCodec);
1995+ private SetCodec(TypeCodec<T> eltCodec) {
1996+ super(DataType.set(eltCodec.cqlType), setOf(eltCodec.getJavaType()), eltCodec);
17301997 }
17311998
17321999 @Override
@@ -1734,11 +2001,6 @@
17342001 return new LinkedHashSet<T>(capacity);
17352002 }
17362003
1737- @Override
1738- protected Set<T> unmodifiable(Set<T> coll) {
1739- return Collections.unmodifiableSet(coll);
1740- }
1741-
17422004 @Override
17432005 protected char getOpeningChar() {
17442006 return '{';
@@ -1752,15 +2014,16 @@
17522014
17532015 /**
17542016 * This codec maps a CQL {@link DataType#map(DataType, DataType) map type} to a Java {@link Map}.
2017+ * Implementation note: this codec returns mutable, non thread-safe {@link LinkedHashMap} instances.
17552018 */
1756- public static class MapCodec<K, V> extends TypeCodec<Map<K, V>> {
2019+ private static class MapCodec<K, V> extends TypeCodec<Map<K, V>> {
17572020
17582021 private final TypeCodec<K> keyCodec;
17592022
17602023 private final TypeCodec<V> valueCodec;
17612024
1762- public MapCodec(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec) {
1763- 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()));
17642027 this.keyCodec = keyCodec;
17652028 this.valueCodec = valueCodec;
17662029 }
@@ -1780,7 +2043,7 @@
17802043
17812044 @Override
17822045 public Map<K, V> parse(String value) {
1783- if (value == null || value.isEmpty() || value.equals(NULL))
2046+ if (value == null || value.isEmpty() || value.equals("NULL"))
17842047 return null;
17852048
17862049 int idx = ParseUtils.skipSpaces(value, 0);
@@ -1790,7 +2053,7 @@
17902053 idx = ParseUtils.skipSpaces(value, idx);
17912054
17922055 if (value.charAt(idx) == '}')
1793- return Collections.emptyMap();
2056+ return new LinkedHashMap<K, V>(0);
17942057
17952058 Map<K, V> m = new HashMap<K, V>();
17962059 while (idx < value.length()) {
@@ -1835,7 +2098,7 @@
18352098 @Override
18362099 public String format(Map<K, V> value) {
18372100 if (value == null)
1838- return NULL;
2101+ return "NULL";
18392102 StringBuilder sb = new StringBuilder();
18402103 sb.append("{");
18412104 int i = 0;
@@ -1885,7 +2148,7 @@
18852148 @Override
18862149 public Map<K, V> deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
18872150 if (bytes == null || bytes.remaining() == 0)
1888- return Collections.emptyMap();
2151+ return new LinkedHashMap<K, V>(0);
18892152 try {
18902153 ByteBuffer input = bytes.duplicate();
18912154 int n = CodecUtils.readCollectionSize(input, protocolVersion);
@@ -1895,7 +2158,7 @@
18952158 ByteBuffer vbb = CodecUtils.readCollectionValue(input, protocolVersion);
18962159 m.put(keyCodec.deserialize(kbb, protocolVersion), valueCodec.deserialize(vbb, protocolVersion));
18972160 }
1898- return Collections.unmodifiableMap(m);
2161+ return m;
18992162 } catch (BufferUnderflowException e) {
19002163 throw new InvalidTypeException("Not enough bytes to deserialize a map");
19012164 }
@@ -1905,26 +2168,23 @@
19052168 /**
19062169 * This codec maps a CQL {@link UserType} to a {@link UDTValue}.
19072170 */
1908- public static class UDTCodec extends TypeCodec<UDTValue> {
2171+ private static class UDTCodec extends TypeCodec<UDTValue> {
19092172
19102173 private final UserType definition;
19112174
1912- public UDTCodec(UserType definition) {
2175+ private UDTCodec(UserType definition) {
19132176 super(definition, UDTValue.class);
19142177 this.definition = definition;
19152178 }
19162179
19172180 @Override
19182181 public boolean accepts(Object value) {
1919- if(value instanceof UDTValue) {
1920- return ((UDTValue) value).getType().equals(definition);
1921- }
1922- return false;
2182+ return value instanceof UDTValue && ((UDTValue)value).getType().equals(definition);
19232183 }
19242184
19252185 @Override
19262186 public UDTValue parse(String value) {
1927- if (value == null || value.isEmpty() || value.equals(NULL))
2187+ if (value == null || value.isEmpty() || value.equals("NULL"))
19282188 return null;
19292189
19302190 UDTValue v = definition.newValue();
@@ -1983,7 +2243,7 @@
19832243 @Override
19842244 public String format(UDTValue value) {
19852245 if (value == null)
1986- return NULL;
2246+ return "NULL";
19872247 return value.toString();
19882248 }
19892249
@@ -2027,11 +2287,11 @@
20272287 /**
20282288 * This codec maps a CQL {@link TupleType} to a {@link TupleValue}.
20292289 */
2030- public static class TupleCodec extends TypeCodec<TupleValue> {
2290+ private static class TupleCodec extends TypeCodec<TupleValue> {
20312291
20322292 private final TupleType definition;
20332293
2034- public TupleCodec(TupleType definition) {
2294+ private TupleCodec(TupleType definition) {
20352295 super(definition, TupleValue.class);
20362296 this.definition = definition;
20372297 }
@@ -2047,12 +2307,12 @@
20472307 public boolean accepts(Object value) {
20482308 // a tuple codec should accept tuple values of a different type,
20492309 // provided that the latter is contained in this codec's type.
2050- return value instanceof TupleValue && definition.contains(((TupleValue) value).getType());
2310+ return value instanceof TupleValue && definition.contains(((TupleValue)value).getType());
20512311 }
20522312
20532313 @Override
20542314 public TupleValue parse(String value) {
2055- if (value == null || value.isEmpty() || value.equals(NULL))
2315+ if (value == null || value.isEmpty() || value.equals("NULL"))
20562316 return null;
20572317
20582318 TupleValue v = definition.newValue();
@@ -2096,7 +2356,7 @@
20962356 @Override
20972357 public String format(TupleValue value) {
20982358 if (value == null)
2099- return NULL;
2359+ return "NULL";
21002360 return value.toString();
21012361 }
21022362
@@ -2137,211 +2397,4 @@
21372397 }
21382398 }
21392399
2140- /**
2141- * An abstract TypeCodec that actually stores objects as serialized strings.
2142- * This can serve as a base for codecs dealing with XML or JSON formats.
2143- *
2144- * @param <T> The Java type this codec serializes from and deserializes to.
2145- */
2146- public abstract static class StringParsingCodec<T> extends TypeCodec<T> {
2147-
2148- private final TypeCodec<String> innerCodec;
2149-
2150- public StringParsingCodec(Class<T> javaType) {
2151- this(TypeToken.of(javaType));
2152- }
2153-
2154- public StringParsingCodec(TypeToken<T> javaType) {
2155- this(VarcharCodec.instance, javaType);
2156- }
2157-
2158- public StringParsingCodec(TypeCodec<String> innerCodec, Class<T> javaType) {
2159- this(innerCodec, TypeToken.of(javaType));
2160- }
2161-
2162- public StringParsingCodec(TypeCodec<String> innerCodec, TypeToken<T> javaType) {
2163- super(innerCodec.getCqlType(), javaType);
2164- this.innerCodec = innerCodec;
2165- }
2166-
2167- @Override
2168- public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
2169- return value == null ? null : innerCodec.serialize(toString(value), protocolVersion);
2170- }
2171-
2172- @Override
2173- public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
2174- String value = innerCodec.deserialize(bytes, protocolVersion);
2175- return value == null ? null : fromString(value);
2176- }
2177-
2178- @Override
2179- public String format(T value) throws InvalidTypeException {
2180- return value == null ? null : innerCodec.format(toString(value));
2181- }
2182-
2183- @Override
2184- public T parse(String value) throws InvalidTypeException {
2185- return value == null || value.isEmpty() || value.equals(NULL) ? null : fromString(innerCodec.parse(value));
2186- }
2187-
2188- /**
2189- * Return the String representation of the given object;
2190- * no special CQL quoting should be applied here.
2191- * Null values should be accepted; in most cases, implementors
2192- * should return null for null inputs.
2193- *
2194- * @param value the value to convert into a string
2195- * @return the String representation of the given object
2196- */
2197- protected abstract String toString(T value);
2198-
2199- /**
2200- * Parse the given string into an object;
2201- * no special CQL unquoting should be applied here.
2202- * Null values should be accepted; in most cases, implementors
2203- * should return null for null inputs.
2204- *
2205- * @param value the string to parse
2206- * @return the parsed object.
2207- */
2208- protected abstract T fromString(String value);
2209-
2210- }
2211-
2212- /**
2213- * An abstract TypeCodec that maps a Java Pojo to another Java object
2214- * that can in turn be serialized into a CQL type.
2215- * This can serve as a base for libraries dealing with Pojo mappings.
2216- *
2217- * @param <T> The outer Java type
2218- * @param <U> The inner Java type
2219- */
2220- public abstract static class MappingCodec<T, U> extends TypeCodec<T> {
2221-
2222- protected final TypeCodec<U> innerCodec;
2223-
2224- public MappingCodec(TypeCodec<U> innerCodec, Class<T> javaType) {
2225- this(innerCodec, TypeToken.of(javaType));
2226- }
2227-
2228- public MappingCodec(TypeCodec<U> innerCodec, TypeToken<T> javaType) {
2229- super(innerCodec.getCqlType(), javaType);
2230- this.innerCodec = innerCodec;
2231- }
2232-
2233- @Override
2234- public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
2235- return innerCodec.serialize(serialize(value), protocolVersion);
2236- }
2237-
2238- @Override
2239- public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
2240- return deserialize(innerCodec.deserialize(bytes, protocolVersion));
2241- }
2242-
2243- @Override
2244- public T parse(String value) throws InvalidTypeException {
2245- return value == null || value.isEmpty() || value.equals(NULL) ? null : deserialize(innerCodec.parse(value));
2246- }
2247-
2248- @Override
2249- public String format(T value) throws InvalidTypeException {
2250- return value == null ? null : innerCodec.format(serialize(value));
2251- }
2252-
2253- protected abstract T deserialize(U value);
2254-
2255- protected abstract U serialize(T value);
2256-
2257- }
2258-
2259- /**
2260- * A codec that serializes {@link Enum} instances as CQL {@link DataType#varchar() varchar}s
2261- * representing their programmatic names as returned by {@link Enum#name()}.
2262- * <p>
2263- * This codec is automatically used by the driver to create codecs for {@link Enum}
2264- * instances on the fly.
2265- *
2266- * @param <E> The Enum class this codec serializes from and deserializes to.
2267- */
2268- public static class EnumStringCodec<E extends Enum<E>> extends StringParsingCodec<E> {
2269-
2270- private final Class<E> enumClass;
2271-
2272- public EnumStringCodec(Class<E> enumClass) {
2273- super(enumClass);
2274- this.enumClass = enumClass;
2275- }
2276-
2277- public EnumStringCodec(TypeCodec<String> innerCodec, Class<E> enumClass) {
2278- super(innerCodec, enumClass);
2279- this.enumClass = enumClass;
2280- }
2281-
2282- @Override
2283- protected String toString(E value) {
2284- return value == null ? null : value.name();
2285- }
2286-
2287- @Override
2288- protected E fromString(String value) {
2289- return value == null ? null : Enum.valueOf(enumClass, value);
2290- }
2291-
2292- }
2293-
2294- /**
2295- * A codec that serializes {@link Enum} instances as CQL {@link DataType#cint() int}s
2296- * representing their ordinal values as returned by {@link Enum#ordinal()}.
2297- * <p>
2298- * Note that, by default, the driver uses {@link EnumStringCodec} to serialize {@link Enum} instances;
2299- * to force the use of this codec instead for a specific {@link Enum} instance,
2300- * the appropriate {@link EnumIntCodec} instance must be explicitly
2301- * {@link CodecRegistry#register(TypeCodec) registered}.
2302- * <p>
2303- * <strong>Note that this codec relies on the enum constants declaration order;
2304- * it is therefore vital that this order remains immutable.</strong>
2305- *
2306- * @param <E> The Enum class this codec serializes from and deserializes to.
2307- */
2308- public static class EnumIntCodec<E extends Enum<E>> extends TypeCodec<E> {
2309-
2310- private final E[] enumConstants;
2311-
2312- private final TypeCodec<Integer> innerCodec;
2313-
2314- public EnumIntCodec(Class<E> enumClass) {
2315- this(IntCodec.instance, enumClass);
2316- }
2317-
2318- public EnumIntCodec(TypeCodec<Integer> innerCodec, Class<E> enumClass) {
2319- super(innerCodec.getCqlType(), enumClass);
2320- this.enumConstants = enumClass.getEnumConstants();
2321- this.innerCodec = innerCodec;
2322- }
2323-
2324- @Override
2325- public ByteBuffer serialize(E value, ProtocolVersion protocolVersion) throws InvalidTypeException {
2326- return innerCodec.serialize(value.ordinal(), protocolVersion);
2327- }
2328-
2329- @Override
2330- public E deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
2331- return enumConstants[innerCodec.deserialize(bytes, protocolVersion)];
2332- }
2333-
2334- @Override
2335- public E parse(String value) throws InvalidTypeException {
2336- return value == null || value.isEmpty() || value.equals(NULL) ? null : enumConstants[Integer.parseInt(value)];
2337- }
2338-
2339- @Override
2340- public String format(E value) throws InvalidTypeException {
2341- if (value == null)
2342- return NULL;
2343- return Integer.toString(value.ordinal());
2344- }
2345- }
2346-
23472400 }
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);
modified driver-core/src/test/java/com/datastax/driver/core/BoundStatementTest.java +3 −3
@@ -25,7 +25,7 @@
2525 import static org.assertj.core.api.Assertions.assertThat;
2626 import static org.assertj.core.api.Assertions.fail;
2727
28-import com.datastax.driver.core.exceptions.InvalidTypeException;
28+import com.datastax.driver.core.exceptions.CodecNotFoundException;
2929
3030 public class BoundStatementTest extends CCMBridge.PerClassSingleNodeCluster {
3131
@@ -60,8 +60,8 @@
6060
6161 try {
6262 statement.getString(0);
63- fail("Expected type error");
64- } catch (InvalidTypeException e) { /* expected */ }
63+ fail("Expected codec not found error");
64+ } catch (CodecNotFoundException e) { /* expected */ }
6565
6666 try {
6767 statement.getString(3);
added driver-core/src/test/java/com/datastax/driver/core/CodecRegistryTest.java +92 −0
@@ -0,0 +1,92 @@
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.util.List;
19+
20+import com.google.common.reflect.TypeToken;
21+import org.apache.log4j.Level;
22+import org.apache.log4j.Logger;
23+import org.testng.annotations.Test;
24+
25+import static org.mockito.Mockito.mock;
26+import static org.mockito.Mockito.when;
27+
28+import static com.datastax.driver.core.Assertions.assertThat;
29+
30+public class CodecRegistryTest {
31+ TypeToken<List<Integer>> LIST_OF_INT_TOKEN = new TypeToken<List<Integer>>() {
32+ };
33+
34+ @Test(groups = "unit")
35+ public void should_ignore_codec_colliding_with_already_registered_codec() {
36+ MemoryAppender logs = startCapturingLogs();
37+
38+ CodecRegistry registry = new CodecRegistry();
39+
40+ TypeCodec newCodec = mock(TypeCodec.class);
41+ when(newCodec.getCqlType()).thenReturn(DataType.cint());
42+ when(newCodec.getJavaType()).thenReturn(TypeToken.of(Integer.class));
43+ when(newCodec.toString()).thenReturn("newCodec");
44+
45+ registry.register(newCodec);
46+
47+ assertThat(logs.getNext()).contains("Ignoring codec newCodec");
48+ assertThat(
49+ registry.codecFor(DataType.cint(), Integer.class)
50+ ).isNotSameAs(newCodec);
51+
52+ stopCapturingLogs(logs);
53+ }
54+
55+ @Test(groups = "unit")
56+ public void should_ignore_codec_colliding_with_already_generated_codec() {
57+ MemoryAppender logs = startCapturingLogs();
58+
59+ CodecRegistry registry = new CodecRegistry();
60+
61+ // Force generation of a list token from the default token
62+ registry.codecFor(DataType.list(DataType.cint()), LIST_OF_INT_TOKEN);
63+
64+ TypeCodec newCodec = mock(TypeCodec.class);
65+ when(newCodec.getCqlType()).thenReturn(DataType.list(DataType.cint()));
66+ when(newCodec.getJavaType()).thenReturn(LIST_OF_INT_TOKEN);
67+ when(newCodec.toString()).thenReturn("newCodec");
68+
69+ registry.register(newCodec);
70+
71+ assertThat(logs.getNext()).contains("Ignoring codec newCodec");
72+ assertThat(
73+ registry.codecFor(DataType.list(DataType.cint()), LIST_OF_INT_TOKEN)
74+ ).isNotSameAs(newCodec);
75+
76+ stopCapturingLogs(logs);
77+ }
78+
79+ private MemoryAppender startCapturingLogs() {
80+ Logger registryLogger = Logger.getLogger(CodecRegistry.class);
81+ registryLogger.setLevel(Level.WARN);
82+ MemoryAppender logs = new MemoryAppender();
83+ registryLogger.addAppender(logs);
84+ return logs;
85+ }
86+
87+ private void stopCapturingLogs(MemoryAppender logs) {
88+ Logger registryLogger = Logger.getLogger(CodecRegistry.class);
89+ registryLogger.setLevel(null);
90+ registryLogger.removeAppender(logs);
91+ }
92+}
No newline at the end of the file
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+}
added driver-core/src/test/java/com/datastax/driver/core/GettableDataIntegrationTest.java +497 −0
@@ -0,0 +1,497 @@
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.math.BigDecimal;
19+import java.math.BigInteger;
20+import java.net.InetAddress;
21+import java.net.UnknownHostException;
22+import java.nio.ByteBuffer;
23+import java.util.Collection;
24+import java.util.Date;
25+import java.util.List;
26+import java.util.Map;
27+import java.util.Set;
28+import java.util.UUID;
29+import java.util.concurrent.atomic.AtomicInteger;
30+
31+import com.google.common.collect.ImmutableMap;
32+import com.google.common.collect.ImmutableSet;
33+import com.google.common.reflect.TypeToken;
34+import org.testng.annotations.BeforeClass;
35+import org.testng.annotations.Test;
36+
37+import static com.google.common.collect.Lists.newArrayList;
38+import static org.assertj.core.api.Assertions.assertThat;
39+
40+import static com.datastax.driver.core.CodecUtils.listOf;
41+import static com.datastax.driver.core.TestUtils.getValue;
42+import static com.datastax.driver.core.TestUtils.setValue;
43+
44+public class GettableDataIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
45+
46+ boolean is21 = cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) > 0;
47+ boolean is20 = cassandraVersion.compareTo(VersionNumber.parse("2.0")) > 0;
48+
49+ CodecRegistry registry = new CodecRegistry();
50+
51+ // Used for generating unique keys.
52+ AtomicInteger keyCounter = new AtomicInteger(0);
53+
54+ @Override
55+ protected Collection<String> getTableDefinitions() {
56+ // only add tuples / nested collections at > 2.1.3.
57+ return newArrayList("CREATE TABLE codec_mapping (k int PRIMARY KEY, "
58+ + "v int, l list<int>, m map<int,int>" +
59+ (is21 ? ", t tuple<int,int>, s set<frozen<list<int>>>)" : ")"));
60+ }
61+
62+ @Override
63+ protected Cluster.Builder configure(Cluster.Builder builder) {
64+ return super.configure(builder).withCodecRegistry(registry);
65+ }
66+
67+ @BeforeClass(groups = "short")
68+ public void setUpRegistry() {
69+ for(TypeMapping<?> mapping : mappings) {
70+ registry.register(mapping.codec);
71+ }
72+ }
73+
74+ static final ByteBuffer intBuf = ByteBuffer.allocate(4);
75+ static {
76+ intBuf.putInt(1);
77+ intBuf.flip();
78+ }
79+
80+ static InetAddress localhost;
81+ static {
82+ try {
83+ localhost = InetAddress.getLocalHost();
84+ } catch(UnknownHostException e) {
85+ localhost = null;
86+ }
87+ }
88+
89+ // Mappings of Codecs, Data Type to access as (used for determining what get|set method to call), value to set.
90+ private TypeMapping<?>[] mappings = {
91+ // set|getString
92+ new TypeMapping<String>(new IntToStringCodec(), DataType.varchar(), "1"),
93+ // set|getLong
94+ new TypeMapping<Long>(new IntToLongCodec(), DataType.bigint(), 1L),
95+ // set|getBytes
96+ new TypeMapping<ByteBuffer>(new IntToByteBufferCodec(), DataType.blob(), intBuf),
97+ // set|getBool
98+ new TypeMapping<Boolean>(new IntToBooleanCodec(), DataType.cboolean(), true),
99+ // set|getDecimal
100+ new TypeMapping<BigDecimal>(new IntToBigDecimalCodec(), DataType.decimal(), new BigDecimal(1)),
101+ // set|getDouble
102+ new TypeMapping<Double>(new IntToDoubleCodec(), DataType.cdouble(), 1.0d),
103+ // set|getFloat
104+ new TypeMapping<Float>(new IntToFloatCodec(), DataType.cfloat(), 1.0f),
105+ // set|getInet
106+ new TypeMapping<InetAddress>(new IntToInetAddressCodec(), DataType.inet(), localhost),
107+ // set|getTime
108+ new TypeMapping<Long>(new IntToLongCodec(), DataType.time(), 8675309L),
109+ // set|getByte
110+ new TypeMapping<Byte>(new IntToByteCodec(), DataType.tinyint(), (byte)0xCF),
111+ // set|getShort
112+ new TypeMapping<Short>(new IntToShortCodec(), DataType.smallint(), (short)1003),
113+ // set|getTimestamp
114+ new TypeMapping<Date>(new IntToDateCodec(), DataType.timestamp(), new Date(124677)),
115+ // set|getDate
116+ new TypeMapping<LocalDate>(new IntToLocalDateCodec(), DataType.date(), LocalDate.fromDaysSinceEpoch(1523)),
117+ // set|getUUID
118+ new TypeMapping<UUID>(new IntToUUIDCodec(), DataType.uuid(), new UUID(244242, 0)),
119+ // set|getVarint
120+ new TypeMapping<BigInteger>(new IntToBigIntegerCodec(), DataType.varint(), BigInteger.valueOf(4566432L))
121+ };
122+
123+ /**
124+ * Validates that all {@link GettableData} types will allow their get methods to be invoked on a column that does
125+ * not match data's cql type if a codec is registered that maps the java type of the getter method to the cql type
126+ * of the column.
127+ * <p/>
128+ * Also validates that all {@link SettableData} types will allow their set methods to be invoked on a column that
129+ * does not match data's cql type if a codec is registered that maps the java type of the setter method to the cql
130+ * type of the column.
131+ * <p/>
132+ * Executes the following for each set|get set:
133+ *
134+ * <ol>
135+ * <li>Insert row using a prepared statement and binding by name.</li>
136+ * <li>Insert row using a prepared statement and binding by index.</li>
137+ * <li>Insert row using a prepared statement and binding everything at once.</li>
138+ * <li>Retrieve inserted rows and get values by name.</li>
139+ * <li>Retrieve inserted rows and get values by index.</li>
140+ * </ol>
141+ *
142+ * @jira_ticket JAVA-940
143+ * @test_category queries
144+ */
145+ @Test(groups = "short")
146+ public void should_allow_getting_and_setting_by_type_if_codec_registered() {
147+ String insertStmt = "INSERT INTO codec_mapping (k,v,l,m" + (is21 ? ",t,s" : "") + ") values (?,?,?,?" + (is21 ? ",?,?)" : ")");
148+ PreparedStatement insert = session.prepare(insertStmt);
149+ PreparedStatement select = session.prepare("SELECT v,l,m" + (is21 ? ",t,s" : "") + " from codec_mapping where k=?");
150+
151+ TupleType tupleType = new TupleType(newArrayList(DataType.cint(), DataType.cint()),
152+ cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), registry);
153+
154+ for(TypeMapping<?> mapping : mappings) {
155+ // Keys used to insert data in this iteration.
156+ List<Integer> keys = newArrayList();
157+
158+ // Values to store.
159+ Map<Object,Object> map = ImmutableMap.of(mapping.value, mapping.value);
160+ List<Object> list = newArrayList(mapping.value);
161+ Set<List<Object>> set = ImmutableSet.of(list);
162+ TupleValue tupleValue = new TupleValue(tupleType);
163+ setValue(tupleValue, 0, mapping.outerType, mapping.value);
164+ setValue(tupleValue, 1, mapping.outerType, mapping.value);
165+
166+ // Insert by name.
167+ BoundStatement byName = insert.bind();
168+ int byNameKey = keyCounter.incrementAndGet();
169+ keys.add(byNameKey);
170+ byName.setInt("k", byNameKey);
171+ setValue(byName, "v", mapping.outerType, mapping.value);
172+ byName.setList("l", list, mapping.javaType);
173+ byName.setMap("m", map, mapping.javaType, mapping.javaType);
174+ if(is21) {
175+ byName.setTupleValue("t", tupleValue);
176+ byName.setSet("s", set, listOf(mapping.javaType));
177+ }
178+ session.execute(byName);
179+
180+ // Insert by index.
181+ BoundStatement byIndex = insert.bind();
182+ int byIndexKey = keyCounter.incrementAndGet();
183+ keys.add(byIndexKey);
184+ byIndex.setInt(0, byIndexKey);
185+ setValue(byIndex, 1, mapping.outerType, mapping.value);
186+ byIndex.setList(2, list, mapping.javaType);
187+ byIndex.setMap(3, map, mapping.javaType, mapping.javaType);
188+ if(is21) {
189+ byIndex.setTupleValue(4, tupleValue);
190+ byIndex.setSet(5, set, listOf(mapping.javaType));
191+ }
192+ session.execute(byIndex);
193+
194+ // Insert by binding all at once.
195+ BoundStatement fullBind;
196+ int fullBindKey = keyCounter.incrementAndGet();
197+ keys.add(fullBindKey);
198+ if(is21) {
199+ fullBind = insert.bind(fullBindKey, mapping.value, list, map, tupleValue, set);
200+ } else {
201+ fullBind = insert.bind(fullBindKey, mapping.value, list, map);
202+ }
203+ session.execute(fullBind);
204+
205+ for(int key : keys) {
206+ // Retrieve by name.
207+ Row row = session.execute(select.bind(key)).one();
208+ assertThat(getValue(row, "v", mapping.outerType, registry)).isEqualTo(mapping.value);
209+ assertThat(row.getList("l", mapping.codec.getJavaType())).isEqualTo(list);
210+ assertThat(row.getMap("m", mapping.codec.getJavaType(), mapping.codec.getJavaType())).isEqualTo(map);
211+
212+ if(is21) {
213+ TupleValue returnedTuple = row.getTupleValue("t");
214+ assertThat(getValue(returnedTuple, 0, mapping.outerType, registry)).isEqualTo(mapping.value);
215+ assertThat(getValue(returnedTuple, 1, mapping.outerType, registry)).isEqualTo(mapping.value);
216+
217+ assertThat(row.getSet("s", listOf(mapping.javaType))).isEqualTo(set);
218+ }
219+
220+ // Retrieve by index.
221+ assertThat(getValue(row, 0, mapping.outerType, registry)).isEqualTo(mapping.value);
222+ assertThat(row.getList(1, mapping.codec.getJavaType())).isEqualTo(list);
223+ assertThat(row.getMap(2, mapping.codec.getJavaType(), mapping.codec.getJavaType())).isEqualTo(map);
224+
225+ if(is21) {
226+ TupleValue returnedTuple = row.getTupleValue(3);
227+ assertThat(getValue(returnedTuple, 0, mapping.outerType, registry)).isEqualTo(mapping.value);
228+ assertThat(getValue(returnedTuple, 1, mapping.outerType, registry)).isEqualTo(mapping.value);
229+
230+ assertThat(row.getSet(4, listOf(mapping.javaType))).isEqualTo(set);
231+ }
232+ }
233+ }
234+ }
235+
236+ private static class TypeMapping<T> {
237+ final TypeCodec<T> codec;
238+ final TypeToken<Object> javaType;
239+ final DataType outerType;
240+ final T value;
241+
242+ @SuppressWarnings("unchecked")
243+ TypeMapping(TypeCodec<T> codec, DataType outerType, T value) {
244+ this.codec = codec;
245+ this.javaType = (TypeToken<Object>)codec.getJavaType();
246+ this.outerType = outerType;
247+ this.value = value;
248+ }
249+ }
250+
251+ // Int <-> Type mappings.
252+ private static class IntToLongCodec extends MappingCodec<Long, Integer> {
253+
254+ IntToLongCodec() {
255+ super(TypeCodec.cint(), Long.class);
256+ }
257+
258+ @Override
259+ protected Long deserialize(Integer value) {
260+ return value.longValue();
261+ }
262+
263+ @Override
264+ protected Integer serialize(Long value) {
265+ return value.intValue();
266+ }
267+ }
268+
269+ private static class IntToStringCodec extends MappingCodec<String, Integer> {
270+
271+ IntToStringCodec() {
272+ super(TypeCodec.cint(), String.class);
273+ }
274+
275+ @Override
276+ protected String deserialize(Integer value) {
277+ return value.toString();
278+ }
279+
280+ @Override
281+ protected Integer serialize(String value) {
282+ return Integer.parseInt(value);
283+ }
284+ }
285+
286+ private static class IntToByteBufferCodec extends MappingCodec<ByteBuffer, Integer> {
287+
288+ IntToByteBufferCodec() {
289+ super(TypeCodec.cint(), ByteBuffer.class);
290+ }
291+
292+ @Override
293+ protected ByteBuffer deserialize(Integer value) {
294+ ByteBuffer buf = ByteBuffer.allocate(4);
295+ buf.putInt(value);
296+ buf.flip();
297+ return buf;
298+ }
299+
300+ @Override
301+ protected Integer serialize(ByteBuffer value) {
302+ return value.duplicate().getInt();
303+ }
304+ }
305+
306+ private static class IntToBooleanCodec extends MappingCodec<Boolean, Integer> {
307+
308+ IntToBooleanCodec() {
309+ super(TypeCodec.cint(), Boolean.class);
310+ }
311+
312+ @Override
313+ protected Boolean deserialize(Integer value) {
314+ return value != 0;
315+ }
316+
317+ @Override
318+ protected Integer serialize(Boolean value) {
319+ return value ? 1 : 0;
320+ }
321+ }
322+
323+ private static class IntToBigDecimalCodec extends MappingCodec<BigDecimal, Integer> {
324+
325+ IntToBigDecimalCodec() {
326+ super(TypeCodec.cint(), BigDecimal.class);
327+ }
328+
329+ @Override
330+ protected BigDecimal deserialize(Integer value) {
331+ return new BigDecimal(value);
332+ }
333+
334+ @Override
335+ protected Integer serialize(BigDecimal value) {
336+ return value.intValue();
337+ }
338+ }
339+
340+ private static class IntToDoubleCodec extends MappingCodec<Double, Integer> {
341+
342+ IntToDoubleCodec() {
343+ super(TypeCodec.cint(), Double.class);
344+ }
345+
346+ @Override
347+ protected Double deserialize(Integer value) {
348+ return value.doubleValue();
349+ }
350+
351+ @Override
352+ protected Integer serialize(Double value) {
353+ return value.intValue();
354+ }
355+ }
356+
357+ private static class IntToFloatCodec extends MappingCodec<Float, Integer> {
358+
359+ IntToFloatCodec() {
360+ super(TypeCodec.cint(), Float.class);
361+ }
362+
363+ @Override
364+ protected Float deserialize(Integer value) {
365+ return value.floatValue();
366+ }
367+
368+ @Override
369+ protected Integer serialize(Float value) {
370+ return value.intValue();
371+ }
372+ }
373+
374+ private static class IntToInetAddressCodec extends MappingCodec<InetAddress, Integer> {
375+
376+ IntToInetAddressCodec() {
377+ super(TypeCodec.cint(), InetAddress.class);
378+ }
379+
380+ @Override
381+ protected InetAddress deserialize(Integer value) {
382+ byte[] address = ByteBuffer.allocate(4).putInt(value).array();
383+ try {
384+ return InetAddress.getByAddress(address);
385+ } catch(UnknownHostException e) {
386+ return null;
387+ }
388+ }
389+
390+ @Override
391+ protected Integer serialize(InetAddress value) {
392+ return ByteBuffer.wrap(value.getAddress()).getInt();
393+ }
394+ }
395+
396+ private static class IntToByteCodec extends MappingCodec<Byte, Integer> {
397+
398+ IntToByteCodec() {
399+ super(TypeCodec.cint(), Byte.class);
400+ }
401+
402+ @Override
403+ protected Byte deserialize(Integer value) {
404+ return value.byteValue();
405+ }
406+
407+ @Override
408+ protected Integer serialize(Byte value) {
409+ return value.intValue();
410+ }
411+ }
412+
413+ private static class IntToShortCodec extends MappingCodec<Short, Integer> {
414+
415+ IntToShortCodec() {
416+ super(TypeCodec.cint(), Short.class);
417+ }
418+
419+ @Override
420+ protected Short deserialize(Integer value) {
421+ return value.shortValue();
422+ }
423+
424+ @Override
425+ protected Integer serialize(Short value) {
426+ return value.intValue();
427+ }
428+ }
429+
430+ private static class IntToDateCodec extends MappingCodec<Date, Integer> {
431+
432+ IntToDateCodec() {
433+ super(TypeCodec.cint(), Date.class);
434+ }
435+
436+ @Override
437+ protected Date deserialize(Integer value) {
438+ return new Date(value);
439+ }
440+
441+ @Override
442+ protected Integer serialize(Date value) {
443+ return new Long(value.getTime()).intValue();
444+ }
445+ }
446+
447+ private static class IntToLocalDateCodec extends MappingCodec<LocalDate, Integer> {
448+
449+ IntToLocalDateCodec() {
450+ super(TypeCodec.cint(), LocalDate.class);
451+ }
452+
453+ @Override
454+ protected LocalDate deserialize(Integer value) {
455+ return LocalDate.fromDaysSinceEpoch(value);
456+ }
457+
458+ @Override
459+ protected Integer serialize(LocalDate value) {
460+ return value.getDaysSinceEpoch();
461+ }
462+ }
463+
464+ private static class IntToUUIDCodec extends MappingCodec<UUID, Integer> {
465+
466+ IntToUUIDCodec() {
467+ super(TypeCodec.cint(), UUID.class);
468+ }
469+
470+ @Override
471+ protected UUID deserialize(Integer value) {
472+ return new UUID(value, 0);
473+ }
474+
475+ @Override
476+ protected Integer serialize(UUID value) {
477+ return new Long(value.getMostSignificantBits()).intValue();
478+ }
479+ }
480+
481+ private static class IntToBigIntegerCodec extends MappingCodec<BigInteger, Integer> {
482+
483+ IntToBigIntegerCodec() {
484+ super(TypeCodec.cint(), BigInteger.class);
485+ }
486+
487+ @Override
488+ protected BigInteger deserialize(Integer value) {
489+ return BigInteger.valueOf((long)value);
490+ }
491+
492+ @Override
493+ protected Integer serialize(BigInteger value) {
494+ return value.intValue();
495+ }
496+ }
497+}
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 +8 −11
@@ -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
@@ -167,7 +164,7 @@
167164 tupleType = (TupleType)innerCodec.getCqlType();
168165 List<DataType> types = tupleType.getComponentTypes();
169166 checkArgument(
170- types.size() == 2 && types.get(0).equals(timestamp()) && types.get(1).equals(varchar()),
167+ types.size() == 2 && types.get(0).equals(DataType.timestamp()) && types.get(1).equals(DataType.varchar()),
171168 "Expected tuple<timestamp,varchar>, got %s",
172169 tupleType);
173170 }
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/PreparedStatementTest.java +17 −9
@@ -34,7 +34,7 @@
3434 import static com.datastax.driver.core.TestUtils.getFixedValue;
3535 import static com.datastax.driver.core.TestUtils.getFixedValue2;
3636 import static com.datastax.driver.core.TestUtils.getValue;
37-import static com.datastax.driver.core.TestUtils.setBoundValue;
37+import static com.datastax.driver.core.TestUtils.setValue;
3838
3939 /**
4040 * Prepared statement tests.
@@ -131,7 +131,8 @@
131131 String name = "c_" + type;
132132 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_native', ?)", ALL_NATIVE_TABLE, name));
133133 BoundStatement bs = ps.bind();
134- session.execute(setBoundValue(bs, name, type, getFixedValue(type)));
134+ setValue(bs, name, type, getFixedValue(type));
135+ session.execute(bs);
135136
136137 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
137138 assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), getFixedValue(type), "For type " + type);
@@ -152,7 +153,8 @@
152153 String name = "c_" + type;
153154 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_native', ?)", ALL_NATIVE_TABLE, name));
154155 BoundStatement bs = ps.bind();
155- session.execute(setBoundValue(bs, name, type, getFixedValue2(type)));
156+ setValue(bs, name, type, getFixedValue2(type));
157+ session.execute(bs);
156158
157159 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_native'", name, ALL_NATIVE_TABLE)).one();
158160 assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), getFixedValue2(type), "For type " + type);
@@ -173,7 +175,8 @@
173175 List<Object> value = (List<Object>)getFixedValue(type);
174176 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
175177 BoundStatement bs = ps.bind();
176- session.execute(setBoundValue(bs, name, type, value));
178+ setValue(bs, name, type, value);
179+ session.execute(bs);
177180
178181 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
179182 assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
@@ -197,7 +200,8 @@
197200 List<Object> value = (List<Object>)getFixedValue2(type);
198201 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
199202 BoundStatement bs = ps.bind();
200- session.execute(setBoundValue(bs, name, type, value));
203+ setValue(bs, name, type, value);
204+ session.execute(bs);
201205
202206 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_list'", name, ALL_LIST_TABLE)).one();
203207 assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
@@ -218,7 +222,8 @@
218222 Set<Object> value = (Set<Object>)getFixedValue(type);
219223 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
220224 BoundStatement bs = ps.bind();
221- session.execute(setBoundValue(bs, name, type, value));
225+ setValue(bs, name, type, value);
226+ session.execute(bs);
222227
223228 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
224229 assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
@@ -242,7 +247,8 @@
242247 Set<Object> value = (Set<Object>)getFixedValue2(type);
243248 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
244249 BoundStatement bs = ps.bind();
245- session.execute(setBoundValue(bs, name, type, value));
250+ setValue(bs, name, type, value);
251+ session.execute(bs);
246252
247253 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_set'", name, ALL_SET_TABLE)).one();
248254 assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
@@ -268,7 +274,8 @@
268274 Map<Object, Object> value = (Map<Object, Object>)getFixedValue(type);
269275 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
270276 BoundStatement bs = ps.bind();
271- session.execute(setBoundValue(bs, name, type, value));
277+ setValue(bs, name, type, value);
278+ session.execute(bs);
272279
273280 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
274281 assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
@@ -298,7 +305,8 @@
298305 Map<Object, Object> value = (Map<Object, Object>)getFixedValue2(type);
299306 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
300307 BoundStatement bs = ps.bind();
301- session.execute(setBoundValue(bs, name, type, value));
308+ setValue(bs, name, type, value);
309+ session.execute(bs);
302310
303311 Row row = session.execute(String.format("SELECT %s FROM %s WHERE k='prepared_map'", name, ALL_MAP_TABLE)).one();
304312 assertEquals(getValue(row, name, type, cluster.getConfiguration().getCodecRegistry()), value, "For type " + type);
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/TestUtils.java +179 −48
@@ -51,136 +51,267 @@
5151
5252 public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60);
5353
54+ public static void setValue(SettableByIndexData<?> data, int i, DataType type, Object value) {
55+ switch (type.getName()) {
56+ case ASCII:
57+ data.setString(i, (String)value);
58+ break;
59+ case BIGINT:
60+ data.setLong(i, (Long)value);
61+ break;
62+ case BLOB:
63+ data.setBytes(i, (ByteBuffer)value);
64+ break;
65+ case BOOLEAN:
66+ data.setBool(i, (Boolean)value);
67+ break;
68+ case COUNTER:
69+ // Just a no-op, we shouldn't handle counters the same way than other types
70+ break;
71+ case DECIMAL:
72+ data.setDecimal(i, (BigDecimal)value);
73+ break;
74+ case DOUBLE:
75+ data.setDouble(i, (Double)value);
76+ break;
77+ case FLOAT:
78+ data.setFloat(i, (Float)value);
79+ break;
80+ case INET:
81+ data.setInet(i, (InetAddress)value);
82+ break;
83+ case TINYINT:
84+ data.setByte(i, (Byte) value);
85+ break;
86+ case SMALLINT:
87+ data.setShort(i, (Short) value);
88+ break;
89+ case INT:
90+ data.setInt(i, (Integer) value);
91+ break;
92+ case TEXT:
93+ data.setString(i, (String) value);
94+ break;
95+ case TIMESTAMP:
96+ data.setTimestamp(i, (Date) value);
97+ break;
98+ case DATE:
99+ data.setDate(i, (LocalDate)value);
100+ break;
101+ case TIME:
102+ data.setTime(i, (Long) value);
103+ break;
104+ case UUID:
105+ data.setUUID(i, (UUID)value);
106+ break;
107+ case VARCHAR:
108+ data.setString(i, (String)value);
109+ break;
110+ case VARINT:
111+ data.setVarint(i, (BigInteger)value);
112+ break;
113+ case TIMEUUID:
114+ data.setUUID(i, (UUID)value);
115+ break;
116+ case LIST:
117+ data.setList(i, (List)value);
118+ break;
119+ case SET:
120+ data.setSet(i, (Set)value);
121+ break;
122+ case MAP:
123+ data.setMap(i, (Map)value);
124+ break;
125+ default:
126+ throw new RuntimeException("Missing handling of " + type);
127+ }
128+ }
129+
54130 @SuppressWarnings({ "unchecked", "rawtypes" })
55- public static BoundStatement setBoundValue(BoundStatement bs, String name, DataType type, Object value) {
131+ public static void setValue(SettableByNameData<?> data, String name, DataType type, Object value) {
56132 switch (type.getName()) {
57133 case ASCII:
58- bs.setString(name, (String)value);
134+ data.setString(name, (String)value);
59135 break;
60136 case BIGINT:
61- bs.setLong(name, (Long)value);
137+ data.setLong(name, (Long)value);
62138 break;
63139 case BLOB:
64- bs.setBytes(name, (ByteBuffer)value);
140+ data.setBytes(name, (ByteBuffer)value);
65141 break;
66142 case BOOLEAN:
67- bs.setBool(name, (Boolean)value);
143+ data.setBool(name, (Boolean)value);
68144 break;
69145 case COUNTER:
70146 // Just a no-op, we shouldn't handle counters the same way than other types
71147 break;
72148 case DECIMAL:
73- bs.setDecimal(name, (BigDecimal)value);
149+ data.setDecimal(name, (BigDecimal)value);
74150 break;
75151 case DOUBLE:
76- bs.setDouble(name, (Double)value);
152+ data.setDouble(name, (Double)value);
77153 break;
78154 case FLOAT:
79- bs.setFloat(name, (Float)value);
155+ data.setFloat(name, (Float)value);
80156 break;
81157 case INET:
82- bs.setInet(name, (InetAddress)value);
158+ data.setInet(name, (InetAddress)value);
83159 break;
84160 case TINYINT:
85- bs.setByte(name, (Byte) value);
161+ data.setByte(name, (Byte) value);
86162 break;
87163 case SMALLINT:
88- bs.setShort(name, (Short) value);
164+ data.setShort(name, (Short) value);
89165 break;
90166 case INT:
91- bs.setInt(name, (Integer) value);
167+ data.setInt(name, (Integer) value);
92168 break;
93169 case TEXT:
94- bs.setString(name, (String) value);
170+ data.setString(name, (String) value);
95171 break;
96172 case TIMESTAMP:
97- bs.setTimestamp(name, (Date) value);
173+ data.setTimestamp(name, (Date) value);
98174 break;
99175 case DATE:
100- bs.setDate(name, (LocalDate)value);
176+ data.setDate(name, (LocalDate)value);
101177 break;
102178 case TIME:
103- bs.setTime(name, (Long) value);
179+ data.setTime(name, (Long) value);
104180 break;
105181 case UUID:
106- bs.setUUID(name, (UUID)value);
182+ data.setUUID(name, (UUID)value);
107183 break;
108184 case VARCHAR:
109- bs.setString(name, (String)value);
185+ data.setString(name, (String)value);
110186 break;
111187 case VARINT:
112- bs.setVarint(name, (BigInteger)value);
188+ data.setVarint(name, (BigInteger)value);
113189 break;
114190 case TIMEUUID:
115- bs.setUUID(name, (UUID)value);
191+ data.setUUID(name, (UUID)value);
116192 break;
117193 case LIST:
118- bs.setList(name, (List)value);
194+ data.setList(name, (List)value);
119195 break;
120196 case SET:
121- bs.setSet(name, (Set)value);
197+ data.setSet(name, (Set)value);
122198 break;
123199 case MAP:
124- bs.setMap(name, (Map)value);
200+ data.setMap(name, (Map)value);
125201 break;
126202 default:
127203 throw new RuntimeException("Missing handling of " + type);
128204 }
129- return bs;
130205 }
131206
132- public static Object getValue(Row row, String name, DataType type, CodecRegistry codecRegistry) {
207+ public static Object getValue(GettableByIndexData data, int i, DataType type, CodecRegistry codecRegistry) {
208+ switch (type.getName()) {
209+ case ASCII:
210+ return data.getString(i);
211+ case BIGINT:
212+ return data.getLong(i);
213+ case BLOB:
214+ return data.getBytes(i);
215+ case BOOLEAN:
216+ return data.getBool(i);
217+ case COUNTER:
218+ return data.getLong(i);
219+ case DECIMAL:
220+ return data.getDecimal(i);
221+ case DOUBLE:
222+ return data.getDouble(i);
223+ case FLOAT:
224+ return data.getFloat(i);
225+ case INET:
226+ return data.getInet(i);
227+ case TINYINT:
228+ return data.getByte(i);
229+ case SMALLINT:
230+ return data.getShort(i);
231+ case INT:
232+ return data.getInt(i);
233+ case TEXT:
234+ return data.getString(i);
235+ case TIMESTAMP:
236+ return data.getTimestamp(i);
237+ case DATE:
238+ return data.getDate(i);
239+ case TIME:
240+ return data.getTime(i);
241+ case UUID:
242+ return data.getUUID(i);
243+ case VARCHAR:
244+ return data.getString(i);
245+ case VARINT:
246+ return data.getVarint(i);
247+ case TIMEUUID:
248+ return data.getUUID(i);
249+ case LIST:
250+ Class<?> listEltClass = codecRegistry.codecFor(type.getTypeArguments().get(0)).getJavaType().getRawType();
251+ return data.getList(i, listEltClass);
252+ case SET:
253+ Class<?> setEltClass = codecRegistry.codecFor(type.getTypeArguments().get(0)).getJavaType().getRawType();
254+ return data.getSet(i, setEltClass);
255+ case MAP:
256+ Class<?> keyClass = codecRegistry.codecFor(type.getTypeArguments().get(0)).getJavaType().getRawType();
257+ Class<?> valueClass = codecRegistry.codecFor(type.getTypeArguments().get(1)).getJavaType().getRawType();
258+ return data.getMap(i, keyClass, valueClass);
259+ }
260+ throw new RuntimeException("Missing handling of " + type);
261+ }
262+
263+ public static Object getValue(GettableByNameData data, String name, DataType type, CodecRegistry codecRegistry) {
133264 switch (type.getName()) {
134265 case ASCII:
135- return row.getString(name);
266+ return data.getString(name);
136267 case BIGINT:
137- return row.getLong(name);
268+ return data.getLong(name);
138269 case BLOB:
139- return row.getBytes(name);
270+ return data.getBytes(name);
140271 case BOOLEAN:
141- return row.getBool(name);
272+ return data.getBool(name);
142273 case COUNTER:
143- return row.getLong(name);
274+ return data.getLong(name);
144275 case DECIMAL:
145- return row.getDecimal(name);
276+ return data.getDecimal(name);
146277 case DOUBLE:
147- return row.getDouble(name);
278+ return data.getDouble(name);
148279 case FLOAT:
149- return row.getFloat(name);
280+ return data.getFloat(name);
150281 case INET:
151- return row.getInet(name);
282+ return data.getInet(name);
152283 case TINYINT:
153- return row.getByte(name);
284+ return data.getByte(name);
154285 case SMALLINT:
155- return row.getShort(name);
286+ return data.getShort(name);
156287 case INT:
157- return row.getInt(name);
288+ return data.getInt(name);
158289 case TEXT:
159- return row.getString(name);
290+ return data.getString(name);
160291 case TIMESTAMP:
161- return row.getTimestamp(name);
292+ return data.getTimestamp(name);
162293 case DATE:
163- return row.getDate(name);
294+ return data.getDate(name);
164295 case TIME:
165- return row.getTime(name);
296+ return data.getTime(name);
166297 case UUID:
167- return row.getUUID(name);
298+ return data.getUUID(name);
168299 case VARCHAR:
169- return row.getString(name);
300+ return data.getString(name);
170301 case VARINT:
171- return row.getVarint(name);
302+ return data.getVarint(name);
172303 case TIMEUUID:
173- return row.getUUID(name);
304+ return data.getUUID(name);
174305 case LIST:
175306 Class<?> listEltClass = codecRegistry.codecFor(type.getTypeArguments().get(0)).getJavaType().getRawType();
176- return row.getList(name, listEltClass);
307+ return data.getList(name, listEltClass);
177308 case SET:
178309 Class<?> setEltClass = codecRegistry.codecFor(type.getTypeArguments().get(0)).getJavaType().getRawType();
179- return row.getSet(name, setEltClass);
310+ return data.getSet(name, setEltClass);
180311 case MAP:
181312 Class<?> keyClass = codecRegistry.codecFor(type.getTypeArguments().get(0)).getJavaType().getRawType();
182313 Class<?> valueClass = codecRegistry.codecFor(type.getTypeArguments().get(1)).getJavaType().getRawType();
183- return row.getMap(name, keyClass, valueClass);
314+ return data.getMap(name, keyClass, valueClass);
184315 }
185316 throw new RuntimeException("Missing handling of " + type);
186317 }
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 +1 −10
@@ -123,7 +123,7 @@
123123 session.execute(session.prepare(insertQuery).bind()
124124 .setString(0, notAJsonString)
125125 .set(1, alice, User.class)
126- .setList(2, bobAndCharlie)
126+ .setList(2, bobAndCharlie, User.class)
127127 );
128128 PreparedStatement ps = session.prepare(selectQuery);
129129 ResultSet rows = session.execute(ps.bind()
@@ -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"), String.class)
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 +6 −11
@@ -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
@@ -159,11 +154,11 @@
159154
160155 @Override
161156 protected UDTValue serialize(Address value) {
162- return value == null ? null : userType.newValue().setString("street", value.street).setInt("zipcode", value.zipcode).setList("phones", value.phones);
157+ return value == null ? null : userType.newValue().setString("street", value.street).setInt("zipcode", value.zipcode).setList("phones", value.phones, Phone.class);
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 +91 −37
@@ -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);
255293 }
256294
257295 @Override
258- protected Address deserialize(UDTValue value) {
259- return value == null ? null : new Address(value.getString("street"), value.getInt("zipcode"));
296+ public Address deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
297+ return toAddress(innerCodec.deserialize(bytes, protocolVersion));
260298 }
261299
262300 @Override
263- protected UDTValue serialize(Address address) {
264- return address == null ? null : userType.newValue().setString("street", address.getStreet()).setInt("zipcode", address.getZipcode());
301+ public Address parse(String value) throws InvalidTypeException {
302+ return value == null || value.isEmpty() || value.equals(NULL) ? null : toAddress(innerCodec.parse(value));
303+ }
304+
305+ @Override
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
@@ -385,14 +440,13 @@
385440
386441 The following situations are exceptions where it is not possible to cache lookup results:
387442
388-* With [SimpleStatement] instances and [BuiltStatement] instances (created via the Query Builder); in these places, the driver has
389- no way to determine the right CQL type to use, so it performs a best-effort heuristic to guess which codec to use.
390-* When using "ambiguous" methods of `BoundStatement` and `Row`, such as [setList()][setList],
391- [setSet()][setSet], [setMap()][setMap], [setObject()][setObject];
392- these methods are "ambiguous" because they do not convey enough compile-time information about the object
393- to serialize, so the driver performs the same heuristic to guess which codec to use.
394-
395-Beware that in these cases the lookup performs in average 10x worse. If performance is a key factor for your application,
443+* With [SimpleStatement] instances;
444+* With [BuiltStatement] instances (created via the Query Builder).
445+
446+In these places, the driver has no way to determine the right CQL type to use, so it performs
447+a best-effort heuristic to guess which codec to use.
448+
449+Beware that in these cases, the lookup performs in average 10x worse. If performance is a key factor for your application,
396450 consider using prepared statements all the time, and avoid calling ambiguous methods (prefer `get()` and `set()`).
397451
398452 [JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721
modified upgrade_guide/README.md +3 −0
@@ -61,6 +61,9 @@
6161 * `TupleType of(DataType... types)`; users should now use `Metadata.newTupleType(DataType...)`.
6262
6363 <p>The driver runtime behavior changes in the following situations:</p>
64+ * By default, the driver now returns _mutable_, _non thread-safe_ instances for CQL collection types;
65+ This affects methods `getList`, `getSet`, `getMap`, `getObject` and `get` for all instances of
66+ `GettableByIndexData` and `GettableByNameData` (`Row`, `BoundStatement`, `TupleValue` and `UDTValue`)
6467 * `RuntimeException`s thrown during serialization or deserialization might not be
6568 the same ones as before, due to the newly-introduced `CodecNotFoundException`
6669 and to the dynamic nature of codec search introduced by JAVA-721.