Elffuss BraidHub

kikocis/java-driver public

Merge pull request #265 from datastax/java570

Support C* 2.1.3 nested collections (JAVA-570)
Changeset686577c52c0ad82299a976c51b362cdfc49bc924bff614b954efd9a4db8fdb5e
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-03-06 17:24 -08:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-03-06 17:24 -08:00
Parents5cc80eb128f8, 1e0f61b0202a

Browse the files at this changeset

47 files changed

modified driver-core/CHANGELOG.rst +4 −0
@@ -4,7 +4,11 @@
44 2.1.5:
55 ------
66
7+- [bug] Fix checks on mapped collection types (JAVA-612)
78 - [bug] Authorize Null parameter in Accessor method (JAVA-575)
9+- [improvement] Support C* 2.1.3's nested collections (JAVA-570)
10+- [bug] Fix checks on mapped collection types (JAVA-612)
11+- [bug] Fix QueryBuilder.putAll() when the collection contains UDTs (JAVA-672)
812
913 Merged from 2.0 branch:
1014
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java +69 −3
@@ -26,6 +26,8 @@
2626 import java.util.Set;
2727 import java.util.UUID;
2828
29+import com.google.common.reflect.TypeToken;
30+
2931 import com.datastax.driver.core.exceptions.InvalidTypeException;
3032
3133 abstract class AbstractGettableByIndexData implements GettableByIndexData {
@@ -290,7 +292,28 @@
290292
291293 Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
292294 if (!elementsClass.isAssignableFrom(expectedClass))
293- throw new InvalidTypeException(String.format("Column %s is a list of %s (CQL type %s), cannot be retrieve as a list of %s", getName(i), expectedClass, type, elementsClass));
295+ throw new InvalidTypeException(String.format("Column %s is a list of %s (CQL type %s), cannot be retrieved as a list of %s", getName(i), expectedClass, type, elementsClass));
296+
297+ ByteBuffer value = getValue(i);
298+ if (value == null)
299+ return Collections.<T>emptyList();
300+
301+ return Collections.unmodifiableList((List<T>)type.codec(protocolVersion).deserialize(value));
302+ }
303+
304+ /**
305+ * {@inheritDoc}
306+ */
307+ @Override
308+ @SuppressWarnings("unchecked")
309+ public <T> List<T> getList(int i, TypeToken<T> elementsType) {
310+ DataType type = getType(i);
311+ if (type.getName() != DataType.Name.LIST)
312+ throw new InvalidTypeException(String.format("Column %s is not of list type", getName(i)));
313+
314+ DataType expectedType = type.getTypeArguments().get(0);
315+ if (!expectedType.canBeDeserializedAs(elementsType))
316+ throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a list of %s", getName(i), type, elementsType));
294317
295318 ByteBuffer value = getValue(i);
296319 if (value == null)
@@ -311,7 +334,28 @@
311334
312335 Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
313336 if (!elementsClass.isAssignableFrom(expectedClass))
314- throw new InvalidTypeException(String.format("Column %s is a set of %s (CQL type %s), cannot be retrieve as a set of %s", getName(i), expectedClass, type, elementsClass));
337+ throw new InvalidTypeException(String.format("Column %s is a set of %s (CQL type %s), cannot be retrieved as a set of %s", getName(i), expectedClass, type, elementsClass));
338+
339+ ByteBuffer value = getValue(i);
340+ if (value == null)
341+ return Collections.<T>emptySet();
342+
343+ return Collections.unmodifiableSet((Set<T>)type.codec(protocolVersion).deserialize(value));
344+ }
345+
346+ /**
347+ * {@inheritDoc}
348+ */
349+ @Override
350+ @SuppressWarnings("unchecked")
351+ public <T> Set<T> getSet(int i, TypeToken<T> elementsType) {
352+ DataType type = getType(i);
353+ if (type.getName() != DataType.Name.SET)
354+ throw new InvalidTypeException(String.format("Column %s is not of set type", getName(i)));
355+
356+ DataType expectedType = type.getTypeArguments().get(0);
357+ if (!expectedType.canBeDeserializedAs(elementsType))
358+ throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a set of %s", getName(i), type, elementsType));
315359
316360 ByteBuffer value = getValue(i);
317361 if (value == null)
@@ -333,7 +377,29 @@
333377 Class<?> expectedKeysClass = type.getTypeArguments().get(0).getName().javaType;
334378 Class<?> expectedValuesClass = type.getTypeArguments().get(1).getName().javaType;
335379 if (!keysClass.isAssignableFrom(expectedKeysClass) || !valuesClass.isAssignableFrom(expectedValuesClass))
336- throw new InvalidTypeException(String.format("Column %s is a map of %s->%s (CQL type %s), cannot be retrieve as a map of %s->%s", getName(i), expectedKeysClass, expectedValuesClass, type, keysClass, valuesClass));
380+ throw new InvalidTypeException(String.format("Column %s is a map of %s->%s (CQL type %s), cannot be retrieved as a map of %s->%s", getName(i), expectedKeysClass, expectedValuesClass, type, keysClass, valuesClass));
381+
382+ ByteBuffer value = getValue(i);
383+ if (value == null)
384+ return Collections.<K, V>emptyMap();
385+
386+ return Collections.unmodifiableMap((Map<K, V>)type.codec(protocolVersion).deserialize(value));
387+ }
388+
389+ /**
390+ * {@inheritDoc}
391+ */
392+ @Override
393+ @SuppressWarnings("unchecked")
394+ public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) {
395+ DataType type = getType(i);
396+ if (type.getName() != DataType.Name.MAP)
397+ throw new InvalidTypeException(String.format("Column %s is not of map type", getName(i)));
398+
399+ DataType expectedKeysType = type.getTypeArguments().get(0);
400+ DataType expectedValuesType = type.getTypeArguments().get(1);
401+ if (!expectedKeysType.canBeDeserializedAs(keysType) || !expectedValuesType.canBeDeserializedAs(valuesType))
402+ throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a map of %s->%s", getName(i), type, keysType, valuesType));
337403
338404 ByteBuffer value = getValue(i);
339405 if (value == null)
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java +26 −0
@@ -21,6 +21,8 @@
2121 import java.nio.ByteBuffer;
2222 import java.util.*;
2323
24+import com.google.common.reflect.TypeToken;
25+
2426 public abstract class AbstractGettableData extends AbstractGettableByIndexData implements GettableData {
2527
2628 /**
@@ -177,6 +179,14 @@
177179 return getList(getIndexOf(name), elementsClass);
178180 }
179181
182+ /**
183+ * {@inheritDoc}
184+ */
185+ @Override
186+ public <T> List<T> getList(String name, TypeToken<T> elementsType) {
187+ return getList(getIndexOf(name), elementsType);
188+ }
189+
180190 /**
181191 * {@inheritDoc}
182192 */
@@ -185,6 +195,14 @@
185195 return getSet(getIndexOf(name), elementsClass);
186196 }
187197
198+ /**
199+ * {@inheritDoc}
200+ */
201+ @Override
202+ public <T> Set<T> getSet(String name, TypeToken<T> elementsType) {
203+ return getSet(getIndexOf(name), elementsType);
204+ }
205+
188206 /**
189207 * {@inheritDoc}
190208 */
@@ -193,6 +211,14 @@
193211 return getMap(getIndexOf(name), keysClass, valuesClass);
194212 }
195213
214+ /**
215+ * {@inheritDoc}
216+ */
217+ @Override
218+ public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType) {
219+ return getMap(getIndexOf(name), keysType, valuesType);
220+ }
221+
196222 /**
197223 * {@inheritDoc}
198224 */
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +44 −0
@@ -21,6 +21,8 @@
2121 import java.nio.ByteBuffer;
2222 import java.util.*;
2323
24+import com.google.common.reflect.TypeToken;
25+
2426 import com.datastax.driver.core.exceptions.InvalidTypeException;
2527
2628 /**
@@ -1238,6 +1240,13 @@
12381240 return wrapper.getList(i, elementsClass);
12391241 }
12401242
1243+ /**
1244+ * {@inheritDoc}
1245+ */
1246+ public <T> List<T> getList(int i, TypeToken<T> elementsType) {
1247+ return wrapper.getList(i, elementsType);
1248+ }
1249+
12411250 /**
12421251 * {@inheritDoc}
12431252 */
@@ -1245,6 +1254,13 @@
12451254 return wrapper.getList(name, elementsClass);
12461255 }
12471256
1257+ /**
1258+ * {@inheritDoc}
1259+ */
1260+ public <T> List<T> getList(String name, TypeToken<T> elementsType) {
1261+ return wrapper.getList(name, elementsType);
1262+ }
1263+
12481264 /**
12491265 * {@inheritDoc}
12501266 */
@@ -1252,6 +1268,13 @@
12521268 return wrapper.getSet(i, elementsClass);
12531269 }
12541270
1271+ /**
1272+ * {@inheritDoc}
1273+ */
1274+ public <T> Set<T> getSet(int i, TypeToken<T> elementsType) {
1275+ return wrapper.getSet(i, elementsType);
1276+ }
1277+
12551278 /**
12561279 * {@inheritDoc}
12571280 */
@@ -1259,6 +1282,13 @@
12591282 return wrapper.getSet(name, elementsClass);
12601283 }
12611284
1285+ /**
1286+ * {@inheritDoc}
1287+ */
1288+ public <T> Set<T> getSet(String name, TypeToken<T> elementsType) {
1289+ return wrapper.getSet(name, elementsType);
1290+ }
1291+
12621292 /**
12631293 * {@inheritDoc}
12641294 */
@@ -1266,6 +1296,13 @@
12661296 return wrapper.getMap(i, keysClass, valuesClass);
12671297 }
12681298
1299+ /**
1300+ * {@inheritDoc}
1301+ */
1302+ public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) {
1303+ return wrapper.getMap(i, keysType, valuesType);
1304+ }
1305+
12691306 /**
12701307 * {@inheritDoc}
12711308 */
@@ -1273,6 +1310,13 @@
12731310 return wrapper.getMap(name, keysClass, valuesClass);
12741311 }
12751312
1313+ /**
1314+ * {@inheritDoc}
1315+ */
1316+ public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType) {
1317+ return wrapper.getMap(name, keysType, valuesType);
1318+ }
1319+
12761320 /**
12771321 * {@inheritDoc}
12781322 */
modified driver-core/src/main/java/com/datastax/driver/core/CassandraTypeParser.java +30 −9
@@ -18,6 +18,8 @@
1818 import java.util.*;
1919
2020 import com.google.common.collect.ImmutableMap;
21+import org.slf4j.Logger;
22+import org.slf4j.LoggerFactory;
2123
2224 import com.datastax.driver.core.exceptions.DriverInternalError;
2325 import com.datastax.driver.core.utils.Bytes;
@@ -35,8 +37,10 @@
3537 * so there shouldn't be anything wrong with them.
3638 */
3739 class CassandraTypeParser {
40+ private static final Logger logger = LoggerFactory.getLogger(CassandraTypeParser.class);
3841
3942 private static final String REVERSED_TYPE = "org.apache.cassandra.db.marshal.ReversedType";
43+ private static final String FROZEN_TYPE = "org.apache.cassandra.db.marshal.FrozenType";
4044 private static final String COMPOSITE_TYPE = "org.apache.cassandra.db.marshal.CompositeType";
4145 private static final String COLLECTION_TYPE = "org.apache.cassandra.db.marshal.ColumnToCollectionType";
4246 private static final String LIST_TYPE = "org.apache.cassandra.db.marshal.ListType";
@@ -66,30 +70,33 @@
6670 .build();
6771
6872 static DataType parseOne(String className) {
73+ boolean frozen = false;
6974 if (isReversed(className)) {
7075 // Just skip the ReversedType part, we don't care
71- Parser p = new Parser(className, 0);
72- p.parseNextName();
73- List<String> l = p.getTypeParameters();
74- if (l.size() != 1)
75- throw new IllegalStateException();
76- className = l.get(0);
76+ className = getNestedClassName(className);
77+ } else if (isFrozen(className)) {
78+ frozen = true;
79+ className = getNestedClassName(className);
7780 }
7881
7982 Parser parser = new Parser(className, 0);
8083 String next = parser.parseNextName();
8184
8285 if (next.startsWith(LIST_TYPE))
83- return DataType.list(parseOne(parser.getTypeParameters().get(0)));
86+ return DataType.list(parseOne(parser.getTypeParameters().get(0)), frozen);
8487
8588 if (next.startsWith(SET_TYPE))
86- return DataType.set(parseOne(parser.getTypeParameters().get(0)));
89+ return DataType.set(parseOne(parser.getTypeParameters().get(0)), frozen);
8790
8891 if (next.startsWith(MAP_TYPE)) {
8992 List<String> params = parser.getTypeParameters();
90- return DataType.map(parseOne(params.get(0)), parseOne(params.get(1)));
93+ return DataType.map(parseOne(params.get(0)), parseOne(params.get(1)), frozen);
9194 }
9295
96+ if (frozen)
97+ logger.warn("Got o.a.c.db.marshal.FrozenType for something else than a collection, "
98+ + "this driver version might be too old for your version of Cassandra");
99+
93100 if (isUserType(next)) {
94101 ++parser.idx; // skipping '('
95102
@@ -121,6 +128,20 @@
121128 return className.startsWith(REVERSED_TYPE);
122129 }
123130
131+ public static boolean isFrozen(String className) {
132+ return className.startsWith(FROZEN_TYPE);
133+ }
134+
135+ private static String getNestedClassName(String className) {
136+ Parser p = new Parser(className, 0);
137+ p.parseNextName();
138+ List<String> l = p.getTypeParameters();
139+ if (l.size() != 1)
140+ throw new IllegalStateException();
141+ className = l.get(0);
142+ return className;
143+ }
144+
124145 public static boolean isUserType(String className) {
125146 return className.startsWith(UDT_TYPE);
126147 }
modified driver-core/src/main/java/com/datastax/driver/core/DataType.java +148 −32
@@ -24,6 +24,7 @@
2424 import com.google.common.base.Objects;
2525 import com.google.common.collect.ImmutableList;
2626 import com.google.common.collect.ImmutableSet;
27+import com.google.common.reflect.TypeToken;
2728 import org.jboss.netty.buffer.ChannelBuffer;
2829
2930 import com.datastax.driver.core.exceptions.DriverInternalError;
@@ -165,26 +166,6 @@
165166 this.name = name;
166167 }
167168
168-
169- /**
170- * Returns whether this data type is frozen.
171- * <p>
172- * This applies to User Defined Types, tuples and nested collections. Frozen types are serialized as a single value in
173- * Cassandra's storage engine, whereas non-frozen types are stored in a form that allows updates to individual subfields.
174- *
175- * @return whether this data type is frozen.
176- */
177- public boolean isFrozen() {
178- // With Cassandra 2.1.0, this is straightforward; in future versions, "frozenness" will be stored in the database.
179- switch (name) {
180- case UDT:
181- case TUPLE:
182- return true;
183- default:
184- return false;
185- }
186- }
187-
188169 static DataType decode(ChannelBuffer buffer) {
189170 Name name = Name.fromProtocolId(buffer.readUnsignedShort());
190171 switch (name) {
@@ -374,23 +355,70 @@
374355 * Returns the type of lists of {@code elementType} elements.
375356 *
376357 * @param elementType the type of the list elements.
358+ * @param frozen whether the list is frozen.
377359 * @return the type of lists of {@code elementType} elements.
378360 */
361+ public static DataType list(DataType elementType, boolean frozen) {
362+ return new DataType.Collection(Name.LIST, ImmutableList.of(elementType), frozen);
363+ }
364+
365+ /**
366+ * Returns the type of lists of "not frozen" {@code elementType} elements.
367+ * <p>
368+ * This is a shorthand for {@code list(elementType, false);}.
369+ *
370+ * @param elementType the type of the list elements.
371+ * @return the type of lists of "not frozen" {@code elementType} elements.
372+ */
379373 public static DataType list(DataType elementType) {
380- // TODO: for list, sets and maps, we could cache them (may or may not be worth it, but since we
381- // don't allow nesting of collections, even pregenerating all the lists/sets like we do for
382- // primitives wouldn't be very costly)
383- return new DataType.Collection(Name.LIST, ImmutableList.of(elementType));
374+ return list(elementType, false);
375+ }
376+
377+ /**
378+ * Returns the type of lists of frozen {@code elementType} elements.
379+ * <p>
380+ * This is a shorthand for {@code list(elementType, true);}.
381+ *
382+ * @param elementType the type of the list elements.
383+ * @return the type of lists of frozen {@code elementType} elements.
384+ */
385+ public static DataType frozenList(DataType elementType) {
386+ return list(elementType, true);
384387 }
385388
386389 /**
387390 * Returns the type of sets of {@code elementType} elements.
388391 *
389392 * @param elementType the type of the set elements.
393+ * @param frozen whether the set is frozen.
390394 * @return the type of sets of {@code elementType} elements.
391395 */
396+ public static DataType set(DataType elementType, boolean frozen) {
397+ return new DataType.Collection(Name.SET, ImmutableList.of(elementType), frozen);
398+ }
399+
400+ /**
401+ * Returns the type of "not frozen" sets of {@code elementType} elements.
402+ * <p>
403+ * This is a shorthand for {@code set(elementType, false);}.
404+ *
405+ * @param elementType the type of the set elements.
406+ * @return the type of sets of "not frozen" {@code elementType} elements.
407+ */
392408 public static DataType set(DataType elementType) {
393- return new DataType.Collection(Name.SET, ImmutableList.of(elementType));
409+ return set(elementType, false);
410+ }
411+
412+ /**
413+ * Returns the type of frozen sets of {@code elementType} elements.
414+ * <p>
415+ * This is a shorthand for {@code set(elementType, true);}.
416+ *
417+ * @param elementType the type of the set elements.
418+ * @return the type of frozen sets of {@code elementType} elements.
419+ */
420+ public static DataType frozenSet(DataType elementType) {
421+ return set(elementType, true);
394422 }
395423
396424 /**
@@ -398,10 +426,37 @@
398426 *
399427 * @param keyType the type of the map keys.
400428 * @param valueType the type of the map values.
401- * @return the type of map of {@code keyType} to {@code valueType} elements.
429+ * @param frozen whether the map is frozen.
430+ * @return the type of maps of {@code keyType} to {@code valueType} elements.
431+ */
432+ public static DataType map(DataType keyType, DataType valueType, boolean frozen) {
433+ return new DataType.Collection(Name.MAP, ImmutableList.of(keyType, valueType), frozen);
434+ }
435+
436+ /**
437+ * Returns the type of "not frozen" maps of {@code keyType} to {@code valueType} elements.
438+ * <p>
439+ * This is a shorthand for {@code map(keyType, valueType, false);}.
440+ *
441+ * @param keyType the type of the map keys.
442+ * @param valueType the type of the map values.
443+ * @return the type of "not frozen" maps of {@code keyType} to {@code valueType} elements.
402444 */
403445 public static DataType map(DataType keyType, DataType valueType) {
404- return new DataType.Collection(Name.MAP, ImmutableList.of(keyType, valueType));
446+ return map(keyType, valueType, false);
447+ }
448+
449+ /**
450+ * Returns the type of frozen maps of {@code keyType} to {@code valueType} elements.
451+ * <p>
452+ * This is a shorthand for {@code map(keyType, valueType, true);}.
453+ *
454+ * @param keyType the type of the map keys.
455+ * @param valueType the type of the map values.
456+ * @return the type of frozen maps of {@code keyType} to {@code valueType} elements.
457+ */
458+ public static DataType frozenMap(DataType keyType, DataType valueType) {
459+ return map(keyType, valueType, true);
405460 }
406461
407462 /**
@@ -433,6 +488,16 @@
433488 return name;
434489 }
435490
491+ /**
492+ * Returns whether this data type is frozen.
493+ * <p>
494+ * This applies to User Defined Types, tuples and nested collections. Frozen types are serialized as a single value in
495+ * Cassandra's storage engine, whereas non-frozen types are stored in a form that allows updates to individual subfields.
496+ *
497+ * @return whether this data type is frozen.
498+ */
499+ public abstract boolean isFrozen();
500+
436501 /**
437502 * Returns the type arguments of this type.
438503 * <p>
@@ -454,6 +519,8 @@
454519 return Collections.<DataType>emptyList();
455520 }
456521
522+ abstract boolean canBeDeserializedAs(TypeToken typeToken);
523+
457524 /**
458525 * Returns the server-side class name for a custom type.
459526 *
@@ -693,6 +760,16 @@
693760 super(name);
694761 }
695762
763+ @Override
764+ public boolean isFrozen() {
765+ return false;
766+ }
767+
768+ @Override
769+ boolean canBeDeserializedAs(TypeToken typeToken) {
770+ return typeToken.isAssignableFrom(getName().javaType);
771+ }
772+
696773 @Override
697774 TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
698775 return TypeCodec.createFor(name);
@@ -725,10 +802,35 @@
725802 private static class Collection extends DataType {
726803
727804 private final List<DataType> typeArguments;
805+ private boolean frozen;
728806
729- private Collection(DataType.Name name, List<DataType> typeArguments) {
807+ private Collection(DataType.Name name, List<DataType> typeArguments, boolean frozen) {
730808 super(name);
731809 this.typeArguments = typeArguments;
810+ this.frozen = frozen;
811+ }
812+
813+ @Override
814+ public boolean isFrozen() {
815+ return frozen;
816+ }
817+
818+ @Override
819+ @SuppressWarnings("unchecked")
820+ boolean canBeDeserializedAs(TypeToken typeToken) {
821+ switch (name) {
822+ case LIST:
823+ return typeToken.getRawType().isAssignableFrom(List.class) &&
824+ typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0]));
825+ case SET:
826+ return typeToken.getRawType().isAssignableFrom(Set.class) &&
827+ typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0]));
828+ case MAP:
829+ return typeToken.getRawType().isAssignableFrom(Map.class) &&
830+ typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0])) &&
831+ typeArguments.get(1).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[1]));
832+ }
833+ throw new AssertionError();
732834 }
733835
734836 @SuppressWarnings("unchecked")
@@ -764,10 +866,14 @@
764866
765867 @Override
766868 public String toString() {
767- if (name == Name.MAP)
768- return String.format("%s<%s, %s>", name, typeArguments.get(0), typeArguments.get(1));
769- else
770- return String.format("%s<%s>", name, typeArguments.get(0));
869+ if (name == Name.MAP) {
870+ String template = frozen ? "frozen<%s<%s, %s>>" : "%s<%s, %s>";
871+ return String.format(template, name, typeArguments.get(0), typeArguments.get(1));
872+ }
873+ else {
874+ String template = frozen ? "frozen<%s<%s>>" : "%s<%s>";
875+ return String.format(template, name, typeArguments.get(0));
876+ }
771877 }
772878 }
773879
@@ -780,6 +886,16 @@
780886 this.customClassName = className;
781887 }
782888
889+ @Override
890+ public boolean isFrozen() {
891+ return false;
892+ }
893+
894+ @Override
895+ boolean canBeDeserializedAs(TypeToken typeToken) {
896+ return typeToken.getRawType().getName().equals(customClassName);
897+ }
898+
783899 @SuppressWarnings("unchecked")
784900 @Override
785901 TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
modified driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java +82 −7
@@ -21,6 +21,8 @@
2121 import java.nio.ByteBuffer;
2222 import java.util.*;
2323
24+import com.google.common.reflect.TypeToken;
25+
2426 import com.datastax.driver.core.exceptions.InvalidTypeException;
2527
2628 /**
@@ -206,55 +208,128 @@
206208
207209 /**
208210 * Returns the {@code i}th value as a list.
211+ * <p>
212+ * If the type of the elements is generic, use {@link #getList(int, TypeToken)}.
209213 *
210214 * @param i the index ({@code 0 <= i < size()}) to retrieve.
211215 * @param elementsClass the class for the elements of the list to retrieve.
212216 * @return the value of the {@code i}th element as a list of
213- * {@code elementsClass} objects. If the value is NULL, an empty list is
217+ * {@code T} objects. If the value is NULL, an empty list is
214218 * returned (note that Cassandra makes no difference between an empty list
215219 * and column of type list that is not set). The returned list is immutable.
216220 *
217221 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
218222 * @throws InvalidTypeException if value {@code i} is not a list or if its
219- * elements are not of class {@code elementsClass}.
223+ * elements are not of class {@code T}.
220224 */
221225 public <T> List<T> getList(int i, Class<T> elementsClass);
222226
227+ /**
228+ * Returns the {@code i}th value as a list.
229+ * <p>
230+ * Use this variant with nested collections, which produce a generic element type:
231+ * <pre>
232+ * {@code List<List<String>> l = row.getList(1, new TypeToken<List<String>>() {});}
233+ * </pre>
234+ *
235+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
236+ * @param elementsType the type of the elements of the list to retrieve.
237+ * @return the value of the {@code i}th element as a list of
238+ * {@code T} objects. If the value is NULL, an empty list is
239+ * returned (note that Cassandra makes no difference between an empty list
240+ * and column of type list that is not set). The returned list is immutable.
241+ *
242+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
243+ * @throws InvalidTypeException if value {@code i} is not a list or if its
244+ * elements are not of class {@code T}.
245+ */
246+ public <T> List<T> getList(int i, TypeToken<T> elementsType);
247+
223248 /**
224249 * Returns the {@code i}th value as a set.
250+ * <p>
251+ * If the type of the elements is generic, use {@link #getSet(int, TypeToken)}.
225252 *
226253 * @param i the index ({@code 0 <= i < size()}) to retrieve.
227254 * @param elementsClass the class for the elements of the set to retrieve.
228255 * @return the value of the {@code i}th element as a set of
229- * {@code elementsClass} objects. If the value is NULL, an empty set is
256+ * {@code T} objects. If the value is NULL, an empty set is
230257 * returned (note that Cassandra makes no difference between an empty set
231258 * and column of type set that is not set). The returned set is immutable.
232259 *
233260 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
234261 * @throws InvalidTypeException if value {@code i} is not a set or if its
235- * elements are not of class {@code elementsClass}.
262+ * elements are not of class {@code T}.
236263 */
237264 public <T> Set<T> getSet(int i, Class<T> elementsClass);
238265
266+ /**
267+ * Returns the {@code i}th value as a set.
268+ * <p>
269+ * Use this variant with nested collections, which produce a generic element type:
270+ * <pre>
271+ * {@code Set<List<String>> l = row.getSet(1, new TypeToken<List<String>>() {});}
272+ * </pre>
273+ *
274+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
275+ * @param elementsType the type for the elements of the set to retrieve.
276+ * @return the value of the {@code i}th element as a set of
277+ * {@code T} objects. If the value is NULL, an empty set is
278+ * returned (note that Cassandra makes no difference between an empty set
279+ * and column of type set that is not set). The returned set is immutable.
280+ *
281+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
282+ * @throws InvalidTypeException if value {@code i} is not a set or if its
283+ * elements are not of class {@code T}.
284+ */
285+ public <T> Set<T> getSet(int i, TypeToken<T> elementsType);
286+
239287 /**
240288 * Returns the {@code i}th value as a map.
289+ * <p>
290+ * If the type of the keys and/or values is generic, use {@link #getMap(int, TypeToken, TypeToken)}.
241291 *
242292 * @param i the index ({@code 0 <= i < size()}) to retrieve.
243293 * @param keysClass the class for the keys of the map to retrieve.
244294 * @param valuesClass the class for the values of the map to retrieve.
245295 * @return the value of the {@code i}th element as a map of
246- * {@code keysClass} to {@code valuesClass} objects. If the value is NULL,
296+ * {@code K} to {@code V} objects. If the value is NULL,
247297 * an empty map is returned (note that Cassandra makes no difference
248298 * between an empty map and column of type map that is not set). The
249299 * returned map is immutable.
250300 *
251301 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
252302 * @throws InvalidTypeException if value {@code i} is not a map, if its
253- * keys are not of class {@code keysClass} or if its values are not of
254- * class {@code valuesClass}.
303+ * keys are not of class {@code K} or if its values are not of
304+ * class {@code V}.
255305 */
256306 public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass);
257307
308+
309+ /**
310+ * Returns the {@code i}th value as a map.
311+ * <p>
312+ * Use this variant with nested collections, which produce a generic element type:
313+ * <pre>
314+ * {@code Map<Int, List<String>> l = row.getMap(1, TypeToken.of(Integer.class), new TypeToken<List<String>>() {});}
315+ * </pre>
316+ *
317+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
318+ * @param keysType the type for the keys of the map to retrieve.
319+ * @param valuesType the type for the values of the map to retrieve.
320+ * @return the value of the {@code i}th element as a map of
321+ * {@code K} to {@code V} objects. If the value is NULL,
322+ * an empty map is returned (note that Cassandra makes no difference
323+ * between an empty map and column of type map that is not set). The
324+ * returned map is immutable.
325+ *
326+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
327+ * @throws InvalidTypeException if value {@code i} is not a map, if its
328+ * keys are not of class {@code K} or if its values are not of
329+ * class {@code V}.
330+ */
331+ public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType);
332+
258333 /**
259334 * Return the {@code i}th value as a UDT value.
260335 *
modified driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java +81 −7
@@ -21,6 +21,8 @@
2121 import java.nio.ByteBuffer;
2222 import java.util.*;
2323
24+import com.google.common.reflect.TypeToken;
25+
2426 import com.datastax.driver.core.exceptions.InvalidTypeException;
2527
2628 /**
@@ -206,55 +208,127 @@
206208
207209 /**
208210 * Returns the value for {@code name} as a list.
211+ * <p>
212+ * If the type of the elements is generic, use {@link #getList(String, TypeToken)}.
209213 *
210214 * @param name the name to retrieve.
211215 * @param elementsClass the class for the elements of the list to retrieve.
212216 * @return the value of the {@code i}th element as a list of
213- * {@code elementsClass} objects. If the value is NULL, an empty list is
217+ * {@code T} objects. If the value is NULL, an empty list is
214218 * returned (note that Cassandra makes no difference between an empty list
215219 * and column of type list that is not set). The returned list is immutable.
216220 *
217221 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
218222 * @throws InvalidTypeException if value {@code name} is not a list or if its
219- * elements are not of class {@code elementsClass}.
223+ * elements are not of class {@code T}.
220224 */
221225 public <T> List<T> getList(String name, Class<T> elementsClass);
222226
227+ /**
228+ * Returns the value for {@code name} as a list.
229+ * <p>
230+ * Use this variant with nested collections, which produce a generic element type:
231+ * <pre>
232+ * {@code List<List<String>> l = row.getList("theColumn", new TypeToken<List<String>>() {});}
233+ * </pre>
234+ *
235+ * @param name the name to retrieve.
236+ * @param elementsType the type for the elements of the list to retrieve.
237+ * @return the value of the {@code i}th element as a list of
238+ * {@code T} objects. If the value is NULL, an empty list is
239+ * returned (note that Cassandra makes no difference between an empty list
240+ * and column of type list that is not set). The returned list is immutable.
241+ *
242+ * @throws IllegalArgumentException if {@code name} is not valid name for this object.
243+ * @throws InvalidTypeException if value {@code name} is not a list or if its
244+ * elements are not of class {@code T}.
245+ */
246+ public <T> List<T> getList(String name, TypeToken<T> elementsType);
247+
223248 /**
224249 * Returns the value for {@code name} as a set.
250+ * <p>
251+ * If the type of the elements is generic, use {@link #getSet(String, TypeToken)}.
225252 *
226253 * @param name the name to retrieve.
227254 * @param elementsClass the class for the elements of the set to retrieve.
228255 * @return the value of the {@code i}th element as a set of
229- * {@code elementsClass} objects. If the value is NULL, an empty set is
256+ * {@code T} objects. If the value is NULL, an empty set is
230257 * returned (note that Cassandra makes no difference between an empty set
231258 * and column of type set that is not set). The returned set is immutable.
232259 *
233260 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
234261 * @throws InvalidTypeException if value {@code name} is not a set or if its
235- * elements are not of class {@code elementsClass}.
262+ * elements are not of class {@code T}.
236263 */
237264 public <T> Set<T> getSet(String name, Class<T> elementsClass);
238265
266+ /**
267+ * Returns the value for {@code name} as a set.
268+ * <p>
269+ * Use this variant with nested collections, which produce a generic element type:
270+ * <pre>
271+ * {@code Set<List<String>> l = row.getSet("theColumn", new TypeToken<List<String>>() {});}
272+ * </pre>
273+ *
274+ * @param name the name to retrieve.
275+ * @param elementsType the type for the elements of the set to retrieve.
276+ * @return the value of the {@code i}th element as a set of
277+ * {@code T} objects. If the value is NULL, an empty set is
278+ * returned (note that Cassandra makes no difference between an empty set
279+ * and column of type set that is not set). The returned set is immutable.
280+ *
281+ * @throws IllegalArgumentException if {@code name} is not valid name for this object.
282+ * @throws InvalidTypeException if value {@code name} is not a set or if its
283+ * elements are not of class {@code T}.
284+ */
285+ public <T> Set<T> getSet(String name, TypeToken<T> elementsType);
286+
239287 /**
240288 * Returns the value for {@code name} as a map.
289+ * <p>
290+ * If the type of the keys and/or values is generic, use {@link #getMap(String, TypeToken, TypeToken)}.
241291 *
242292 * @param name the name to retrieve.
243293 * @param keysClass the class for the keys of the map to retrieve.
244294 * @param valuesClass the class for the values of the map to retrieve.
245295 * @return the value of {@code name} as a map of
246- * {@code keysClass} to {@code valuesClass} objects. If the value is NULL,
296+ * {@code K} to {@code V} objects. If the value is NULL,
247297 * an empty map is returned (note that Cassandra makes no difference
248298 * between an empty map and column of type map that is not set). The
249299 * returned map is immutable.
250300 *
251301 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
252302 * @throws InvalidTypeException if value {@code name} is not a map, if its
253- * keys are not of class {@code keysClass} or if its values are not of
254- * class {@code valuesClass}.
303+ * keys are not of class {@code K} or if its values are not of
304+ * class {@code V}.
255305 */
256306 public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass);
257307
308+ /**
309+ * Returns the value for {@code name} as a map.
310+ * <p>
311+ * Use this variant with nested collections, which produce a generic element type:
312+ * <pre>
313+ * {@code Map<Int, List<String>> l = row.getMap("theColumn", TypeToken.of(Integer.class), new TypeToken<List<String>>() {});}
314+ * </pre>
315+ *
316+ * @param name the name to retrieve.
317+ * @param keysType the class for the keys of the map to retrieve.
318+ * @param valuesType the class for the values of the map to retrieve.
319+ * @return the value of {@code name} as a map of
320+ * {@code K} to {@code V} objects. If the value is NULL,
321+ * an empty map is returned (note that Cassandra makes no difference
322+ * between an empty map and column of type map that is not set). The
323+ * returned map is immutable.
324+ *
325+ * @throws IllegalArgumentException if {@code name} is not valid name for this object.
326+ * @throws InvalidTypeException if value {@code name} is not a map, if its
327+ * keys are not of class {@code K} or if its values are not of
328+ * class {@code V}.
329+ */
330+ public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType);
331+
258332 /**
259333 * Return the value for {@code name} as a UDT value.
260334 *
modified driver-core/src/main/java/com/datastax/driver/core/TupleType.java +13 −2
@@ -18,6 +18,7 @@
1818 import java.util.*;
1919
2020 import com.google.common.collect.ImmutableList;
21+import com.google.common.reflect.TypeToken;
2122
2223 import com.datastax.driver.core.exceptions.InvalidTypeException;
2324
@@ -99,6 +100,16 @@
99100 return t;
100101 }
101102
103+ @Override
104+ public boolean isFrozen() {
105+ return true;
106+ }
107+
108+ @Override
109+ boolean canBeDeserializedAs(TypeToken typeToken) {
110+ return typeToken.isAssignableFrom(getName().javaType);
111+ }
112+
102113 @Override
103114 public int hashCode() {
104115 return Arrays.hashCode(new Object[]{ name, types });
@@ -117,9 +128,9 @@
117128 public String toString() {
118129 StringBuilder sb = new StringBuilder();
119130 for (DataType type : types) {
120- sb.append(sb.length() == 0 ? "tuple<" : ", ");
131+ sb.append(sb.length() == 0 ? "frozen<tuple<" : ", ");
121132 sb.append(type);
122133 }
123- return sb.append(">").toString();
134+ return sb.append(">>").toString();
124135 }
125136 }
modified driver-core/src/main/java/com/datastax/driver/core/UserType.java +13 −2
@@ -19,6 +19,7 @@
1919
2020 import com.google.common.collect.ImmutableMap;
2121 import com.google.common.collect.Iterators;
22+import com.google.common.reflect.TypeToken;
2223
2324 import com.datastax.driver.core.exceptions.InvalidTypeException;
2425
@@ -166,6 +167,16 @@
166167 return byIdx[idx[0]].getType();
167168 }
168169
170+ @Override
171+ public boolean isFrozen() {
172+ return true;
173+ }
174+
175+ @Override
176+ boolean canBeDeserializedAs(TypeToken typeToken) {
177+ return typeToken.isAssignableFrom(getName().javaType);
178+ }
179+
169180 @Override
170181 public final int hashCode() {
171182 return Arrays.hashCode(new Object[]{ name, keyspace, typeName, byIdx });
@@ -225,12 +236,12 @@
225236 TableMetadata.newLine(sb, formatted);
226237 }
227238
228- return sb.append(')').toString();
239+ return sb.append(");").toString();
229240 }
230241
231242 @Override
232243 public String toString() {
233- return Metadata.escapeId(getKeyspace()) + '.' + Metadata.escapeId(getTypeName());
244+ return "frozen<" + Metadata.escapeId(getKeyspace()) + '.' + Metadata.escapeId(getTypeName()) + ">";
234245 }
235246
236247 // We don't want to expose that, it's already exposed through DataType.parse
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +1 −2
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.ArrayList;
2019 import java.util.List;
2120
@@ -361,7 +360,7 @@
361360 StringBuilder sb = new StringBuilder();
362361 Utils.appendName(columnName, sb);
363362 sb.append('[');
364- Utils.appendFlatValue(key, sb);
363+ Utils.appendValue(key, sb);
365364 return column(sb.append(']').toString());
366365 }
367366 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +5 −14
@@ -26,7 +26,6 @@
2626 import com.datastax.driver.core.ProtocolVersion;
2727 import com.datastax.driver.core.TupleValue;
2828 import com.datastax.driver.core.UDTValue;
29-import com.datastax.driver.core.utils.Bytes;
3029
3130 // Static utilities private to the query builder
3231 abstract class Utils {
@@ -96,7 +95,7 @@
9695 return sb;
9796 }
9897
99- private static StringBuilder appendValue(Object value, StringBuilder sb) {
98+ static StringBuilder appendValue(Object value, StringBuilder sb) {
10099 // That is kind of lame but lacking a better solution
101100 if (appendValueIfLiteral(value, sb))
102101 return sb;
@@ -114,14 +113,6 @@
114113 return sb;
115114 }
116115
117- static StringBuilder appendFlatValue(Object value, StringBuilder sb) {
118- if (appendValueIfLiteral(value, sb))
119- return sb;
120-
121- appendStringIfValid(value, sb);
122- return sb;
123- }
124-
125116 private static void appendStringIfValid(Object value, StringBuilder sb) {
126117 if (value instanceof RawString) {
127118 sb.append(value.toString());
@@ -205,7 +196,7 @@
205196 for (int i = 0; i < l.size(); i++) {
206197 if (i > 0)
207198 sb.append(',');
208- appendFlatValue(l.get(i), sb);
199+ appendValue(l.get(i), sb);
209200 }
210201 sb.append(']');
211202 return sb;
@@ -216,7 +207,7 @@
216207 boolean first = true;
217208 for (Object elt : s) {
218209 if (first) first = false; else sb.append(',');
219- appendFlatValue(elt, sb);
210+ appendValue(elt, sb);
220211 }
221212 sb.append('}');
222213 return sb;
@@ -230,9 +221,9 @@
230221 first = false;
231222 else
232223 sb.append(',');
233- appendFlatValue(entry.getKey(), sb);
224+ appendValue(entry.getKey(), sb);
234225 sb.append(':');
235- appendFlatValue(entry.getValue(), sb);
226+ appendValue(entry.getValue(), sb);
236227 }
237228 sb.append('}');
238229 return sb;
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +4 −0
@@ -15,4 +15,8 @@
1515 public static TokenRangeAssert assertThat(TokenRange range) {
1616 return new TokenRangeAssert(range);
1717 }
18+
19+ public static DataTypeAssert assertThat(DataType type) {
20+ return new DataTypeAssert(type);
21+ }
1822 }
modified driver-core/src/test/java/com/datastax/driver/core/CassandraTypeParserTest.java +26 −3
@@ -17,10 +17,15 @@
1717
1818 import java.util.Arrays;
1919 import java.util.Iterator;
20-import java.util.List;
2120
2221 import org.testng.annotations.Test;
23-import static org.testng.Assert.*;
22+
23+import static org.testng.Assert.assertEquals;
24+import static org.testng.Assert.assertFalse;
25+import static org.testng.Assert.assertNotNull;
26+import static org.testng.Assert.assertTrue;
27+
28+import static com.datastax.driver.core.Assertions.assertThat;
2429
2530 public class CassandraTypeParserTest {
2631
@@ -44,7 +49,7 @@
4449 public void parseWithCompositeTest() {
4550
4651 String s = "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type, org.apache.cassandra.db.marshal.UTF8Type,";
47- s += "org.apache.cassandra.db.marshal.ColumnToCollectionType(6162:org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))";
52+ s += "org.apache.cassandra.db.marshal.ColumnToCollectionType(6162:org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))";
4853 CassandraTypeParser.ParseResult r1 = CassandraTypeParser.parseWithComposite(s);
4954 assertTrue(r1.isComposite);
5055 assertEquals(r1.types, Arrays.asList(DataType.cint(), DataType.text()));
@@ -106,4 +111,22 @@
106111 assertEquals(type.getComponentTypes().get(1), DataType.text());
107112 assertEquals(type.getComponentTypes().get(2), DataType.cfloat());
108113 }
114+
115+ @Test(groups = "unit")
116+ public void parseNestedCollectionTest() {
117+ // map<text, frozen<map<int,int>>>
118+ String s = "org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.Int32Type)))";
119+
120+ DataType parentMap = CassandraTypeParser.parseOne(s);
121+ assertThat(parentMap)
122+ .hasName(DataType.Name.MAP)
123+ .isNotFrozen()
124+ .hasTypeArgument(0, DataType.text());
125+
126+ DataType childMap = parentMap.getTypeArguments().get(1);
127+ assertThat(childMap)
128+ .hasName(DataType.Name.MAP)
129+ .isFrozen()
130+ .hasTypeArguments(DataType.cint(), DataType.cint());
131+ }
109132 }
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +2 −2
@@ -12,6 +12,7 @@
1212 import com.datastax.driver.core.policies.LoadBalancingPolicy;
1313 import com.datastax.driver.core.policies.Policies;
1414 import com.datastax.driver.core.policies.ReconnectionPolicy;
15+import com.datastax.driver.core.utils.CassandraVersion;
1516
1617 public class ControlConnectionTest {
1718 @Test(groups = "short")
@@ -73,9 +74,8 @@
7374 * Therefore we use two different driver instances in this test.
7475 */
7576 @Test(groups = "short")
77+ @CassandraVersion(major=2.1)
7678 public void should_parse_UDT_definitions_when_using_default_protocol_version() {
77- TestUtils.versionCheck(2.1, 0, "This will only work with C* 2.1.0");
78-
7979 CCMBridge ccm = null;
8080 Cluster cluster = null;
8181
added driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java +47 −0
@@ -0,0 +1,47 @@
1+package com.datastax.driver.core;
2+
3+import com.google.common.reflect.TypeToken;
4+import org.assertj.core.api.AbstractAssert;
5+
6+import static com.datastax.driver.core.Assertions.assertThat;
7+
8+public class DataTypeAssert extends AbstractAssert<DataTypeAssert, DataType> {
9+ public DataTypeAssert(DataType actual) {
10+ super(actual, DataTypeAssert.class);
11+ }
12+
13+ public DataTypeAssert hasName(DataType.Name name) {
14+ assertThat(actual.name).isEqualTo(name);
15+ return this;
16+ }
17+
18+ public DataTypeAssert isFrozen() {
19+ assertThat(actual.isFrozen()).isTrue();
20+ return this;
21+ }
22+
23+ public DataTypeAssert isNotFrozen() {
24+ assertThat(actual.isFrozen()).isFalse();
25+ return this;
26+ }
27+
28+ public DataTypeAssert canBeDeserializedAs(TypeToken typeToken) {
29+ assertThat(actual.canBeDeserializedAs(typeToken)).isTrue();
30+ return this;
31+ }
32+
33+ public DataTypeAssert cannotBeDeserializedAs(TypeToken typeToken) {
34+ assertThat(actual.canBeDeserializedAs(typeToken)).isFalse();
35+ return this;
36+ }
37+
38+ public DataTypeAssert hasTypeArgument(int position, DataType expected) {
39+ assertThat(actual.getTypeArguments().get(position)).isEqualTo(expected);
40+ return this;
41+ }
42+
43+ public DataTypeAssert hasTypeArguments(DataType... expected) {
44+ assertThat(actual.getTypeArguments()).containsExactly(expected);
45+ return this;
46+ }
47+}
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +221 −540
@@ -15,627 +15,308 @@
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.text.SimpleDateFormat;
2318 import java.util.*;
24-
25-import com.google.common.collect.ImmutableSet;
26-
19+import java.util.concurrent.atomic.AtomicInteger;
20+
21+import com.google.common.collect.*;
22+import org.slf4j.Logger;
23+import org.slf4j.LoggerFactory;
2724 import org.testng.annotations.Test;
2825
29-import static com.datastax.driver.core.DataTypeTest.exclude;
30-import static org.testng.Assert.assertEquals;
31-import static org.testng.Assert.assertTrue;
26+import static org.assertj.core.api.Assertions.assertThat;
3227
3328 import com.datastax.driver.core.utils.CassandraVersion;
3429
3530 /**
36- * Tests DataType class to ensure data sent in is the same as data received
37- * All tests are executed via a Simple Statements
38- * Counters are the only datatype not tested within the entirety of the suite.
39- * There is, however, an isolated test case that needs to be implemented.
40- * All statements and sample data is easily exportable via the print_*() methods.
31+ * The goal of this test is to cover the serialization and deserialization of datatypes.
32+ *
33+ * It creates a table with a column of a given type, inserts a value and then tries to retrieve it.
34+ * There are 3 variants for the insert query: a raw string, a simple statement with a parameter
35+ * (protocol > v2 only) and a prepared statement.
36+ * This is repeated with a large number of datatypes.
4137 */
4238 public class DataTypeIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
39+ private static final Logger logger = LoggerFactory.getLogger(DataTypeIntegrationTest.class);
4340
44- private final static Set<DataType> DATA_TYPE_PRIMITIVES = DataType.allPrimitiveTypes();
45- private final static Set<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES = EnumSet.of(DataType.Name.MAP, DataType.Name.SET, DataType.Name.LIST);
46-
47- private final static String PRIMITIVE_INSERT_FORMAT = "INSERT INTO %1$s (k, v) VALUES (%2$s, %2$s);";
48- private final static String BASIC_SELECT_FORMAT = "SELECT k, v FROM %1$s;";
49-
50- private final static String COLLECTION_INSERT_FORMAT = "INSERT INTO %1$s (k, v) VALUES (%2$s, %3$s);";
51- private final static String MAP_INSERT_FORMAT = "INSERT INTO %1$s (k, v) VALUES (%3$s, {%2$s: %3$s});";
41+ List<TestTable> tables = allTables();
42+ VersionNumber cassandraVersion;
5243
53- private final static HashMap<DataType, Object> SAMPLE_DATA = getSampleData();
54- private final static HashMap<DataType, Object> SAMPLE_COLLECTIONS = getSampleCollections();
44+ enum StatementType {RAW_STRING, SIMPLE_WITH_PARAM, PREPARED}
5545
56- private final static Collection<String> PRIMITIVE_INSERT_STATEMENTS = getPrimitiveInsertStatements();
57- private final static HashMap<DataType, String> PRIMITIVE_SELECT_STATEMENTS = getPrimitiveSelectStatements();
58-
59- private final static Collection<String> COLLECTION_INSERT_STATEMENTS = getCollectionInsertStatements();
60- private final static HashMap<DataType, String> COLLECTION_SELECT_STATEMENTS = getCollectionSelectStatements();
61-
62- /**
63- * Generates the table definitions that will be used in testing
64- */
6546 @Override
6647 protected Collection<String> getTableDefinitions() {
67- ArrayList<String> tableDefinitions = new ArrayList<String>();
68-
69- // Create primitive data type definitions
70- for (DataType dataType : DATA_TYPE_PRIMITIVES) {
71- if (exclude(dataType))
72- continue;
73-
74- tableDefinitions.add(String.format("CREATE TABLE %1$s (k %2$s PRIMARY KEY, v %1$s)", dataType, dataType));
75- }
48+ Host host = cluster.getMetadata().getAllHosts().iterator().next();
49+ cassandraVersion = host.getCassandraVersion().nextStable();
7650
77- // Create collection data type definitions
78- for (DataType.Name dataTypeName : DATA_TYPE_NON_PRIMITIVE_NAMES) {
79- // Create MAP data type definitions
80- if (dataTypeName == DataType.Name.MAP) {
81- for (DataType typeArgument1 : DATA_TYPE_PRIMITIVES) {
82- if (exclude(typeArgument1))
83- continue;
84-
85- for (DataType typeArgument2 : DATA_TYPE_PRIMITIVES) {
86- if (exclude(typeArgument2))
87- continue;
88-
89- tableDefinitions.add(String.format("CREATE TABLE %1$s_%2$s_%3$s (k %3$s PRIMARY KEY, v %1$s<%2$s, %3$s>)", dataTypeName, typeArgument1, typeArgument2));
90- }
91- }
92- // Create SET and LIST data type definitions
93- } else {
94- for (DataType typeArgument : DATA_TYPE_PRIMITIVES) {
95- if (exclude(typeArgument))
96- continue;
97-
98- tableDefinitions.add(String.format("CREATE TABLE %1$s_%2$s (k %2$s PRIMARY KEY, v %1$s<%2$s>)", dataTypeName, typeArgument));
99- }
100- }
51+ List<String> statements = Lists.newArrayList();
52+ for (TestTable table : tables) {
53+ if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
54+ logger.debug("Skipping table because it uses a feature not supported by Cassandra {}: {}",
55+ cassandraVersion, table.createStatement);
56+ else
57+ statements.add(table.createStatement);
10158 }
10259
103- return tableDefinitions;
60+ return statements;
10461 }
10562
106- /**
107- * Generates the sample data that will be used in testing
108- */
109- protected static HashMap<DataType, Object> getSampleData() {
110- HashMap<DataType, Object> sampleData = new HashMap<DataType, Object>();
111-
112- for (DataType dataType : DATA_TYPE_PRIMITIVES) {
113- switch (dataType.getName()) {
114- case ASCII:
115- sampleData.put(dataType, new String("ascii"));
116- break;
117- case BIGINT:
118- sampleData.put(dataType, Long.MAX_VALUE);
119- break;
120- case BLOB:
121- ByteBuffer bb = ByteBuffer.allocate(58);
122- bb.putShort((short) 0xCAFE);
123- bb.flip();
124- sampleData.put(dataType, bb);
125- break;
126- case BOOLEAN:
127- sampleData.put(dataType, Boolean.TRUE);
128- break;
129- case COUNTER:
130- // Not supported in an insert statement
131- break;
132- case DECIMAL:
133- sampleData.put(dataType, new BigDecimal("12.3E+7"));
134- break;
135- case DOUBLE:
136- sampleData.put(dataType, Double.MAX_VALUE);
137- break;
138- case FLOAT:
139- sampleData.put(dataType, Float.MAX_VALUE);
140- break;
141- case INET:
142- try {
143- sampleData.put(dataType, InetAddress.getByName("123.123.123.123"));
144- } catch (java.net.UnknownHostException e) {}
145- break;
146- case INT:
147- sampleData.put(dataType, Integer.MAX_VALUE);
148- break;
149- case TEXT:
150- sampleData.put(dataType, new String("text"));
151- break;
152- case TIMESTAMP:
153- sampleData.put(dataType, new Date(872835240000L));
154- break;
155- case TIMEUUID:
156- sampleData.put(dataType, UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"));
157- break;
158- case UUID:
159- sampleData.put(dataType, UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"));
160- break;
161- case VARCHAR:
162- sampleData.put(dataType, new String("varchar"));
163- break;
164- case VARINT:
165- sampleData.put(dataType, new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000"));
166- break;
167- default:
168- throw new RuntimeException("Missing handling of " + dataType);
169- }
170- }
63+ @Test(groups = "long")
64+ public void should_insert_and_retrieve_data_with_legacy_statements() {
65+ should_insert_and_retrieve_data(StatementType.RAW_STRING);
66+ }
17167
172- return sampleData;
68+ @Test(groups = "long")
69+ public void should_insert_and_retrieve_data_with_prepared_statements() {
70+ should_insert_and_retrieve_data(StatementType.PREPARED);
17371 }
17472
175- protected static Object getCollectionSample(DataType.Name collectionType, DataType dataType) {
176- if(collectionType == DataType.Name.LIST) {
177- List<Object> theList = new ArrayList<Object>();
178- theList.add(SAMPLE_DATA.get(dataType));
179- theList.add(SAMPLE_DATA.get(dataType));
180- return theList;
181- }
182- else if(collectionType == DataType.Name.SET)
183- return ImmutableSet.of(SAMPLE_DATA.get(dataType));
184- else if(collectionType == DataType.Name.MAP)
185- return new HashMap<Object, Object>().put(SAMPLE_DATA.get(dataType), SAMPLE_DATA.get(dataType));
186- else if(collectionType == DataType.Name.TUPLE) {
187- TupleType t = TupleType.of(dataType);
188- return t.newValue(SAMPLE_DATA.get(dataType));
189- }
190- else
191- throw new IllegalArgumentException("Missing handling of non-primitive type" + collectionType);
73+ @Test(groups = "long")
74+ @CassandraVersion(major = 2.0, description = "Uses parameterized simple statements, which are only available with protocol v2")
75+ public void should_insert_and_retrieve_data_with_parameterized_simple_statements() {
76+ should_insert_and_retrieve_data(StatementType.SIMPLE_WITH_PARAM);
19277 }
19378
194- /**
195- * Generates the sample collections that will be used in testing
196- */
197- protected static HashMap<DataType, Object> getSampleCollections() {
198- HashMap<DataType, Object> sampleCollections = new HashMap<DataType, Object>();
199- HashMap<DataType, Object> setAndListCollection;
200- HashMap<DataType, HashMap<DataType, Object>> mapCollection;
201-
202- for (DataType.Name dataTypeName : DATA_TYPE_NON_PRIMITIVE_NAMES) {
203- switch (dataTypeName) {
204- case LIST:
205- for (DataType typeArgument : DATA_TYPE_PRIMITIVES) {
206- if (exclude(typeArgument))
207- continue;
208-
209- List<Object> list = new ArrayList<Object>();
210- for (int i = 0; i < 5; i++) {
211- list.add(SAMPLE_DATA.get(typeArgument));
212- }
213-
214- setAndListCollection = new HashMap<DataType, Object>();
215- setAndListCollection.put(typeArgument, list);
216- sampleCollections.put(DataType.list(typeArgument), setAndListCollection);
217- }
79+ protected void should_insert_and_retrieve_data(StatementType statementType) {
80+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
81+
82+ for (TestTable table : tables) {
83+ if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
84+ continue;
85+
86+ switch (statementType) {
87+ case RAW_STRING:
88+ session.execute(table.insertStatement.replace("?", table.testColumnType.format(table.sampleValue)));
21889 break;
219- case SET:
220- for (DataType typeArgument : DATA_TYPE_PRIMITIVES) {
221- if (exclude(typeArgument))
222- continue;
223-
224- Set<Object> set = new HashSet<Object>();
225- for (int i = 0; i < 5; i++) {
226- set.add(SAMPLE_DATA.get(typeArgument));
227- }
228-
229- setAndListCollection = new HashMap<DataType, Object>();
230- setAndListCollection.put(typeArgument, set);
231- sampleCollections.put(DataType.set(typeArgument), setAndListCollection);
232- }
90+ case SIMPLE_WITH_PARAM:
91+ session.execute(table.insertStatement, table.sampleValue);
23392 break;
234- case MAP:
235- for (DataType typeArgument1 : DATA_TYPE_PRIMITIVES) {
236- if (exclude(typeArgument1))
237- continue;
238-
239- for (DataType typeArgument2 : DATA_TYPE_PRIMITIVES) {
240- if (exclude(typeArgument2))
241- continue;
242-
243- HashMap<DataType, Object> map = new HashMap<DataType, Object>();
244- map.put(typeArgument1, SAMPLE_DATA.get(typeArgument2));
245-
246- mapCollection = new HashMap<DataType, HashMap<DataType, Object>>();
247- mapCollection.put(typeArgument1, map);
248- sampleCollections.put(DataType.map(typeArgument1, typeArgument2), mapCollection);
249- }
250- }
93+ case PREPARED:
94+ PreparedStatement ps = session.prepare(table.insertStatement);
95+ session.execute(ps.bind(table.sampleValue));
25196 break;
252- default:
253- throw new RuntimeException("Missing handling of " + dataTypeName);
25497 }
255- }
256-
257- return sampleCollections;
258- }
25998
260- /**
261- * Helper method to stringify SAMPLE_DATA for simple insert statements
262- */
263- @SuppressWarnings("fallthrough")
264- private static String helperStringifiedData(DataType dataType) {
265- String value = SAMPLE_DATA.get(dataType).toString();
266-
267- switch (dataType.getName()) {
268- case BLOB:
269- value = "0xCAFE";
270- break;
271-
272- case INET:
273- InetAddress v1 = (InetAddress) SAMPLE_DATA.get(dataType);
274- value = String.format("'%s'", v1.getHostAddress());
275- break;
276-
277- case TIMESTAMP:
278- Date v2 = (Date) SAMPLE_DATA.get(dataType);
279- value = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(v2);
280- case ASCII:
281- case TEXT:
282- case VARCHAR:
283- value = String.format("'%s'", value);
284- break;
285-
286- default:
287- break;
288- }
99+ Row row = session.execute(table.selectStatement).one();
100+ Object queriedValue = table.testColumnType.deserialize(row.getBytesUnsafe("v"), protocolVersion);
289101
290- return value;
291- }
102+ assertThat(queriedValue)
103+ .as("Test failure on %s statement with table:%n%s;%n" +
104+ "insert statement:%n%s;%n",
105+ statementType,
106+ table.createStatement,
107+ table.insertStatement)
108+ .isEqualTo(table.sampleValue);
292109
293- /**
294- * Generates the insert statements that will be used in testing
295- */
296- private static Collection<String> getPrimitiveInsertStatements() {
297- ArrayList<String> insertStatements = new ArrayList<String>();
298-
299- for (DataType dataType : SAMPLE_DATA.keySet()) {
300- String value = helperStringifiedData(dataType);
301- insertStatements.add(String.format(PRIMITIVE_INSERT_FORMAT, dataType, value));
110+ session.execute(table.truncateStatement);
302111 }
303-
304- return insertStatements;
305112 }
306113
307114 /**
308- * Generates the select statements that will be used in testing
115+ * Abstracts information about a table (corresponding to a given column type).
309116 */
310- private static HashMap<DataType, String> getPrimitiveSelectStatements() {
311- HashMap<DataType, String> selectStatements = new HashMap<DataType, String>();
312-
313- for (DataType dataType : SAMPLE_DATA.keySet()) {
314- selectStatements.put(dataType, String.format(BASIC_SELECT_FORMAT, dataType));
315- }
117+ static class TestTable {
118+ private static final AtomicInteger counter = new AtomicInteger();
119+ private String tableName = "date_type_test" + counter.incrementAndGet();
316120
317- return selectStatements;
318- }
121+ final DataType testColumnType;
122+ final Object sampleValue;
319123
320- /**
321- * Helper method to generate table names in the form of:
322- * DataType_TypeArgument[_TypeArgument]
323- */
324- private static String helperGenerateTableName(DataType dataType) {
325- String tableName = dataType.getName().toString();
326- for (DataType typeArgument : dataType.getTypeArguments())
327- tableName += "_" + typeArgument;
328-
329- return tableName;
330- }
124+ final String createStatement;
125+ final String insertStatement = String.format("INSERT INTO %s (k, v) VALUES (1, ?)", tableName);
126+ final String selectStatement = String.format("SELECT v FROM %s WHERE k = 1", tableName);
127+ final String truncateStatement = String.format("TRUNCATE %s", tableName);
331128
332- /**
333- * Generates the insert statements that will be used in testing
334- */
335- @SuppressWarnings("unchecked")
336- private static Collection<String> getCollectionInsertStatements() {
337- ArrayList<String> insertStatements = new ArrayList<String>();
338-
339- String tableName;
340- String key;
341- String value;
342- for (DataType dataType : SAMPLE_COLLECTIONS.keySet()) {
343- HashMap<DataType, Object> sampleValueMap = (HashMap<DataType, Object>) SAMPLE_COLLECTIONS.get(dataType);
344-
345- // Create tableName in form of: DataType_TypeArgument[_TypeArgument]
346- tableName = helperGenerateTableName(dataType);
347-
348- if (dataType.getName() == DataType.Name.MAP) {
349- List<DataType> typeArgument = dataType.getTypeArguments();
350-
351- key = helperStringifiedData(typeArgument.get(0));
352- value = helperStringifiedData(typeArgument.get(1));
353-
354- insertStatements.add(String.format(MAP_INSERT_FORMAT, tableName, key, value));
355- } else if (dataType.getName() == DataType.Name.LIST) {
356- DataType typeArgument = sampleValueMap.keySet().iterator().next();
357- key = helperStringifiedData(typeArgument);
358-
359- // Create the value to be a list of the same 5 elements
360- value = "[";
361- for (int i = 0; i < 5; i++)
362- value += key + ',';
363- value = value.substring(0, value.length() - 1) + ']';
364-
365- insertStatements.add(String.format(COLLECTION_INSERT_FORMAT, tableName, key, value));
366- } else {
367- DataType typeArgument = sampleValueMap.keySet().iterator().next();
368- key = helperStringifiedData(typeArgument);
369- value = '{' + key + '}';
370-
371- insertStatements.add(String.format(COLLECTION_INSERT_FORMAT, tableName, key, value));
372- }
373- }
129+ final VersionNumber minCassandraVersion;
374130
375- return insertStatements;
376- }
131+ TestTable(DataType testColumnType, Object sampleValue, String minCassandraVersion) {
132+ this.testColumnType = testColumnType;
133+ this.sampleValue = sampleValue;
134+ this.minCassandraVersion = VersionNumber.parse(minCassandraVersion);
377135
378- /**
379- * Generates the select statements that will be used in testing
380- */
381- private static HashMap<DataType, String> getCollectionSelectStatements() {
382- HashMap<DataType, String> selectStatements = new HashMap<DataType, String>();
383-
384- String tableName;
385- for (DataType dataType : SAMPLE_COLLECTIONS.keySet()) {
386- tableName = helperGenerateTableName(dataType);
387- selectStatements.put(dataType, String.format(BASIC_SELECT_FORMAT, tableName));
136+ this.createStatement = String.format("CREATE TABLE %s (k int PRIMARY KEY, v %s)", tableName, testColumnType);
388137 }
389-
390- return selectStatements;
391138 }
392139
393- /**
394- * Test simple statement inserts for all primitive data types
395- */
396- public void primitiveInsertTest() throws Throwable {
397- ResultSet rs;
398- for (String execute_string : PRIMITIVE_INSERT_STATEMENTS) {
399- rs = session.execute(execute_string);
400- assertTrue(rs.isExhausted());
401- }
402- assertEquals(SAMPLE_DATA.size(), 14);
403- assertEquals(PRIMITIVE_INSERT_STATEMENTS.size(), SAMPLE_DATA.size());
404- }
140+ private static List<TestTable> allTables() {
141+ List<TestTable> tables = Lists.newArrayList();
405142
406- /**
407- * Validate simple statement selects for all primitive data types
408- */
409- public void primitiveSelectTest() throws Throwable {
410- String execute_string;
411- Object value;
412- Row row;
413- for (DataType dataType : PRIMITIVE_SELECT_STATEMENTS.keySet()) {
414- execute_string = PRIMITIVE_SELECT_STATEMENTS.get(dataType);
415- row = session.execute(execute_string).one();
416-
417- value = SAMPLE_DATA.get(dataType);
418- assertEquals(TestUtils.getValue(row, "k", dataType), value);
419- assertEquals(TestUtils.getValue(row, "v", dataType), value);
420- }
421- assertEquals(SAMPLE_DATA.size(), 14);
422- assertEquals(PRIMITIVE_SELECT_STATEMENTS.keySet().size(), SAMPLE_DATA.size());
143+ tables.addAll(tablesWithPrimitives());
144+ tables.addAll(tablesWithCollectionsOfPrimitives());
145+ tables.addAll(tablesWithMapsOfPrimitives());
146+ tables.addAll(tablesWithNestedCollections());
147+ tables.addAll(tablesWithRandomlyGeneratedNestedCollections());
148+
149+ return ImmutableList.copyOf(tables);
423150 }
424151
425- /**
426- * Test simple statement inserts and selects for all primitive data types
427- */
428- @Test(groups = "long")
429- public void primitiveTests() throws Throwable {
430- primitiveInsertTest();
431- primitiveSelectTest();
152+ private static List<TestTable> tablesWithPrimitives() {
153+ List<TestTable> tables = Lists.newArrayList();
154+ for (Map.Entry<DataType, Object> entry : PrimitiveTypeSamples.ALL.entrySet())
155+ tables.add(new TestTable(entry.getKey(), entry.getValue(), "1.2.0"));
156+ return tables;
432157 }
433158
434- @Test(groups = "short")
435- @CassandraVersion(major=2.0, minor=0, description="This feature requires protocol v2")
436- public void primitiveInsertWithValueTest() throws Throwable {
437- for (DataType dt : DataType.allPrimitiveTypes()) {
438- if (exclude(dt))
439- continue;
159+ private static List<TestTable> tablesWithCollectionsOfPrimitives() {
160+ List<TestTable> tables = Lists.newArrayList();
161+ for (Map.Entry<DataType, Object> entry : PrimitiveTypeSamples.ALL.entrySet()) {
440162
441- session.execute(String.format(PRIMITIVE_INSERT_FORMAT, dt, "?"), SAMPLE_DATA.get(dt), SAMPLE_DATA.get(dt));
442- }
443- // Kind of checking results (kind of because the schema used by this class make it ultra painful
444- // somehow to use a different partition for different tests, so that the insert done here actually
445- // conflict with the one in primitiveInsertTest. So all we check is that we don't write something
446- // horribly wrong, but if the inserts of this test where to do nothing, the following check might
447- // not work. We should fix the schema used by this class)
448- primitiveSelectTest();
449- }
163+ DataType elementType = entry.getKey();
164+ Object elementSample = entry.getValue();
450165
451- /**
452- * Test simple statement inserts for all collection data types
453- */
454- public void collectionInsertTest() throws Throwable {
455- ResultSet rs;
456- for (String execute_string : COLLECTION_INSERT_STATEMENTS) {
457- rs = session.execute(execute_string);
458- assertTrue(rs.isExhausted());
166+ tables.add(new TestTable(DataType.list(elementType), Lists.newArrayList(elementSample, elementSample), "1.2.0"));
167+ tables.add(new TestTable(DataType.set(elementType), Sets.newHashSet(elementSample), "1.2.0"));
459168 }
460- assertEquals(SAMPLE_COLLECTIONS.size(), 224);
461- assertEquals(COLLECTION_INSERT_STATEMENTS.size(), SAMPLE_COLLECTIONS.size());
169+ return tables;
462170 }
463171
464- /**
465- * Test simple statement selects for all collection data types
466- */
467- @SuppressWarnings("unchecked")
468- public void collectionSelectTest() throws Throwable {
469- HashMap<DataType, Object> sampleValueMap;
470- String execute_string;
471- DataType typeArgument1;
472- DataType typeArgument2;
473- Row row;
474- for (DataType dataType : COLLECTION_SELECT_STATEMENTS.keySet()) {
475- execute_string = COLLECTION_SELECT_STATEMENTS.get(dataType);
476- row = session.execute(execute_string).one();
477-
478- sampleValueMap = (HashMap<DataType, Object>) SAMPLE_COLLECTIONS.get(dataType);
479- typeArgument1 = dataType.getTypeArguments().get(0);
480- if (dataType.getName() == DataType.Name.MAP) {
481- typeArgument2 = dataType.getTypeArguments().get(1);
482-
483- // Create a copy of the map that is being expected
484- HashMap<DataType, Object> sampleMap = (HashMap<DataType, Object>) sampleValueMap.get(typeArgument1);
485- Object mapKey = SAMPLE_DATA.get(sampleMap.keySet().iterator().next());
486- Object mapValue = sampleMap.values().iterator().next();
487- HashMap<Object, Object> expectedMap = new HashMap<Object, Object>();
488- expectedMap.put(mapKey, mapValue);
489-
490- assertEquals(TestUtils.getValue(row, "k", typeArgument2), SAMPLE_DATA.get(typeArgument2));
491- assertEquals(TestUtils.getValue(row, "v", dataType), expectedMap);
492- } else {
493- Object expectedValue = sampleValueMap.get(typeArgument1);
172+ private static List<TestTable> tablesWithMapsOfPrimitives() {
173+ List<TestTable> tables = Lists.newArrayList();
174+ for (Map.Entry<DataType, Object> keyEntry : PrimitiveTypeSamples.ALL.entrySet()) {
175+ DataType keyType = keyEntry.getKey();
176+ Object keySample = keyEntry.getValue();
177+ for (Map.Entry<DataType, Object> valueEntry : PrimitiveTypeSamples.ALL.entrySet()) {
178+ DataType valueType = valueEntry.getKey();
179+ Object valueSample = valueEntry.getValue();
494180
495- assertEquals(TestUtils.getValue(row, "k", typeArgument1), SAMPLE_DATA.get(typeArgument1));
496- assertEquals(TestUtils.getValue(row, "v", dataType), expectedValue);
181+ tables.add(new TestTable(DataType.map(keyType, valueType),
182+ ImmutableMap.builder().put(keySample, valueSample).build(),
183+ "1.2.0"));
497184 }
498185 }
499- assertEquals(SAMPLE_COLLECTIONS.size(), 224);
500- assertEquals(COLLECTION_SELECT_STATEMENTS.keySet().size(), SAMPLE_COLLECTIONS.size());
186+ return tables;
501187 }
502188
503- /**
504- * Test simple statement inserts and selects for all collection data types
505- */
506- @Test(groups = "long")
507- public void collectionTest() throws Throwable {
508- collectionInsertTest();
509- collectionSelectTest();
510- }
189+ private static Collection<? extends TestTable> tablesWithNestedCollections() {
190+ List<TestTable> tables = Lists.newArrayList();
511191
512- /**
513- * Prints the table definitions that will be used in testing
514- * (for exporting purposes)
515- */
516- @Test(groups = "doc")
517- public void printTableDefinitions() {
518- String objective = "Table Definitions";
519- System.out.println(String.format("Printing %s...", objective));
520-
521- // Prints the full list of table definitions
522- for (String definition : getTableDefinitions()) {
523- System.out.println(definition);
524- }
192+ // To avoid combinatorial explosion, only use int as the primitive type, and two levels of nesting.
193+ // This yields collections like list<frozen<map<int, int>>, map<frozen<set<int>>, frozen<list<int>>>, etc.
525194
526- System.out.println(String.format("\nEnd of %s\n\n", objective));
527- }
195+ // Types and samples for the inner collections like frozen<list<int>>
196+ Map<DataType, Object> childCollectionSamples = ImmutableMap.<DataType, Object>builder()
197+ .put(DataType.frozenList(DataType.cint()), Lists.newArrayList(1, 1))
198+ .put(DataType.frozenSet(DataType.cint()), Sets.newHashSet(1, 2))
199+ .put(DataType.frozenMap(DataType.cint(), DataType.cint()), ImmutableMap.<Integer, Integer>builder().put(1, 2).put(3, 4).build())
200+ .build();
528201
529- /**
530- * Prints the sample data that will be used in testing
531- * (for exporting purposes)
532- */
533- @Test(groups = "doc")
534- public void printSampleData() {
535- String objective = "Sample Data";
536- System.out.println(String.format("Printing %s...", objective));
537-
538- for (DataType dataType : SAMPLE_DATA.keySet()) {
539- Object sampleValue = SAMPLE_DATA.get(dataType);
540- System.out.println(String.format("%1$-10s %2$s", dataType, sampleValue));
541- }
202+ for (Map.Entry<DataType, Object> entry : childCollectionSamples.entrySet()) {
203+ DataType elementType = entry.getKey();
204+ Object elementSample = entry.getValue();
542205
543- System.out.println(String.format("\nEnd of %s\n\n", objective));
544- }
206+ tables.add(new TestTable(DataType.list(elementType), Lists.newArrayList(elementSample, elementSample), "2.1.3"));
207+ tables.add(new TestTable(DataType.set(elementType), Sets.newHashSet(elementSample), "2.1.3"));
545208
546- /**
547- * Prints the sample collections that will be used in testing
548- * (for exporting purposes)
549- */
550- @Test(groups = "doc")
551- @SuppressWarnings("unchecked")
552- public void printSampleCollections() {
553- String objective = "Sample Collections";
554- System.out.println(String.format("Printing %s...", objective));
555-
556- for (DataType dataType : SAMPLE_COLLECTIONS.keySet()) {
557- HashMap<DataType, Object> sampleValueMap = (HashMap<DataType, Object>) SAMPLE_COLLECTIONS.get(dataType);
558-
559- if (dataType.getName() == DataType.Name.MAP) {
560- DataType typeArgument = sampleValueMap.keySet().iterator().next();
561- HashMap<DataType, Object> sampleMap = (HashMap<DataType, Object>) sampleValueMap.get(typeArgument);
562-
563- Object mapKey = SAMPLE_DATA.get(typeArgument);
564- Object mapValue = sampleMap.get(typeArgument);
565- System.out.println(String.format("%1$-30s {%2$s : %3$s}", dataType, mapKey, mapValue));
566- } else {
567- DataType typeArgument = sampleValueMap.keySet().iterator().next();
568- Object sampleValue = sampleValueMap.get(typeArgument);
209+ for (Map.Entry<DataType, Object> valueEntry : childCollectionSamples.entrySet()) {
210+ DataType valueType = valueEntry.getKey();
211+ Object valueSample = valueEntry.getValue();
569212
570- System.out.println(String.format("%1$-30s %2$s", dataType, sampleValue));
213+ tables.add(new TestTable(DataType.map(elementType, valueType),
214+ ImmutableMap.builder().put(elementSample, valueSample).build(), "2.1.3"));
571215 }
572216 }
573-
574- System.out.println(String.format("\nEnd of %s\n\n", objective));
217+ return tables;
575218 }
576219
577- /**
578- * Prints the simple insert statements that will be used in testing
579- * (for exporting purposes)
580- */
581- @Test(groups = "doc")
582- public void printPrimitiveInsertStatements() {
583- String objective = "Primitive Insert Statements";
584- System.out.println(String.format("Printing %s...", objective));
585-
586- for (String execute_string : PRIMITIVE_INSERT_STATEMENTS) {
587- System.out.println(execute_string);
588- }
220+ private static Collection<? extends TestTable> tablesWithRandomlyGeneratedNestedCollections() {
221+ List<TestTable> tables = Lists.newArrayList();
222+
223+ DataType nestedListType = buildNestedType(DataType.Name.LIST, 5);
224+ DataType nestedSetType = buildNestedType(DataType.Name.SET, 5);
225+ DataType nestedMapType = buildNestedType(DataType.Name.MAP, 5);
589226
590- System.out.println(String.format("\nEnd of %s\n\n", objective));
227+ tables.add(new TestTable(nestedListType, nestedObject(nestedListType), "2.1.3"));
228+ tables.add(new TestTable(nestedSetType, nestedObject(nestedSetType), "2.1.3"));
229+ tables.add(new TestTable(nestedMapType, nestedObject(nestedMapType), "2.1.3"));
230+ return tables;
591231 }
592232
593233 /**
594- * Prints the simple select statements that will be used in testing
595- * (for exporting purposes)
234+ * Populate a nested collection based on the given type and it's arguments.
596235 */
597- @Test(groups = "doc")
598- public void printPrimitiveSelectStatements() {
599- String objective = "Primitive Select Statements";
600- System.out.println(String.format("Printing %s...", objective));
601-
602- for (String execute_string : PRIMITIVE_SELECT_STATEMENTS.values()) {
603- System.out.println(execute_string);
604- }
236+ public static Object nestedObject(DataType type) {
605237
606- System.out.println(String.format("\nEnd of %s\n\n", objective));
607- }
238+ int typeIdx = type.getTypeArguments().size() > 1 ? 1 : 0;
239+ DataType argument = type.getTypeArguments().get(typeIdx);
240+ boolean isAtBottom = !argument.isCollection();
608241
609- /**
610- * Prints the simple insert statements that will be used in testing
611- * (for exporting purposes)
612- */
613- @Test(groups = "doc")
614- public void printCollectionInsertStatements() {
615- String objective = "Collection Insert Statements";
616- System.out.println(String.format("Printing %s...", objective));
617-
618- for (String execute_string : COLLECTION_INSERT_STATEMENTS) {
619- System.out.println(execute_string);
242+ if(isAtBottom) {
243+ switch(type.getName()) {
244+ case LIST:
245+ return Lists.newArrayList(1, 2, 3);
246+ case SET:
247+ return Sets.newHashSet(1, 2, 3);
248+ case MAP:
249+ Map<Integer, Integer> map = Maps.newHashMap();
250+ map.put(1, 2);
251+ map.put(3, 4);
252+ map.put(5, 6);
253+ return map;
254+ }
620255 }
621-
622- System.out.println(String.format("\nEnd of %s\n\n", objective));
256+ else {
257+ switch(type.getName()) {
258+ case LIST:
259+ List<Object> l = Lists.newArrayListWithExpectedSize(2);
260+ for(int i = 0; i < 5; i++) {
261+ l.add(nestedObject(argument));
262+ }
263+ return l;
264+ case SET:
265+ Set<Object> s = Sets.newHashSet();
266+ for(int i = 0; i < 5; i++) {
267+ s.add(nestedObject(argument));
268+ }
269+ return s;
270+ case MAP:
271+ Map<Integer, Object> map = Maps.newHashMap();
272+ for(int i = 0; i < 5; i++) {
273+ map.put(i, nestedObject(argument));
274+ }
275+ return map;
276+ }
277+ }
278+ return null;
623279 }
624280
625281 /**
626- * Prints the simple insert statements that will be used in testing
627- * (for exporting purposes)
282+ * @param baseType The base type to use, one of SET, MAP, LIST.
283+ * @param depth How many subcollections to generate.
284+ * @return a DataType that is a nested collection with the given baseType with the
285+ * given depth.
628286 */
629- @Test(groups = "doc")
630- public void printCollectionSelectStatements() {
631- String objective = "Collection Select Statements";
632- System.out.println(String.format("Printing %s...", objective));
633-
634- for (String execute_string : COLLECTION_SELECT_STATEMENTS.values()) {
635- System.out.println(execute_string);
636- }
287+ public static DataType buildNestedType(DataType.Name baseType, int depth) {
288+ Random r = new Random();
289+ DataType t = null;
637290
638- System.out.println(String.format("\nEnd of %s\n\n", objective));
291+ for (int i = 1; i <= depth; i++) {
292+ int chooser = r.nextInt(3);
293+ if(t == null) {
294+ if(chooser == 0) {
295+ t = DataType.frozenList(DataType.cint());
296+ } else if(chooser == 1) {
297+ t = DataType.frozenSet(DataType.cint());
298+ } else {
299+ t = DataType.frozenMap(DataType.cint(), DataType.cint());
300+ }
301+ } else if(i == depth) {
302+ switch(baseType) {
303+ case LIST:
304+ return DataType.list(t);
305+ case SET:
306+ return DataType.set(t);
307+ case MAP:
308+ return DataType.map(DataType.cint(), t);
309+ }
310+ } else {
311+ if(chooser == 0) {
312+ t = DataType.frozenList(t);
313+ } else if(chooser == 1) {
314+ t = DataType.frozenSet(t);
315+ } else {
316+ t = DataType.frozenMap(DataType.cint(), t);
317+ }
318+ }
319+ }
320+ return null;
639321 }
640322 }
641-
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +25 −2
@@ -19,15 +19,19 @@
1919 import java.math.BigInteger;
2020 import java.net.InetAddress;
2121 import java.nio.ByteBuffer;
22-import java.text.SimpleDateFormat;
2322 import java.util.*;
2423
24+import com.google.common.reflect.TypeToken;
2525 import org.testng.annotations.Test;
26-import static org.testng.Assert.*;
26+
27+import static org.testng.Assert.assertEquals;
28+import static org.testng.Assert.fail;
2729
2830 import com.datastax.driver.core.exceptions.InvalidTypeException;
2931 import com.datastax.driver.core.utils.Bytes;
3032
33+import static com.datastax.driver.core.Assertions.assertThat;
34+
3135 /**
3236 * DataType simple unit tests.
3337 */
@@ -246,4 +250,23 @@
246250 fail("This should not have worked");
247251 } catch (InvalidTypeException e) { /* That's what we want */ }
248252 }
253+
254+ @Test(groups = "unit")
255+ public void should_check_which_java_type_it_can_be_deserialized_to() {
256+ assertThat(DataType.cint())
257+ .canBeDeserializedAs(TypeToken.of(Integer.class))
258+ .canBeDeserializedAs(TypeToken.of(Number.class))
259+ .cannotBeDeserializedAs(TypeToken.of(String.class));
260+
261+ assertThat(DataType.list(DataType.cint()))
262+ .canBeDeserializedAs(new TypeToken<List<Integer>>(){})
263+ .canBeDeserializedAs(new TypeToken<Collection<Integer>>(){})
264+ .cannotBeDeserializedAs(new TypeToken<Set<Integer>>(){})
265+ .cannotBeDeserializedAs(new TypeToken<List<String>>(){});
266+
267+ assertThat(DataType.map(DataType.cint(), DataType.frozenList(DataType.text())))
268+ .canBeDeserializedAs(new TypeToken<Map<Integer, List<String>>>(){})
269+ .canBeDeserializedAs(new TypeToken<Map<Number, Collection<String>>>(){})
270+ .cannotBeDeserializedAs(new TypeToken<Map<Integer, Collection<Integer>>>(){});
271+ }
249272 }
added driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java +74 −0
@@ -0,0 +1,74 @@
1+/*
2+ * Copyright (C) 2012-2014 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.util.Date;
23+import java.util.List;
24+import java.util.Map;
25+import java.util.UUID;
26+
27+import com.google.common.collect.ImmutableMap;
28+import com.google.common.collect.Lists;
29+
30+import static org.assertj.core.api.Assertions.assertThat;
31+
32+import com.datastax.driver.core.utils.Bytes;
33+
34+/**
35+ * This class provides sample values for each primitive data type.
36+ *
37+ * These values have no particular meaning, the goal is just to have an instance that can be used in automated tests.
38+ */
39+public class PrimitiveTypeSamples {
40+
41+ public static final Map<DataType, Object> ALL = generateAll();
42+
43+ private static Map<DataType, Object> generateAll() {
44+ try {
45+ ImmutableMap<DataType, Object> result = ImmutableMap.<DataType, Object>builder()
46+ .put(DataType.ascii(), "ascii")
47+ .put(DataType.bigint(), Long.MAX_VALUE)
48+ .put(DataType.blob(), Bytes.fromHexString("0xCAFE"))
49+ .put(DataType.cboolean(), Boolean.TRUE)
50+ .put(DataType.decimal(), new BigDecimal("12.3E+7"))
51+ .put(DataType.cdouble(), Double.MAX_VALUE)
52+ .put(DataType.cfloat(), Float.MAX_VALUE)
53+ .put(DataType.inet(), InetAddress.getByName("123.123.123.123"))
54+ .put(DataType.cint(), Integer.MAX_VALUE)
55+ .put(DataType.text(), "text")
56+ .put(DataType.timestamp(), new Date(872835240000L))
57+ .put(DataType.timeuuid(), UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"))
58+ .put(DataType.uuid(), UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"))
59+ .put(DataType.varint(), new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000"))
60+ .build();
61+
62+ // Check that we cover all types (except counter)
63+ List<DataType> tmp = Lists.newArrayList(DataType.allPrimitiveTypes());
64+ tmp.removeAll(result.keySet());
65+ assertThat(tmp)
66+ .as("new datatype not covered in test")
67+ .containsOnly(DataType.counter());
68+
69+ return result;
70+ } catch (UnknownHostException e) {
71+ throw new AssertionError(e);
72+ }
73+ }
74+}
modified driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java +2 −4
@@ -11,18 +11,16 @@
1111 import com.datastax.driver.core.Cluster.Builder;
1212 import com.datastax.driver.core.Metrics.Errors;
1313 import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
14-
15-import static com.datastax.driver.core.TestUtils.versionCheck;
14+import com.datastax.driver.core.utils.CassandraVersion;
1615
1716 /**
1817 * Tests the behavior of client-provided timestamps with protocol v3.
1918 */
19+@CassandraVersion(major=2.1)
2020 public class QueryTimestampTest extends CCMBridge.PerClassSingleNodeCluster {
2121
2222 @Override
2323 protected Collection<String> getTableDefinitions() {
24- versionCheck(2.1, 0, "This will only work with Cassandra 2.1.0");
25-
2624 return Lists.newArrayList("CREATE TABLE foo (k int PRIMARY KEY, v int)");
2725 }
2826
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +2 −2
@@ -71,7 +71,7 @@
7171 session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace));
7272
7373 for (Metadata m : metadatas)
74- assertThat(m.getKeyspace(keyspace).getUserType("type1"))
74+ assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1"))
7575 .isNotNull();
7676 }
7777
@@ -93,7 +93,7 @@
9393 session.execute(String.format("DROP TYPE %s.type1", keyspace));
9494
9595 for (Metadata m : metadatas)
96- assertThat(m.getKeyspace(keyspace).getUserType("type1"))
96+ assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1"))
9797 .isNull();
9898 }
9999
modified driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java +3 −2
@@ -12,11 +12,12 @@
1212
1313 import static org.testng.Assert.fail;
1414
15+import com.datastax.driver.core.utils.CassandraVersion;
16+
17+@CassandraVersion(major=2.1)
1518 public class SingleConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
1619 @Override
1720 protected Collection<String> getTableDefinitions() {
18- TestUtils.versionCheck(2.1, 0, "This will only work with Cassandra 2.1.0+");
19-
2021 return Lists.newArrayList();
2122 }
2223
modified driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +15 −48
@@ -15,24 +15,25 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
1918 import java.nio.ByteBuffer;
19+import java.util.*;
2020
21+import com.beust.jcommander.internal.Lists;
2122 import com.google.common.base.Joiner;
2223 import org.testng.annotations.Test;
2324
24-import static com.datastax.driver.core.DataTypeIntegrationTest.getSampleData;
25-import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
26-import static com.datastax.driver.core.TestUtils.versionCheck;
2725 import static org.testng.Assert.assertEquals;
2826 import static org.testng.Assert.fail;
2927
28+import com.datastax.driver.core.utils.CassandraVersion;
29+
30+import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
31+
32+@CassandraVersion(major=2.1)
3033 public class TupleTest extends CCMBridge.PerClassSingleNodeCluster {
3134
3235 @Override
3336 protected Collection<String> getTableDefinitions() {
34- versionCheck(2.1, 0, "This will only work with Cassandra 2.1.0");
35-
3637 return Arrays.asList("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)");
3738 }
3839
@@ -215,16 +216,7 @@
215216 @Test(groups = "short")
216217 public void tupleSubtypesTest() throws Exception {
217218
218- // hold onto constants
219- ArrayList<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>();
220- for (DataType dt : DataType.allPrimitiveTypes()) {
221- // skip counter types since counters are not allowed inside tuples
222- if (dt == DataType.counter())
223- continue;
224-
225- DATA_TYPE_PRIMITIVES.add(dt);
226- }
227- HashMap<DataType, Object> SAMPLE_DATA = getSampleData();
219+ List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet());
228220
229221 try {
230222 session.execute("CREATE KEYSPACE test_tuple_subtypes " +
@@ -249,8 +241,8 @@
249241 for (int j = 0; j < i; ++j) {
250242 dataTypes.add(DATA_TYPE_PRIMITIVES.get(j));
251243 completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(j));
252- createdValues.add(SAMPLE_DATA.get(DATA_TYPE_PRIMITIVES.get(j)));
253- completeValues.add(SAMPLE_DATA.get(DATA_TYPE_PRIMITIVES.get(j)));
244+ createdValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j)));
245+ completeValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j)));
254246 }
255247
256248 // complete portion of the arrays needed for trailing nulls
@@ -290,19 +282,7 @@
290282 @Test(groups = "short")
291283 public void tupleNonPrimitiveSubTypesTest() throws Exception {
292284
293- // hold onto constants
294- ArrayList<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>();
295- for (DataType dt : DataType.allPrimitiveTypes()) {
296- // skip counter types since counters are not allowed inside tuples
297- if (dt == DataType.counter())
298- continue;
299-
300- DATA_TYPE_PRIMITIVES.add(dt);
301- }
302- ArrayList<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES = new ArrayList<DataType.Name>(Arrays.asList(DataType.Name.MAP,
303- DataType.Name.SET,
304- DataType.Name.LIST));
305- HashMap<DataType, Object> SAMPLE_DATA = getSampleData();
285+ List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet());
306286
307287 try {
308288 session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
@@ -323,9 +303,7 @@
323303
324304 // create map values
325305 for (DataType datatype : DATA_TYPE_PRIMITIVES) {
326- DataType dataType1 = datatype;
327- DataType dataType2 = datatype;
328- values.add(String.format("v_%s frozen<tuple<map<%s, %s>>>", values.size(), dataType1, dataType2));
306+ values.add(String.format("v_%s frozen<tuple<map<%s, %s>>>", values.size(), datatype, datatype));
329307 }
330308
331309 // create table
@@ -340,7 +318,7 @@
340318 ArrayList<Object> createdValues = new ArrayList<Object>();
341319
342320 dataTypes.add(DataType.list(datatype));
343- createdValues.add(Arrays.asList(SAMPLE_DATA.get(datatype)));
321+ createdValues.add(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype)));
344322
345323 TupleType t = new TupleType(dataTypes);
346324 TupleValue createdTuple = t.newValue(createdValues.toArray());
@@ -363,7 +341,7 @@
363341 ArrayList<Object> createdValues = new ArrayList<Object>();
364342
365343 dataTypes.add(DataType.set(datatype));
366- createdValues.add(new HashSet<Object>(Arrays.asList(SAMPLE_DATA.get(datatype))));
344+ createdValues.add(new HashSet<Object>(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype))));
367345
368346 TupleType t = new TupleType(dataTypes);
369347 TupleValue createdTuple = t.newValue(createdValues.toArray());
@@ -386,7 +364,7 @@
386364 ArrayList<Object> createdValues = new ArrayList<Object>();
387365
388366 HashMap<Object, Object> hm = new HashMap<Object, Object>();
389- hm.put(SAMPLE_DATA.get(datatype), SAMPLE_DATA.get(datatype));
367+ hm.put(PrimitiveTypeSamples.ALL.get(datatype), PrimitiveTypeSamples.ALL.get(datatype));
390368
391369 dataTypes.add(DataType.map(datatype, datatype));
392370 createdValues.add(hm);
@@ -447,17 +425,6 @@
447425 @Test(groups = "short")
448426 public void nestedTuplesTest() throws Exception {
449427
450- // hold onto constants
451- ArrayList<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>();
452- for (DataType dt : DataType.allPrimitiveTypes()) {
453- // skip counter types since counters are not allowed inside tuples
454- if (dt == DataType.counter())
455- continue;
456-
457- DATA_TYPE_PRIMITIVES.add(dt);
458- }
459- HashMap<DataType, Object> SAMPLE_DATA = getSampleData();
460-
461428 try {
462429 session.execute("CREATE KEYSPACE test_nested_tuples " +
463430 "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +12 −11
@@ -22,28 +22,29 @@
2222 import java.nio.ByteBuffer;
2323 import java.util.*;
2424
25+import com.google.common.collect.ImmutableMap;
2526 import com.google.common.collect.ImmutableSet;
2627 import com.google.common.base.Joiner;
2728
29+import com.google.common.collect.Lists;
30+import com.google.common.collect.Sets;
2831 import org.testng.annotations.Test;
2932 import static org.testng.Assert.assertEquals;
3033
3134 import static com.datastax.driver.core.Metadata.quote;
32-import static com.datastax.driver.core.TestUtils.versionCheck;
3335 import static org.testng.Assert.assertNotEquals;
3436
37+import com.datastax.driver.core.utils.CassandraVersion;
38+
39+@CassandraVersion(major=2.1)
3540 public class UserTypesTest extends CCMBridge.PerClassSingleNodeCluster {
3641
3742 private final static List<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>(DataType.allPrimitiveTypes());
3843 private final static List<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES =
3944 new ArrayList<DataType.Name>(EnumSet.of(DataType.Name.LIST, DataType.Name.SET, DataType.Name.MAP, DataType.Name.TUPLE));
4045
41- private final static HashMap<DataType, Object> SAMPLE_DATA = DataTypeIntegrationTest.getSampleData();
42-
4346 @Override
4447 protected Collection<String> getTableDefinitions() {
45- versionCheck(2.1, 0, "This will only work with Cassandra 2.1.0");
46-
4748 String type1 = "CREATE TYPE phone (alias text, number text)";
4849 String type2 = "CREATE TYPE address (street text, \"ZIP\" int, phones set<frozen<phone>>)";
4950
@@ -242,7 +243,7 @@
242243 for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) {
243244 DataType dataType = DATA_TYPE_PRIMITIVES.get(i);
244245 String index = Character.toString((char) (startIndex + i));
245- Object sampleData = SAMPLE_DATA.get(dataType);
246+ Object sampleData = PrimitiveTypeSamples.ALL.get(dataType);
246247
247248 switch (dataType.getName()) {
248249 case ASCII:
@@ -365,19 +366,19 @@
365366 DataType dataType = DATA_TYPE_PRIMITIVES.get(j);
366367
367368 String index = Character.toString((char) (startIndex + i)) + "_" + Character.toString((char) (startIndex + j));
368- Object sample = DataTypeIntegrationTest.getCollectionSample(name, dataType);
369+ Object sampleElement = PrimitiveTypeSamples.ALL.get(dataType);
369370 switch(name) {
370371 case LIST:
371- alldatatypes.setList(index, (ArrayList<DataType>) sample);
372+ alldatatypes.setList(index, Lists.newArrayList(sampleElement));
372373 break;
373374 case SET:
374- alldatatypes.setSet(index, (Set<DataType>) sample);
375+ alldatatypes.setSet(index, Sets.newHashSet(sampleElement));
375376 break;
376377 case MAP:
377- alldatatypes.setMap(index, (HashMap<DataType, DataType>) sample);
378+ alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement));
378379 break;
379380 case TUPLE:
380- alldatatypes.setTupleValue(index, (TupleValue) sample);
381+ alldatatypes.setTupleValue(index, TupleType.of(dataType).newValue(sampleElement));
381382 }
382383 }
383384
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +2 −26
@@ -15,11 +15,7 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.net.InetAddress;
19-import java.util.Arrays;
20-import java.util.Collection;
21-import java.util.Date;
22-import java.util.List;
18+import java.util.*;
2319
2420 import org.testng.annotations.Test;
2521
@@ -36,9 +32,7 @@
3632 @Override
3733 protected Collection<String> getTableDefinitions() {
3834 return Arrays.asList(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1),
39- "CREATE TABLE dateTest (t timestamp PRIMARY KEY)",
40- "CREATE TYPE udt (i int, a inet)",
41- "CREATE TABLE udtTest(k int PRIMARY KEY, t frozen<udt>)");
35+ "CREATE TABLE dateTest (t timestamp PRIMARY KEY)");
4236 }
4337
4438 @Test(groups = "short")
@@ -108,22 +102,4 @@
108102 assertEquals("batchTest2", r2.getString("k"));
109103 assertEquals("val2", r2.getString("t"));
110104 }
111-
112- @Test(groups = "short")
113- public void insertUdtTest() throws Exception {
114- UserType udtType = cluster.getMetadata().getKeyspace("ks").getUserType("udt");
115- UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
116-
117- Statement insert = insertInto("udtTest").value("k", 1).value("t", udtValue);
118- assertEquals(insert.toString(), "INSERT INTO udtTest(k,t) VALUES (1,{i:2, a:'127.0.0.1'});");
119-
120- session.execute(insert);
121-
122- List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
123-
124- assertEquals(rows.size(), 1);
125-
126- Row r1 = rows.get(0);
127- assertEquals("127.0.0.1", r1.getUDTValue("t").getInet("a").getHostAddress());
128- }
129105 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +51 −2
@@ -20,13 +20,19 @@
2020 import java.net.InetAddress;
2121 import java.util.*;
2222
23+import com.google.common.collect.ImmutableList;
24+import com.google.common.collect.ImmutableMap;
2325 import org.testng.annotations.Test;
26+
27+import static org.assertj.core.api.Assertions.assertThat;
2428 import static org.testng.Assert.*;
2529
2630 import com.datastax.driver.core.*;
2731 import com.datastax.driver.core.querybuilder.Delete.Where;
2832 import com.datastax.driver.core.utils.Bytes;
33+import com.datastax.driver.core.utils.CassandraVersion;
2934
35+import static com.datastax.driver.core.DataType.cint;
3036 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3137
3238 public class QueryBuilderTest {
@@ -211,7 +217,7 @@
211217 assertEquals(insert.toString(), query);
212218
213219 query = "INSERT INTO foo(k,x) VALUES (0,(1));";
214- insert = insertInto("foo").value("k", 0).value("x", TupleType.of(DataType.cint()).newValue(1));
220+ insert = insertInto("foo").value("k", 0).value("x", TupleType.of(cint()).newValue(1));
215221 assertEquals(insert.toString(), query);
216222
217223 // UDT: see QueryBuilderExecutionTest
@@ -562,7 +568,11 @@
562568 assertEquals(insert.toString(), query);
563569
564570 query = "INSERT INTO foo(a,b) VALUES ({'2''} space','3','4'},3.4) USING TTL 24 AND TIMESTAMP 42;";
565- insert = insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<String>(){{ add("2'} space"); add("3"); add("4"); }}, 3.4 }).using(ttl(24)).and(timestamp(42));
571+ insert = insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<String>() {{
572+ add("2'} space");
573+ add("3");
574+ add("4");
575+ }}, 3.4 }).using(ttl(24)).and(timestamp(42));
566576 assertEquals(insert.toString(), query);
567577 }
568578
@@ -718,4 +728,43 @@
718728 // getValues() is called on any RegularStatement before we send it (see SessionManager.makeRequestMessage).
719729 statement.getValues(ProtocolVersion.V3);
720730 }
731+
732+ @Test(groups = "unit")
733+ public void should_handle_collections_of_tuples() {
734+ String query;
735+ Statement statement;
736+
737+ query = "UPDATE foo SET l=[(1, 2)] WHERE k=1;";
738+ List<TupleValue> list = ImmutableList.of(TupleType.of(cint(), cint()).newValue(1, 2));
739+ statement = update("foo").with(set("l", list)).where(eq("k", 1));
740+ assertThat(statement.toString()).isEqualTo(query);
741+ }
742+
743+ @Test(groups = "unit")
744+ @CassandraVersion(major = 2.1, minor = 3)
745+ public void should_handle_nested_collections() {
746+ String query;
747+ Statement statement;
748+
749+ query = "UPDATE foo SET l=[[1],[2]] WHERE k=1;";
750+ ImmutableList<ImmutableList<Integer>> list = ImmutableList.of(ImmutableList.of(1), ImmutableList.of(2));
751+ statement = update("foo").with(set("l", list)).where(eq("k", 1));
752+ assertThat(statement.toString()).isEqualTo(query);
753+
754+ query = "UPDATE foo SET m={1:[[1],[2]],2:[[1],[2]]} WHERE k=1;";
755+ statement = update("foo").with(set("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1));
756+ assertThat(statement.toString()).isEqualTo(query);
757+
758+ query = "UPDATE foo SET m=m+{1:[[1],[2]],2:[[1],[2]]} WHERE k=1;";
759+ statement = update("foo").with(putAll("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1));
760+ assertThat(statement.toString()).isEqualTo(query);
761+
762+ query = "UPDATE foo SET l=[[1]]+l WHERE k=1;";
763+ statement = update("foo").with(prepend("l", ImmutableList.of(1))).where(eq("k", 1));
764+ assertThat(statement.toString()).isEqualTo(query);
765+
766+ query = "UPDATE foo SET l=[[1],[2]]+l WHERE k=1;";
767+ statement = update("foo").with(prependAll("l", list)).where(eq("k", 1));
768+ assertThat(statement.toString()).isEqualTo(query);
769+ }
721770 }
added driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java +83 −0
@@ -0,0 +1,83 @@
1+package com.datastax.driver.core.querybuilder;
2+
3+import java.net.InetAddress;
4+import java.util.Arrays;
5+import java.util.Collection;
6+import java.util.List;
7+import java.util.Map;
8+
9+import com.google.common.collect.ImmutableList;
10+import com.google.common.collect.Maps;
11+import org.testng.annotations.Test;
12+
13+import static org.assertj.core.api.Assertions.assertThat;
14+import static org.testng.Assert.assertEquals;
15+
16+import com.datastax.driver.core.*;
17+import com.datastax.driver.core.utils.CassandraVersion;
18+
19+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
20+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
21+import static com.datastax.driver.core.querybuilder.QueryBuilder.putAll;
22+import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
23+import static com.datastax.driver.core.querybuilder.QueryBuilder.update;
24+
25+@CassandraVersion(major=2.1, minor=3)
26+public class QueryBuilderUDTExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
27+
28+ @Override
29+ protected Collection<String> getTableDefinitions() {
30+ return Arrays.asList("CREATE TYPE udt (i int, a inet)",
31+ "CREATE TABLE udtTest(k int PRIMARY KEY, t frozen<udt>, l list<frozen<udt>>, m map<int, frozen<udt>>)");
32+ }
33+
34+ @Test(groups = "short")
35+ public void insertUdtTest() throws Exception {
36+ UserType udtType = cluster.getMetadata().getKeyspace("ks").getUserType("udt");
37+ UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
38+
39+ Statement insert = insertInto("udtTest").value("k", 1).value("t", udtValue);
40+ assertEquals(insert.toString(), "INSERT INTO udtTest(k,t) VALUES (1,{i:2, a:'127.0.0.1'});");
41+
42+ session.execute(insert);
43+
44+ List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
45+
46+ assertEquals(rows.size(), 1);
47+
48+ Row r1 = rows.get(0);
49+ assertEquals("127.0.0.1", r1.getUDTValue("t").getInet("a").getHostAddress());
50+ }
51+
52+ @Test(groups = "short")
53+ public void should_handle_collections_of_UDT() throws Exception {
54+ UserType udtType = cluster.getMetadata().getKeyspace("ks").getUserType("udt");
55+ UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost"));
56+ UDTValue udtValue2 = udtType.newValue().setInt("i", 3).setInet("a", InetAddress.getByName("localhost"));
57+
58+ Statement insert = insertInto("udtTest").value("k", 1).value("l", ImmutableList.of(udtValue));
59+ assertThat(insert.toString()).isEqualTo("INSERT INTO udtTest(k,l) VALUES (1,[{i:2, a:'127.0.0.1'}]);");
60+
61+ session.execute(insert);
62+
63+ List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
64+
65+ assertThat(rows.size()).isEqualTo(1);
66+
67+ Row r1 = rows.get(0);
68+ assertThat(r1.getList("l", UDTValue.class).get(0).getInet("a").getHostAddress()).isEqualTo("127.0.0.1");
69+
70+ Map<Integer, UDTValue> map = Maps.newHashMap();
71+ map.put(0, udtValue);
72+ map.put(2, udtValue2);
73+ Statement updateMap = update("udtTest").with(putAll("m", map)).where(eq("k", 1));
74+ assertThat(updateMap.toString())
75+ .isEqualTo("UPDATE udtTest SET m=m+{0:{i:2, a:'127.0.0.1'},2:{i:3, a:'127.0.0.1'}} WHERE k=1;");
76+
77+ session.execute(updateMap);
78+
79+ rows = session.execute(select().from("udtTest").where(eq("k", 1))).all();
80+ r1 = rows.get(0);
81+ assertThat(r1.getMap("m", Integer.class, UDTValue.class)).isEqualTo(map);
82+ }
83+}
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/SchemaBuilderIT.java +3 −4
@@ -11,6 +11,7 @@
1111
1212 import com.datastax.driver.core.*;
1313 import com.datastax.driver.core.schemabuilder.TableOptions.CompactionOptions.DateTieredCompactionStrategyOptions.TimeStampResolution;
14+import com.datastax.driver.core.utils.CassandraVersion;
1415
1516 import static com.datastax.driver.core.schemabuilder.SchemaBuilder.dateTieredStrategy;
1617 import static com.datastax.driver.core.schemabuilder.SchemaBuilder.percentile;
@@ -25,9 +26,8 @@
2526 }
2627
2728 @Test(groups = "short")
29+ @CassandraVersion(major=2.1, minor=2)
2830 public void should_modify_table_metadata() {
29- TestUtils.versionCheck(2.1, 2, "This test requires Cassandra 2.1.2");
30-
3131 // Create a table
3232 session.execute(SchemaBuilder.createTable("ks", "TableMetadata")
3333 .addPartitionKey("a", DataType.cint())
@@ -122,9 +122,8 @@
122122 }
123123
124124 @Test(groups = "short")
125+ @CassandraVersion(major=2.1)
125126 public void should_create_a_table_and_a_udt() {
126- TestUtils.versionCheck(2.1, 0, "This test requires Cassandra 2.1.0");
127-
128127 // Create a UDT and a table
129128 session.execute(SchemaBuilder.createType("MyUDT")
130129 .ifNotExists()
modified driver-mapping/pom.xml +7 −0
@@ -55,6 +55,13 @@
5555 <scope>test</scope>
5656 </dependency>
5757
58+ <dependency>
59+ <groupId>org.mockito</groupId>
60+ <artifactId>mockito-all</artifactId>
61+ <version>1.10.8</version>
62+ <scope>test</scope>
63+ </dependency>
64+
5865 <dependency>
5966 <groupId>org.ow2.asm</groupId>
6067 <artifactId>asm-all</artifactId>
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationChecks.java +29 −46
@@ -20,13 +20,7 @@
2020 import java.lang.reflect.Field;
2121 import java.util.*;
2222
23-import com.google.common.primitives.Primitives;
24-
2523 import com.datastax.driver.mapping.annotations.*;
26-import com.google.common.collect.ImmutableSet;
27-import com.google.common.collect.ImmutableSet.Builder;
28-
29-import com.datastax.driver.core.DataType;
3024
3125 /**
3226 * Various checks on mapping annotations.
@@ -36,22 +30,6 @@
3630 // The package containing the mapping annotations
3731 private static final Package MAPPING_PACKAGE = Table.class.getPackage();
3832
39- // The Java types that should not be annotated with @Frozen. Any other type is supposed
40- // to map to a UDT or tuple.
41- private static final Set<Class<?>> EXPECTED_NON_FROZEN_CLASSES;
42- static {
43- Builder<Class<?>> builder = ImmutableSet.<Class<?>>builder();
44- for (DataType type : DataType.allPrimitiveTypes()) {
45- builder.add(type.asJavaClass());
46- builder.add(Primitives.unwrap(type.asJavaClass()));
47- }
48- builder.add(List.class);
49- builder.add(Set.class);
50- builder.add(Map.class);
51-
52- EXPECTED_NON_FROZEN_CLASSES = builder.build();
53- }
54-
5533 /**
5634 * Checks that a class is decorated with the given annotation, and return the annotation instance.
5735 * Also validates that no other mapping annotation is present.
@@ -118,35 +96,39 @@
11896
11997 static void checkFrozenTypes(Field field) {
12098 Type javaType = field.getGenericType();
121- CQLType cqlType = getCQLType(field);
122- checkFrozenTypes(javaType, cqlType);
99+ DeclaredFrozenType declaredFrozenType = getDeclaredFrozenType(field);
100+ checkFrozenTypes(javaType, declaredFrozenType);
123101 }
124102
125- // Builds a CQLType hierarchy based on the @Frozen* annotations on a field.
126- private static CQLType getCQLType(Field field) {
103+ // Builds a DeclaredFrozenType hierarchy based on the @Frozen* annotations on a field.
104+ private static DeclaredFrozenType getDeclaredFrozenType(Field field) {
127105 Frozen frozen = field.getAnnotation(Frozen.class);
128106 if (frozen != null)
129- return CQLType.parse(frozen.value());
107+ return DeclaredFrozenType.parse(frozen.value());
130108
131109 boolean frozenKey = field.getAnnotation(FrozenKey.class) != null;
132110 boolean frozenValue = field.getAnnotation(FrozenValue.class) != null;
133111 if (frozenKey && frozenValue)
134- return CQLType.FROZEN_MAP_KEY_AND_VALUE;
112+ return DeclaredFrozenType.FROZEN_MAP_KEY_AND_VALUE;
135113 else if (frozenKey)
136- return CQLType.FROZEN_MAP_KEY;
114+ return DeclaredFrozenType.FROZEN_MAP_KEY;
137115 else if (frozenValue && field.getType().equals(Map.class))
138- return CQLType.FROZEN_MAP_VALUE;
116+ return DeclaredFrozenType.FROZEN_MAP_VALUE;
139117 else if (frozenValue)
140- return CQLType.FROZEN_ELEMENT;
118+ return DeclaredFrozenType.FROZEN_ELEMENT;
141119 else
142- return CQLType.UNFROZEN_SIMPLE;
120+ return DeclaredFrozenType.UNFROZEN_SIMPLE;
143121 }
144122
145123 // Traverses the Java type and CQLType hierarchies in parallel, to ensure that all
146- // Java types mapping to UDTs and tuples are marked as frozen in the CQLType.
124+ // Java types mapping to UDTs, tuples and nested collections are marked as frozen in the CQLType.
147125 // We accept that parts of the CQLType be null, in which case the matching parts
148126 // in the Java type will be considered as not frozen.
149- private static void checkFrozenTypes(Type javaType, CQLType cqlType) {
127+ private static void checkFrozenTypes(Type javaType, DeclaredFrozenType declaredFrozenType) {
128+ checkFrozenTypes(javaType, declaredFrozenType, true);
129+ }
130+
131+ private static void checkFrozenTypes(Type javaType, DeclaredFrozenType declaredFrozenType, boolean isRoot) {
150132 Class<?> javaClass;
151133 Type[] childrenJavaTypes;
152134 if (javaType instanceof Class<?>) {
@@ -159,26 +141,27 @@
159141 } else
160142 throw new IllegalArgumentException("unexpected type: " + javaType);
161143
162- boolean frozen = (cqlType != null && cqlType.frozen);
163- checkValidFrozen(javaClass, frozen);
144+ boolean frozen = (declaredFrozenType != null && declaredFrozenType.frozen);
145+ checkValidFrozen(javaClass, isRoot, frozen);
164146
165147 if (childrenJavaTypes != null) {
166148 for (int i = 0; i < childrenJavaTypes.length; i++) {
167149 Type childJavaType = childrenJavaTypes[i];
168- CQLType childCQLType = null;
169- if (cqlType != null && cqlType.subTypes != null && cqlType.subTypes.size() > i)
170- childCQLType = cqlType.subTypes.get(i);
171- checkFrozenTypes(childJavaType, childCQLType);
150+ DeclaredFrozenType childDeclaredFrozenType = null;
151+ if (declaredFrozenType != null && declaredFrozenType.subTypes != null && declaredFrozenType.subTypes.size() > i)
152+ childDeclaredFrozenType = declaredFrozenType.subTypes.get(i);
153+ checkFrozenTypes(childJavaType, childDeclaredFrozenType, false);
172154 }
173155 }
174156 }
175157
176- private static void checkValidFrozen(Class<?> clazz, boolean declared) {
177- boolean expected = !EXPECTED_NON_FROZEN_CLASSES.contains(clazz) && !clazz.isEnum();
178- if (expected != declared)
158+ private static void checkValidFrozen(Class<?> clazz, boolean isRoot, boolean isDeclaredFrozen) {
159+ boolean shouldBeFrozen = (TypeMappings.mapsToCollection(clazz) && !isRoot)
160+ || TypeMappings.mapsToUserTypeOrTuple(clazz);
161+ if (shouldBeFrozen != isDeclaredFrozen)
179162 throw new IllegalArgumentException(String.format("expected %s to be %sfrozen but was %sfrozen",
180- clazz.getSimpleName(),
181- expected ? "" : "not ",
182- declared ? "" : "not "));
163+ clazz.getSimpleName(),
164+ shouldBeFrozen ? "" : "not ",
165+ isDeclaredFrozen ? "" : "not "));
183166 }
184167 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +15 −35
@@ -16,26 +16,21 @@
1616 package com.datastax.driver.mapping;
1717
1818 import java.lang.annotation.Annotation;
19-import java.lang.reflect.*;
2019 import java.lang.reflect.Field;
21-import java.util.*;
22-
23-import com.google.common.collect.ImmutableSet.Builder;
24-import com.google.common.collect.ImmutableSet;
20+import java.lang.reflect.*;
21+import java.util.ArrayList;
22+import java.util.Collections;
23+import java.util.Comparator;
24+import java.util.List;
2525
26-import com.datastax.driver.mapping.annotations.Frozen;
26+import com.google.common.base.Strings;
2727
2828 import com.datastax.driver.core.ConsistencyLevel;
29-import com.datastax.driver.core.DataType;
30-
29+import com.datastax.driver.mapping.MethodMapper.EnumParamMapper;
30+import com.datastax.driver.mapping.MethodMapper.NestedUDTParamMapper;
3131 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
32-import com.datastax.driver.mapping.MethodMapper.UDTListParamMapper;
33-import com.datastax.driver.mapping.MethodMapper.UDTMapParamMapper;
3432 import com.datastax.driver.mapping.MethodMapper.UDTParamMapper;
35-import com.datastax.driver.mapping.MethodMapper.UDTSetParamMapper;
36-import com.datastax.driver.mapping.MethodMapper.EnumParamMapper;
3733 import com.datastax.driver.mapping.annotations.*;
38-import com.google.common.base.Strings;
3934
4035 /**
4136 * Static metods that facilitates parsing class annotations into the corresponding {@link EntityMapper}.
@@ -291,29 +286,14 @@
291286 }
292287 return new ParamMapper(paramName, idx);
293288 } if (paramType instanceof ParameterizedType) {
294- ParameterizedType pt = (ParameterizedType) paramType;
295- Type raw = pt.getRawType();
296- if (!(raw instanceof Class))
297- throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName));
298- Class<?> klass = (Class<?>)raw;
299- Class<?> firstTypeParam = ReflectionUtils.getParam(pt, 0, paramName);
300- if (List.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) {
301- UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam);
302- return new UDTListParamMapper(paramName, idx, valueMapper);
303- }
304- if (Set.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) {
305- UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam);
306- return new UDTSetParamMapper(paramName, idx, valueMapper);
289+ InferredCQLType inferredCQLType = InferredCQLType.from(className, methodName, idx, paramName, paramType, mappingManager);
290+ if (inferredCQLType.containsMappedUDT) {
291+ // We need a specialized mapper to convert UDT instances in the hierarchy.
292+ return new NestedUDTParamMapper(paramName, idx, inferredCQLType);
293+ } else {
294+ // Use the default mapper but provide the extracted type
295+ return new ParamMapper(paramName, idx, inferredCQLType.dataType);
307296 }
308- if (Map.class.isAssignableFrom(klass)) {
309- Class<?> secondTypeParam = ReflectionUtils.getParam(pt, 1, paramName);
310- UDTMapper<?> keyMapper = firstTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(firstTypeParam) : null;
311- UDTMapper<?> valueMapper = secondTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(secondTypeParam) : null;
312- if (keyMapper != null || valueMapper != null) {
313- return new UDTMapParamMapper(paramName, idx, keyMapper, valueMapper);
314- }
315- }
316- return new ParamMapper(paramName, idx);
317297 } else {
318298 throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName));
319299 }
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/CQLType.java +0 −167
@@ -1,167 +0,0 @@
1-package com.datastax.driver.mapping;
2-
3-import java.util.ArrayList;
4-import java.util.List;
5-
6-import com.datastax.driver.mapping.annotations.Frozen;
7-import com.google.common.base.Strings;
8-
9-/** A CQL type definition parsed from {@link Frozen#value()}, for example map<text,map<text,frozen<user>>> */
10-class CQLType {
11- String name;
12- boolean frozen;
13- List<CQLType> subTypes;
14-
15- private CQLType(String name) {
16- this(name, false);
17- }
18-
19- private CQLType(String name, boolean frozen, CQLType... subTypes) {
20- this.name = name;
21- this.frozen = frozen;
22- for (CQLType subType : subTypes) {
23- if (this.subTypes == null)
24- this.subTypes = new ArrayList<CQLType>();
25- this.subTypes.add(subType);
26- }
27- }
28-
29- // Some constant types for the simple cases. Note that we can afford generic names because currently we don't include the name in our
30- // checks.
31- static final CQLType FROZEN_SIMPLE = new CQLType("root", true);
32- static final CQLType FROZEN_ELEMENT = new CQLType("collection", false,
33- new CQLType("element", true));
34- static final CQLType FROZEN_MAP_KEY = new CQLType("map", false,
35- new CQLType("key", true));
36- static final CQLType FROZEN_MAP_VALUE = new CQLType("map", false,
37- new CQLType("key", false),
38- new CQLType("value", true));
39- static final CQLType FROZEN_MAP_KEY_AND_VALUE = new CQLType("map", false,
40- new CQLType("key", true),
41- new CQLType("value", true));
42- static final CQLType UNFROZEN_SIMPLE = new CQLType("root");
43-
44- static CQLType parse(String toParse) {
45- if (Strings.isNullOrEmpty(toParse))
46- // we allow that as a shorthand
47- return FROZEN_SIMPLE;
48- else
49- return new Parser(toParse).parse();
50- }
51-
52- private static class Parser {
53- private final String toParse;
54- private int idx;
55-
56- Parser(String toParse) {
57- this.toParse = toParse;
58- }
59-
60- CQLType parse() {
61- skipSpaces();
62-
63- if (toParse.charAt(idx) == '"') {
64- // quoted identifier: just return everything up to the next quote
65- int endQuote = idx + 1;
66- while (endQuote < toParse.length() && toParse.charAt(endQuote) != '"')
67- endQuote += 1;
68- if (endQuote == toParse.length())
69- throw fail("could not find matching quote");
70- if (endQuote == idx + 1)
71- throw fail("empty quoted identifier");
72-
73- String name = toParse.substring(idx + 1, endQuote);
74- idx = endQuote + 1;
75- // a quoted identifier cannot be parameterized, so we can return immediately
76- return new CQLType(name);
77- } else {
78- // unquoted identifier: could be "simpleType", "complexType<subType1, subType2...>" or "frozen<type>"
79- int n = skipWord();
80- String nextWord = toParse.substring(idx, n).toLowerCase();
81- idx = n;
82- if ("frozen".equals(nextWord)) {
83- skipSpaces();
84- if (idx >= toParse.length() || toParse.charAt(idx) != '<')
85- throw fail("expected '<'");
86- idx += 1;
87- CQLType type = parse();
88- skipSpaces();
89- if (idx >= toParse.length() || toParse.charAt(idx) != '>')
90- throw fail("expected '>'");
91- idx += 1;
92- type.frozen = true;
93- return type;
94- } else {
95- CQLType type = new CQLType(nextWord);
96- skipSpaces();
97- if (idx < toParse.length() && toParse.charAt(idx) == '<') {
98- idx += 1;
99- type.subTypes = new ArrayList<CQLType>();
100- while (idx < toParse.length()) {
101- type.subTypes.add(parse());
102- skipSpaces();
103- if (idx >= toParse.length())
104- fail("unterminated list of subtypes");
105- else if (toParse.charAt(idx) == '>') {
106- idx += 1;
107- break;
108- }
109- else if (toParse.charAt(idx) != ',')
110- fail("expected ','");
111- else
112- idx += 1;
113- }
114- }
115- return type;
116- }
117- }
118- }
119-
120- private void skipSpaces() {
121- while (idx < toParse.length() && isBlank(idx))
122- idx += 1;
123- }
124-
125- private int skipWord() {
126- if (idx >= toParse.length())
127- throw fail("expected type name");
128-
129- if (!isIdentStart(idx))
130- throw fail("illegal character at start of type name");
131-
132- int i = idx;
133- while (i < toParse.length() && isIdentBody(i))
134- i += 1;
135-
136- return i;
137- }
138-
139- private boolean isBlank(int i) {
140- char c = toParse.charAt(i);
141- return c == ' ' || c == '\t' || c == '\n';
142- }
143-
144- private boolean isIdentStart(int i) {
145- char c = toParse.charAt(i);
146- return isLetter(c);
147- }
148-
149- private boolean isIdentBody(int i) {
150- char c = toParse.charAt(i);
151- return isLetter(c) || isDigit(c) || c == '_';
152- }
153-
154- private boolean isLetter(char c) {
155- return (c >= 'a' && c <= 'z') ||
156- (c >= 'A' && c <= 'Z');
157- }
158-
159- private boolean isDigit(char c) {
160- return (c >= '0' && c <= '9');
161- }
162-
163- private IllegalArgumentException fail(String cause) {
164- return new IllegalArgumentException(cause + " (" + toParse + " [" + idx + "])");
165- }
166- }
167-}
added driver-mapping/src/main/java/com/datastax/driver/mapping/DeclaredFrozenType.java +170 −0
@@ -0,0 +1,170 @@
1+package com.datastax.driver.mapping;
2+
3+import java.util.ArrayList;
4+import java.util.List;
5+
6+import com.datastax.driver.mapping.annotations.Frozen;
7+import com.google.common.base.Strings;
8+
9+/**
10+ * A tree-like structure parsed from {@code Frozen*} annotations, that indicates which
11+ * types in the hierarchy were declared frozen.
12+ */
13+class DeclaredFrozenType {
14+ String name;
15+ boolean frozen;
16+ List<DeclaredFrozenType> subTypes;
17+
18+ private DeclaredFrozenType(String name) {
19+ this(name, false);
20+ }
21+
22+ private DeclaredFrozenType(String name, boolean frozen, DeclaredFrozenType... subTypes) {
23+ this.name = name;
24+ this.frozen = frozen;
25+ for (DeclaredFrozenType subType : subTypes) {
26+ if (this.subTypes == null)
27+ this.subTypes = new ArrayList<DeclaredFrozenType>();
28+ this.subTypes.add(subType);
29+ }
30+ }
31+
32+ // Some constant types for the simple cases. Note that we can afford generic names because currently we don't include the name in our
33+ // checks.
34+ static final DeclaredFrozenType FROZEN_SIMPLE = new DeclaredFrozenType("root", true);
35+ static final DeclaredFrozenType FROZEN_ELEMENT = new DeclaredFrozenType("collection", false,
36+ new DeclaredFrozenType("element", true));
37+ static final DeclaredFrozenType FROZEN_MAP_KEY = new DeclaredFrozenType("map", false,
38+ new DeclaredFrozenType("key", true));
39+ static final DeclaredFrozenType FROZEN_MAP_VALUE = new DeclaredFrozenType("map", false,
40+ new DeclaredFrozenType("key", false),
41+ new DeclaredFrozenType("value", true));
42+ static final DeclaredFrozenType FROZEN_MAP_KEY_AND_VALUE = new DeclaredFrozenType("map", false,
43+ new DeclaredFrozenType("key", true),
44+ new DeclaredFrozenType("value", true));
45+ static final DeclaredFrozenType UNFROZEN_SIMPLE = new DeclaredFrozenType("root");
46+
47+ static DeclaredFrozenType parse(String toParse) {
48+ if (Strings.isNullOrEmpty(toParse))
49+ // we allow that as a shorthand
50+ return FROZEN_SIMPLE;
51+ else
52+ return new Parser(toParse).parse();
53+ }
54+
55+ private static class Parser {
56+ private final String toParse;
57+ private int idx;
58+
59+ Parser(String toParse) {
60+ this.toParse = toParse;
61+ }
62+
63+ DeclaredFrozenType parse() {
64+ skipSpaces();
65+
66+ if (toParse.charAt(idx) == '"') {
67+ // quoted identifier: just return everything up to the next quote
68+ int endQuote = idx + 1;
69+ while (endQuote < toParse.length() && toParse.charAt(endQuote) != '"')
70+ endQuote += 1;
71+ if (endQuote == toParse.length())
72+ throw fail("could not find matching quote");
73+ if (endQuote == idx + 1)
74+ throw fail("empty quoted identifier");
75+
76+ String name = toParse.substring(idx + 1, endQuote);
77+ idx = endQuote + 1;
78+ // a quoted identifier cannot be parameterized, so we can return immediately
79+ return new DeclaredFrozenType(name);
80+ } else {
81+ // unquoted identifier: could be "simpleType", "complexType<subType1, subType2...>" or "frozen<type>"
82+ int n = skipWord();
83+ String nextWord = toParse.substring(idx, n).toLowerCase();
84+ idx = n;
85+ if ("frozen".equals(nextWord)) {
86+ skipSpaces();
87+ if (idx >= toParse.length() || toParse.charAt(idx) != '<')
88+ throw fail("expected '<'");
89+ idx += 1;
90+ DeclaredFrozenType type = parse();
91+ skipSpaces();
92+ if (idx >= toParse.length() || toParse.charAt(idx) != '>')
93+ throw fail("expected '>'");
94+ idx += 1;
95+ type.frozen = true;
96+ return type;
97+ } else {
98+ DeclaredFrozenType type = new DeclaredFrozenType(nextWord);
99+ skipSpaces();
100+ if (idx < toParse.length() && toParse.charAt(idx) == '<') {
101+ idx += 1;
102+ type.subTypes = new ArrayList<DeclaredFrozenType>();
103+ while (idx < toParse.length()) {
104+ type.subTypes.add(parse());
105+ skipSpaces();
106+ if (idx >= toParse.length())
107+ fail("unterminated list of subtypes");
108+ else if (toParse.charAt(idx) == '>') {
109+ idx += 1;
110+ break;
111+ }
112+ else if (toParse.charAt(idx) != ',')
113+ fail("expected ','");
114+ else
115+ idx += 1;
116+ }
117+ }
118+ return type;
119+ }
120+ }
121+ }
122+
123+ private void skipSpaces() {
124+ while (idx < toParse.length() && isBlank(idx))
125+ idx += 1;
126+ }
127+
128+ private int skipWord() {
129+ if (idx >= toParse.length())
130+ throw fail("expected type name");
131+
132+ if (!isIdentStart(idx))
133+ throw fail("illegal character at start of type name");
134+
135+ int i = idx;
136+ while (i < toParse.length() && isIdentBody(i))
137+ i += 1;
138+
139+ return i;
140+ }
141+
142+ private boolean isBlank(int i) {
143+ char c = toParse.charAt(i);
144+ return c == ' ' || c == '\t' || c == '\n';
145+ }
146+
147+ private boolean isIdentStart(int i) {
148+ char c = toParse.charAt(i);
149+ return isLetter(c);
150+ }
151+
152+ private boolean isIdentBody(int i) {
153+ char c = toParse.charAt(i);
154+ return isLetter(c) || isDigit(c) || c == '_';
155+ }
156+
157+ private boolean isLetter(char c) {
158+ return (c >= 'a' && c <= 'z') ||
159+ (c >= 'A' && c <= 'Z');
160+ }
161+
162+ private boolean isDigit(char c) {
163+ return (c >= '0' && c <= '9');
164+ }
165+
166+ private IllegalArgumentException fail(String cause) {
167+ return new IllegalArgumentException(cause + " (" + toParse + " [" + idx + "])");
168+ }
169+ }
170+}
added driver-mapping/src/main/java/com/datastax/driver/mapping/InferredCQLType.java +101 −0
@@ -0,0 +1,101 @@
1+/*
2+ * Copyright (C) 2012-2014 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.mapping;
17+
18+import java.lang.reflect.Field;
19+import java.lang.reflect.ParameterizedType;
20+import java.lang.reflect.Type;
21+import java.util.Collections;
22+import java.util.List;
23+
24+import com.google.common.collect.Lists;
25+
26+import com.datastax.driver.core.DataType;
27+
28+/**
29+ * Describes the CQL type inferred from a generic Java field (which will always map
30+ * to a collection, possibly with various levels of nesting).
31+ *
32+ * The reason we wrap {@code DataType} is because we also want to remember if there are mapped UDT
33+ * types somewhere in the hierarchy.
34+ */
35+class InferredCQLType {
36+ final DataType dataType;
37+ final boolean containsMappedUDT;
38+ final UDTMapper udtMapper;
39+ final List<InferredCQLType> childTypes;
40+
41+ static InferredCQLType from(Field field, MappingManager mappingManager) {
42+ String name = String.format("field %s of class %s", field.getName(), field.getDeclaringClass().getName());
43+ return new InferredCQLType(field.getGenericType(), name, field.getGenericType(), mappingManager);
44+ }
45+
46+ static InferredCQLType from(String className, String methodName, int idx, String paramName, Type paramType, MappingManager mappingManager) {
47+ String name = String.format("parameter %s of %s.%s", paramName == null ? idx : paramName, className, methodName);
48+ return new InferredCQLType(paramType, name, paramType, mappingManager);
49+ }
50+
51+ private InferredCQLType(Type javaType, String rootName, Type rootType, MappingManager mappingManager) {
52+ if (javaType instanceof ParameterizedType) {
53+ ParameterizedType pt = (ParameterizedType)javaType;
54+ Type raw = pt.getRawType();
55+ if (!(raw instanceof Class))
56+ throw fail(rootName, rootType);
57+
58+ Class<?> klass = (Class<?>)raw;
59+ if (!TypeMappings.mapsToCollection(klass))
60+ throw fail(rootName, rootType);
61+
62+ childTypes = Lists.newArrayList();
63+ boolean childrenContainMappedUDT = false;
64+ for (Type childJavaType : pt.getActualTypeArguments()) {
65+ InferredCQLType child = new InferredCQLType(childJavaType, rootName, rootType, mappingManager);
66+ childrenContainMappedUDT |= child.containsMappedUDT;
67+ childTypes.add(child);
68+ }
69+ containsMappedUDT = childrenContainMappedUDT;
70+ udtMapper = null;
71+
72+ if (TypeMappings.mapsToList(klass)) {
73+ dataType = DataType.list(childTypes.get(0).dataType);
74+ } else if (TypeMappings.mapsToSet(klass)) {
75+ dataType = DataType.set(childTypes.get(0).dataType);
76+ } else if (TypeMappings.mapsToMap(klass)) {
77+ dataType = DataType.map(childTypes.get(0).dataType, childTypes.get(1).dataType);
78+ } else
79+ throw fail(rootName, rootType);
80+ } else if (javaType instanceof Class) {
81+ Class<?> klass = (Class<?>)javaType;
82+ if (TypeMappings.isMappedUDT(klass)) {
83+ containsMappedUDT = true;
84+ udtMapper = mappingManager.udtMapper(klass);
85+ dataType = udtMapper.getUserType();
86+ childTypes = Collections.emptyList();
87+ } else {
88+ containsMappedUDT = false;
89+ udtMapper = null;
90+ dataType = TypeMappings.getSimpleType(klass, rootName);
91+ childTypes = Collections.emptyList();
92+ }
93+ } else {
94+ throw fail(rootName, rootType);
95+ }
96+ }
97+
98+ private IllegalArgumentException fail(String rootName, Type rootType) {
99+ return new IllegalArgumentException(String.format("Cannot map class %s for %s", rootType, rootName));
100+ }
101+}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +23 −47
@@ -18,9 +18,7 @@
1818 import java.lang.reflect.Method;
1919 import java.lang.reflect.ParameterizedType;
2020 import java.lang.reflect.Type;
21-import java.util.List;
22-import java.util.Map;
23-import java.util.Set;
21+import java.nio.ByteBuffer;
2422
2523 import com.google.common.util.concurrent.Futures;
2624 import com.google.common.util.concurrent.ListenableFuture;
@@ -160,23 +158,32 @@
160158 // We'll only set one of the other. If paramName is null, then paramIdx is used.
161159 private final String paramName;
162160 private final int paramIdx;
161+ private final DataType dataType;
163162
164- public ParamMapper(String paramName, int paramIdx) {
163+ public ParamMapper(String paramName, int paramIdx, DataType dataType) {
165164 this.paramName = paramName;
166165 this.paramIdx = paramIdx;
166+ this.dataType = dataType;
167+ }
168+
169+ public ParamMapper(String paramName, int paramIdx) {
170+ this(paramName, paramIdx, null);
167171 }
168172
169173 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
174+ ByteBuffer serializedArg = (dataType == null)
175+ ? DataType.serializeValue(arg, protocolVersion)
176+ : dataType.serialize(arg, protocolVersion);
170177 if (paramName == null) {
171178 if (arg == null)
172179 boundStatement.setToNull(paramIdx);
173180 else
174- boundStatement.setBytesUnsafe(paramIdx, DataType.serializeValue(arg, protocolVersion));
181+ boundStatement.setBytesUnsafe(paramIdx, serializedArg);
175182 } else {
176183 if (arg == null)
177184 boundStatement.setToNull(paramName);
178185 else
179- boundStatement.setBytesUnsafe(paramName, DataType.serializeValue(arg, protocolVersion));
186+ boundStatement.setBytesUnsafe(paramName, serializedArg);
180187 }
181188 }
182189 }
@@ -198,53 +205,22 @@
198205 }
199206 }
200207
201- static class UDTListParamMapper<V> extends ParamMapper {
202- private final UDTMapper<V> valueMapper;
203-
204- UDTListParamMapper(String paramName, int paramIdx, UDTMapper<V> valueMapper) {
205- super(paramName, paramIdx);
206- this.valueMapper = valueMapper;
207- }
208-
209- @Override
210- void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
211- @SuppressWarnings("unchecked")
212- List<V> entities = (List<V>) arg;
213- super.setValue(boundStatement, valueMapper.toUDTValues(entities), protocolVersion);
214- }
215- }
216-
217- static class UDTSetParamMapper<V> extends ParamMapper {
218- private final UDTMapper<V> valueMapper;
219-
220- UDTSetParamMapper(String paramName, int paramIdx, UDTMapper<V> valueMapper) {
221- super(paramName, paramIdx);
222- this.valueMapper = valueMapper;
223- }
224-
225- @Override
226- void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
227- @SuppressWarnings("unchecked")
228- Set<V> entities = (Set<V>) arg;
229- super.setValue(boundStatement, valueMapper.toUDTValues(entities), protocolVersion);
230- }
231- }
232-
233- static class UDTMapParamMapper<K, V> extends ParamMapper {
234- private final UDTMapper<K> keyMapper;
235- private final UDTMapper<V> valueMapper;
208+ /**
209+ * Maps a nested collection which has a mapped UDT somewhere in the hierarchy.
210+ */
211+ static class NestedUDTParamMapper extends ParamMapper {
212+ private final InferredCQLType inferredCQLType;
236213
237- UDTMapParamMapper(String paramName, int paramIdx, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper) {
214+ NestedUDTParamMapper(String paramName, int paramIdx, InferredCQLType inferredCQLType) {
238215 super(paramName, paramIdx);
239- this.keyMapper = keyMapper;
240- this.valueMapper = valueMapper;
216+ this.inferredCQLType = inferredCQLType;
241217 }
242218
243219 @Override
244220 void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
245- @SuppressWarnings("unchecked")
246- Map<K, V> entities = (Map<K, V>) arg;
247- super.setValue(boundStatement, UDTMapper.toUDTValues(entities, keyMapper, valueMapper), protocolVersion);
221+ super.setValue(boundStatement,
222+ UDTMapper.convertEntitiesToUDTs(arg, inferredCQLType),
223+ protocolVersion);
248224 }
249225 }
250226
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +22 −167
@@ -21,16 +21,10 @@
2121 import java.lang.reflect.ParameterizedType;
2222 import java.lang.reflect.Type;
2323 import java.lang.reflect.Method;
24-import java.net.InetAddress;
25-import java.nio.ByteBuffer;
26-import java.math.BigInteger;
27-import java.math.BigDecimal;
2824 import java.util.*;
2925
3026 import com.datastax.driver.core.*;
3127
32-import com.datastax.driver.mapping.annotations.UDT;
33-
3428 /**
3529 * An {@link EntityMapper} implementation that use reflection to read and write fields
3630 * of an entity.
@@ -62,7 +56,7 @@
6256 private final Method writeMethod;
6357
6458 private LiteralMapper(Field field, int position, PropertyDescriptor pd) {
65- this(field, extractType(field), position, pd);
59+ this(field, extractSimpleType(field), position, pd);
6660 }
6761
6862 private LiteralMapper(Field field, DataType type, int position, PropertyDescriptor pd) {
@@ -166,159 +160,36 @@
166160 }
167161 }
168162
169- private static class UDTListMapper<T, V> extends LiteralMapper<T> {
170-
171- private final UDTMapper<V> valueMapper;
172-
173- UDTListMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<V> valueMapper) {
174- super(field, DataType.list(valueMapper.getUserType()), position, pd);
175- this.valueMapper = valueMapper;
176- }
177-
178- @Override
179- public Object getValue(T entity) {
180- @SuppressWarnings("unchecked")
181- List<V> entities = (List<V>) super.getValue(entity);
182- return valueMapper.toUDTValues(entities);
183- }
184-
185- @Override
186- public void setValue(Object entity, Object value) {
187- @SuppressWarnings("unchecked")
188- List<UDTValue> udtValues = (List<UDTValue>) value;
189- super.setValue(entity, valueMapper.toEntities(udtValues));
190- }
191- }
192-
193- private static class UDTSetMapper<T, V> extends LiteralMapper<T> {
194-
195- private final UDTMapper<V> valueMapper;
196-
197- UDTSetMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<V> valueMapper) {
198- super(field, DataType.set(valueMapper.getUserType()), position, pd);
199- this.valueMapper = valueMapper;
200- }
201-
202- @Override
203- public Object getValue(T entity) {
204- @SuppressWarnings("unchecked")
205- Set<V> entities = (Set<V>) super.getValue(entity);
206- return valueMapper.toUDTValues(entities);
207- }
208-
209- @Override
210- public void setValue(Object entity, Object value) {
211- @SuppressWarnings("unchecked")
212- Set<UDTValue> udtValues = (Set<UDTValue>) value;
213- super.setValue(entity, valueMapper.toEntities(udtValues));
214- }
215- }
163+ private static class NestedUDTMapper<T> extends LiteralMapper<T> {
164+ private final InferredCQLType inferredCQLType;
216165
217- /**
218- * A map field that contains UDT values.
219- * <p>
220- * UDTs may be used either as keys, or as values, or both. This is reflected
221- * in keyMapper and valueMapper being null or non-null.
222- * </p>
223- */
224- private static class UDTMapMapper<T, K, V> extends LiteralMapper<T> {
225- private final UDTMapper<K> keyMapper;
226- private final UDTMapper<V> valueMapper;
227-
228- UDTMapMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper, Class<?> keyClass, Class<?> valueClass) {
229- super(field, buildDataType(field, keyMapper, valueMapper, keyClass, valueClass), position, pd);
230- this.keyMapper = keyMapper;
231- this.valueMapper = valueMapper;
166+ public NestedUDTMapper(Field field, int position, PropertyDescriptor pd, InferredCQLType inferredCQLType) {
167+ super(field, inferredCQLType.dataType, position, pd);
168+ this.inferredCQLType = inferredCQLType;
232169 }
233170
234171 @Override
172+ @SuppressWarnings("unchecked")
235173 public Object getValue(T entity) {
236- @SuppressWarnings("unchecked")
237- Map<K, V> entities = (Map<K, V>) super.getValue(entity);
238- return UDTMapper.toUDTValues(entities, keyMapper, valueMapper);
174+ Object valueWithEntities = super.getValue(entity);
175+ return (T)UDTMapper.convertEntitiesToUDTs(valueWithEntities, inferredCQLType);
239176 }
240177
241178 @Override
242- @SuppressWarnings("unchecked")
243- public void setValue(Object entity, Object fieldValue) {
244- Map<Object, Object> udtValues = (Map<Object, Object>) fieldValue;
245- super.setValue(entity, UDTMapper.toEntities(udtValues, keyMapper, valueMapper));
246- }
247-
248- private static <K, V> DataType buildDataType(Field field, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper, Class<?> keyClass, Class<?> valueClass) {
249- assert keyMapper != null || valueMapper != null;
250-
251- DataType keyType = (keyMapper != null) ?
252- keyMapper.getUserType() :
253- getSimpleType(keyClass, field);
254- DataType valueType = (valueMapper != null) ?
255- valueMapper.getUserType() :
256- getSimpleType(valueClass, field);
257- return DataType.map(keyType, valueType);
179+ public void setValue(Object entity, Object valueWithUDTValues) {
180+ super.setValue(entity, UDTMapper.convertUDTsToEntities(valueWithUDTValues, inferredCQLType));
258181 }
259182 }
260183
261- static DataType extractType(Field f) {
184+ static DataType extractSimpleType(Field f) {
262185 Type type = f.getGenericType();
263186
264- if (type instanceof ParameterizedType) {
265- ParameterizedType pt = (ParameterizedType)type;
266- Type raw = pt.getRawType();
267- if (!(raw instanceof Class))
268- throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName()));
269-
270- Class<?> klass = (Class<?>)raw;
271- if (List.class.isAssignableFrom(klass)) {
272- return DataType.list(getSimpleType(ReflectionUtils.getParam(pt, 0, f.getName()), f));
273- }
274- if (Set.class.isAssignableFrom(klass)) {
275- return DataType.set(getSimpleType(ReflectionUtils.getParam(pt, 0, f.getName()), f));
276- }
277- if (Map.class.isAssignableFrom(klass)) {
278- return DataType.map(getSimpleType(ReflectionUtils.getParam(pt, 0, f.getName()), f), getSimpleType(ReflectionUtils.getParam(pt, 1, f.getName()), f));
279- }
280- throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName()));
281- }
187+ assert !(type instanceof ParameterizedType);
282188
283189 if (!(type instanceof Class))
284190 throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName()));
285191
286- return getSimpleType((Class<?>)type, f);
287- }
288-
289- static DataType getSimpleType(Class<?> klass, Field f) {
290- if (ByteBuffer.class.isAssignableFrom(klass))
291- return DataType.blob();
292-
293- if (klass == int.class || Integer.class.isAssignableFrom(klass))
294- return DataType.cint();
295- if (klass == long.class || Long.class.isAssignableFrom(klass))
296- return DataType.bigint();
297- if (klass == float.class || Float.class.isAssignableFrom(klass))
298- return DataType.cfloat();
299- if (klass == double.class || Double.class.isAssignableFrom(klass))
300- return DataType.cdouble();
301- if (klass == boolean.class || Boolean.class.isAssignableFrom(klass))
302- return DataType.cboolean();
303-
304- if (BigDecimal.class.isAssignableFrom(klass))
305- return DataType.decimal();
306- if (BigInteger.class.isAssignableFrom(klass))
307- return DataType.varint();
308-
309- if (String.class.isAssignableFrom(klass))
310- return DataType.text();
311- if (InetAddress.class.isAssignableFrom(klass))
312- return DataType.inet();
313- if (Date.class.isAssignableFrom(klass))
314- return DataType.timestamp();
315- if (UUID.class.isAssignableFrom(klass))
316- return DataType.uuid();
317-
318- if (Collection.class.isAssignableFrom(klass))
319- throw new IllegalArgumentException(String.format("Cannot map non-parametrized collection type %s for field %s; Please use a concrete type parameter", klass.getName(), f.getName()));
320-
321- throw new IllegalArgumentException(String.format("Cannot map unknown class %s for field %s", klass.getName(), f));
192+ return TypeMappings.getSimpleType((Class<?>)type, f.getName());
322193 }
323194
324195 private static class ReflectionFactory implements Factory {
@@ -337,35 +208,19 @@
337208 return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field));
338209 }
339210
340- if (field.getType().isAnnotationPresent(UDT.class)) {
211+ if (TypeMappings.isMappedUDT(field.getType())) {
341212 UDTMapper<?> udtMapper = mappingManager.getUDTMapper(field.getType());
342213 return (ColumnMapper<T>) new UDTColumnMapper(field, position, pd, udtMapper);
343214 }
344215
345216 if (field.getGenericType() instanceof ParameterizedType) {
346- ParameterizedType pt = (ParameterizedType) field.getGenericType();
347- Type raw = pt.getRawType();
348- if (!(raw instanceof Class))
349- throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", field, field.getName()));
350-
351- Class<?> klass = (Class<?>)raw;
352- Class<?> firstTypeParam = ReflectionUtils.getParam(pt, 0, field.getName());
353- if (List.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) {
354- UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam);
355- return (ColumnMapper<T>) new UDTListMapper(field, position, pd, valueMapper);
356- }
357- if (Set.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) {
358- UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam);
359- return (ColumnMapper<T>) new UDTSetMapper(field, position, pd, valueMapper);
360- }
361- if (Map.class.isAssignableFrom(klass)) {
362- Class<?> secondTypeParam = ReflectionUtils.getParam(pt, 1, field.getName());
363- UDTMapper<?> keyMapper = firstTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(firstTypeParam) : null;
364- UDTMapper<?> valueMapper = secondTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(secondTypeParam) : null;
365-
366- if (keyMapper != null || valueMapper != null) {
367- return (ColumnMapper<T>) new UDTMapMapper(field, position, pd, keyMapper, valueMapper, firstTypeParam, secondTypeParam);
368- }
217+ InferredCQLType inferredCQLType = InferredCQLType.from(field, mappingManager);
218+ if (inferredCQLType.containsMappedUDT) {
219+ // We need a specialized mapper to convert UDT instances in the hierarchy.
220+ return (ColumnMapper<T>)new NestedUDTMapper(field, position, pd, inferredCQLType);
221+ } else {
222+ // The default codecs will know how to handle the extracted datatype.
223+ return new LiteralMapper<T>(field, inferredCQLType.dataType, position, pd);
369224 }
370225 }
371226
added driver-mapping/src/main/java/com/datastax/driver/mapping/TypeMappings.java +95 −0
@@ -0,0 +1,95 @@
1+/*
2+ * Copyright (C) 2012-2014 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.mapping;
17+
18+import java.lang.reflect.Field;
19+import java.math.BigDecimal;
20+import java.math.BigInteger;
21+import java.net.InetAddress;
22+import java.nio.ByteBuffer;
23+import java.util.*;
24+
25+import com.datastax.driver.core.DataType;
26+import com.datastax.driver.core.TupleValue;
27+import com.datastax.driver.core.UDTValue;
28+import com.datastax.driver.mapping.annotations.UDT;
29+
30+/**
31+ * Utility methods to determine which CQL type we expect for a given Java field type.
32+ */
33+class TypeMappings {
34+
35+ static DataType getSimpleType(Class<?> klass, String fieldName) {
36+ if (ByteBuffer.class.isAssignableFrom(klass))
37+ return DataType.blob();
38+
39+ if (klass == int.class || Integer.class.isAssignableFrom(klass))
40+ return DataType.cint();
41+ if (klass == long.class || Long.class.isAssignableFrom(klass))
42+ return DataType.bigint();
43+ if (klass == float.class || Float.class.isAssignableFrom(klass))
44+ return DataType.cfloat();
45+ if (klass == double.class || Double.class.isAssignableFrom(klass))
46+ return DataType.cdouble();
47+ if (klass == boolean.class || Boolean.class.isAssignableFrom(klass))
48+ return DataType.cboolean();
49+
50+ if (BigDecimal.class.isAssignableFrom(klass))
51+ return DataType.decimal();
52+ if (BigInteger.class.isAssignableFrom(klass))
53+ return DataType.varint();
54+
55+ if (String.class.isAssignableFrom(klass))
56+ return DataType.text();
57+ if (InetAddress.class.isAssignableFrom(klass))
58+ return DataType.inet();
59+ if (Date.class.isAssignableFrom(klass))
60+ return DataType.timestamp();
61+ if (UUID.class.isAssignableFrom(klass))
62+ return DataType.uuid();
63+
64+ if (Collection.class.isAssignableFrom(klass))
65+ throw new IllegalArgumentException(String.format("Cannot map non-parametrized collection type %s for field %s; Please use a concrete type parameter", klass.getName(), fieldName));
66+
67+ throw new IllegalArgumentException(String.format("Cannot map unknown class %s for field %s", klass.getName(), fieldName));
68+ }
69+
70+ static boolean mapsToList(Class<?> klass) {
71+ return List.class.equals(klass);
72+ }
73+
74+ static boolean mapsToSet(Class<?> klass) {
75+ return Set.class.equals(klass);
76+ }
77+
78+ static boolean mapsToMap(Class<?> klass) {
79+ return Map.class.equals(klass);
80+ }
81+
82+ static boolean mapsToCollection(Class<?> klass) {
83+ return mapsToList(klass) || mapsToSet(klass) || mapsToMap(klass);
84+ }
85+
86+ static boolean isMappedUDT(Class<?> klass) {
87+ return klass.isAnnotationPresent(UDT.class);
88+ }
89+
90+ static boolean mapsToUserTypeOrTuple(Class<?> klass) {
91+ return isMappedUDT(klass) ||
92+ klass.equals(UDTValue.class) ||
93+ klass.equals(TupleValue.class);
94+ }
95+}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/UDTMapper.java +81 −66
@@ -19,9 +19,6 @@
1919 import java.util.*;
2020 import java.util.Map.Entry;
2121
22-import com.google.common.collect.Maps;
23-import com.google.common.collect.Sets;
24-
2522 import com.datastax.driver.core.*;
2623
2724 /**
@@ -88,51 +85,6 @@
8885 return userType;
8986 }
9087
91- List<UDTValue> toUDTValues(List<T> entities) {
92- if (entities == null)
93- return null;
94-
95- List<UDTValue> udtValues = new ArrayList<UDTValue>(entities.size());
96- for (T entity : entities) {
97- UDTValue udtValue = toUDT(entity);
98- udtValues.add(udtValue);
99- }
100- return udtValues;
101- }
102-
103- Set<UDTValue> toUDTValues(Set<T> entities) {
104- if (entities == null)
105- return null;
106-
107- Set<UDTValue> udtValues = Sets.newHashSetWithExpectedSize(entities.size());
108- for (T entity : entities) {
109- UDTValue udtValue = toUDT(entity);
110- udtValues.add(udtValue);
111- }
112- return udtValues;
113- }
114-
115- /*
116- * Map conversion methods are static because they use two mappers, either of
117- * which (but not both) may be null.
118- *
119- * This reflects the fact that the map datatype can use UDTs as keys, or
120- * values, or both.
121- */
122- static <K, V> Map<Object, Object> toUDTValues(Map<K, V> entities, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper) {
123- assert keyMapper != null || valueMapper != null;
124- if (entities == null)
125- return null;
126-
127- Map<Object, Object> udtValues = Maps.newHashMapWithExpectedSize(entities.size());
128- for (Entry<K, V> entry : entities.entrySet()) {
129- Object key = (keyMapper == null) ? entry.getKey() : keyMapper.toUDT(entry.getKey());
130- Object value = (valueMapper == null) ? entry.getValue() : valueMapper.toUDT(entry.getValue());
131- udtValues.put(key, value);
132- }
133- return udtValues;
134- }
135-
13688 T toEntity(UDTValue udtValue) {
13789 T entity = entityMapper.newEntity();
13890 for (ColumnMapper<T> cm : entityMapper.allColumns()) {
@@ -143,30 +95,93 @@
14395 return entity;
14496 }
14597
146- List<T> toEntities(List<UDTValue> udtValues) {
147- List<T> entities = new ArrayList<T>(udtValues.size());
148- for (UDTValue udtValue : udtValues) {
149- entities.add(toEntity(udtValue));
98+ /**
99+ * Handles a (possibly nested) collection where some of the elements are domain classes that
100+ * must be converted to {@code UDTValue} instances.
101+ */
102+ @SuppressWarnings("unchecked")
103+ static Object convertEntitiesToUDTs(Object value, InferredCQLType type) {
104+ if (value == null)
105+ return null;
106+
107+ if (!type.containsMappedUDT)
108+ return value;
109+
110+ if (type.udtMapper != null)
111+ return type.udtMapper.toUDT(value);
112+
113+ if (type.dataType.getName() == DataType.Name.LIST) {
114+ InferredCQLType elementType = type.childTypes.get(0);
115+ List<Object> result = new ArrayList<Object>();
116+ for (Object element : (List<Object>)value)
117+ result.add(convertEntitiesToUDTs(element, elementType));
118+ return result;
119+ }
120+
121+ if (type.dataType.getName() == DataType.Name.SET) {
122+ InferredCQLType elementType = type.childTypes.get(0);
123+ Set<Object> result = new LinkedHashSet<Object>();
124+ for (Object element : (Set<Object>)value)
125+ result.add(convertEntitiesToUDTs(element, elementType));
126+ return result;
150127 }
151- return entities;
152- }
153128
154- Set<T> toEntities(Set<UDTValue> udtValues) {
155- Set<T> entities = Sets.newHashSetWithExpectedSize(udtValues.size());
156- for (UDTValue udtValue : udtValues) {
157- entities.add(toEntity(udtValue));
129+ if (type.dataType.getName() == DataType.Name.MAP) {
130+ InferredCQLType keyType = type.childTypes.get(0);
131+ InferredCQLType valueType = type.childTypes.get(1);
132+ Map<Object, Object> result = new LinkedHashMap<Object, Object>();
133+ for (Entry<Object, Object> entry : ((Map<Object, Object>)value).entrySet())
134+ result.put(
135+ convertEntitiesToUDTs(entry.getKey(), keyType),
136+ convertEntitiesToUDTs(entry.getValue(), valueType)
137+ );
138+ return result;
158139 }
159- return entities;
140+ throw new IllegalArgumentException("Error converting " + value);
160141 }
161142
143+ /**
144+ * Handles a (possibly nested) collection where some of the elements are {@code UDTValue}
145+ * instances that must be converted to domain classes.
146+ */
162147 @SuppressWarnings("unchecked")
163- static <K, V> Map<K, V> toEntities(Map<Object, Object> udtValues, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper) {
164- Map<K, V> entities = Maps.newHashMapWithExpectedSize(udtValues.size());
165- for (Entry<Object, Object> entry : udtValues.entrySet()) {
166- K key = (keyMapper == null) ? (K) entry.getKey() : keyMapper.toEntity((UDTValue) entry.getKey());
167- V value = (valueMapper == null) ? (V) entry.getValue() : valueMapper.toEntity((UDTValue)entry.getValue());
168- entities.put(key, value);
148+ static Object convertUDTsToEntities(Object value, InferredCQLType type) {
149+ if (value == null)
150+ return null;
151+
152+ if (!type.containsMappedUDT)
153+ return value;
154+
155+ if (type.udtMapper != null)
156+ return type.udtMapper.toEntity((UDTValue)value);
157+
158+ if (type.dataType.getName() == DataType.Name.LIST) {
159+ InferredCQLType elementType = type.childTypes.get(0);
160+ List<Object> result = new ArrayList<Object>();
161+ for (Object element : (List<Object>)value)
162+ result.add(convertUDTsToEntities(element, elementType));
163+ return result;
164+ }
165+
166+ if (type.dataType.getName() == DataType.Name.SET) {
167+ InferredCQLType elementType = type.childTypes.get(0);
168+ Set<Object> result = new LinkedHashSet<Object>();
169+ for (Object element : (Set<Object>)value)
170+ result.add(convertUDTsToEntities(element, elementType));
171+ return result;
172+ }
173+
174+ if (type.dataType.getName() == DataType.Name.MAP) {
175+ InferredCQLType keyType = type.childTypes.get(0);
176+ InferredCQLType valueType = type.childTypes.get(1);
177+ Map<Object, Object> result = new LinkedHashMap<Object, Object>();
178+ for (Entry<Object, Object> entry : ((Map<Object, Object>)value).entrySet())
179+ result.put(
180+ convertUDTsToEntities(entry.getKey(), keyType),
181+ convertUDTsToEntities(entry.getValue(), valueType)
182+ );
183+ return result;
169184 }
170- return entities;
185+ throw new IllegalArgumentException("Error converting " + value);
171186 }
172187 }
added driver-mapping/src/test/java/com/datastax/driver/core/CoreHooks.java +10 −0
@@ -0,0 +1,10 @@
1+package com.datastax.driver.core;
2+
3+import java.util.Collections;
4+
5+/**
6+ * Provides access to package-private members of the core module.
7+ */
8+public class CoreHooks {
9+ public static UserType MOCK_USER_TYPE = new UserType("mockKs", "mockUDT", Collections.<UserType.Field>emptyList());
10+}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/AnnotationChecksTest.java +25 −2
@@ -3,15 +3,19 @@
33 import java.lang.reflect.Field;
44 import java.util.List;
55 import java.util.Map;
6+import java.util.Set;
67
78 import com.datastax.driver.mapping.annotations.Frozen;
89 import com.datastax.driver.mapping.annotations.FrozenValue;
10+import com.datastax.driver.mapping.annotations.UDT;
11+
912 import org.testng.annotations.Test;
1013
1114 import static org.testng.Assert.fail;
1215
1316 public class AnnotationChecksTest {
1417 // Dummy UDT class:
18+ @UDT(name = "user")
1519 public class User {
1620 }
1721
@@ -27,11 +31,21 @@
2731 @FrozenValue
2832 List<User> listOfFrozenUsers;
2933 Map<String, Map<String, User>> deeplyNestedUnfrozenUser;
30- @Frozen("map<text, map<text, frozen<user>>>")
34+ @Frozen("map<text, frozen<map<text, frozen<user>>>>")
3135 Map<String, Map<String, User>> deeplyNestedFrozenUser;
3236
37+ Map<String, List<Integer>> mapOfUnfrozenListOfInt;
38+ @FrozenValue
39+ Map<String, List<Integer>> mapOfFrozenListOfInt;
40+ @FrozenValue
41+ Map<Integer, List<Set<Integer>>> deeplyNestedUnfrozenSet;
42+ @Frozen("map<int, frozen<list<set<int>>>>")
43+ Map<Integer, List<Set<Integer>>> deeplyNestedUnfrozenSet2;
44+ @Frozen("map<int, frozen<list<frozen<set<int>>>>>")
45+ Map<Integer, List<Set<Integer>>> deeplyNestedFrozenSet;
46+
3347 @Test(groups = "unit")
34- public void checkFrozenTypesTest() throws Exception {
48+ public void should_fail_if_udt_not_frozen() throws Exception {
3549 checkFrozenTypesTest("string", true);
3650 checkFrozenTypesTest("frozenString", false);
3751 checkFrozenTypesTest("listOfStrings", true);
@@ -43,6 +57,15 @@
4357 checkFrozenTypesTest("deeplyNestedFrozenUser", true);
4458 }
4559
60+ @Test(groups = "unit")
61+ public void should_fail_if_nested_collection_not_frozen() throws Exception {
62+ checkFrozenTypesTest("mapOfUnfrozenListOfInt", false);
63+ checkFrozenTypesTest("mapOfFrozenListOfInt", true);
64+ checkFrozenTypesTest("deeplyNestedUnfrozenSet", false);
65+ checkFrozenTypesTest("deeplyNestedUnfrozenSet2", false);
66+ checkFrozenTypesTest("deeplyNestedFrozenSet", true);
67+ }
68+
4669 private void checkFrozenTypesTest(String fieldName, boolean expectSuccess) throws Exception {
4770 Field field = AnnotationChecksTest.class.getDeclaredField(fieldName);
4871 Exception exception = null;
deleted driver-mapping/src/test/java/com/datastax/driver/mapping/CQLTypeTest.java +0 −103
@@ -1,103 +0,0 @@
1-package com.datastax.driver.mapping;
2-
3-import org.testng.annotations.Test;
4-import static org.testng.Assert.*;
5-
6-public class CQLTypeTest {
7- @Test(groups = "unit")
8- public void parseSimpleTypeTest() {
9- CQLType type = CQLType.parse(" foo");
10- assertEquals(type.name, "foo");
11- assertFalse(type.frozen);
12- assertNull(type.subTypes);
13- }
14-
15- @Test(groups = "unit")
16- public void parseQuotedTypeTest() {
17- CQLType type = CQLType.parse("\"Foo bar\"");
18- assertEquals(type.name, "Foo bar");
19- assertFalse(type.frozen);
20- assertNull(type.subTypes);
21- }
22-
23- @Test(groups = "unit")
24- public void parseNestedTypeTest() {
25- // list
26- CQLType type = CQLType.parse("list<foo1>");
27- assertEquals(type.name, "list");
28- assertFalse(type.frozen);
29- assertEquals(type.subTypes.size(), 1);
30-
31- CQLType subType0 = type.subTypes.get(0);
32- assertEquals(subType0.name, "foo1");
33- assertFalse(subType0.frozen);
34- assertNull(subType0.subTypes);
35-
36- // map
37- type = CQLType.parse("map < foo , bar >");
38- assertEquals(type.name, "map");
39- assertFalse(type.frozen);
40- assertEquals(type.subTypes.size(), 2);
41-
42- subType0 = type.subTypes.get(0);
43- assertEquals(subType0.name, "foo");
44- assertFalse(subType0.frozen);
45- assertNull(subType0.subTypes);
46-
47- CQLType subType1 = type.subTypes.get(1);
48- assertEquals(subType1.name, "bar");
49- assertFalse(subType1.frozen);
50- assertNull(subType1.subTypes);
51-
52- }
53-
54- @Test(groups = "unit")
55- public void parseSimpleFrozenTypeTest() {
56- CQLType type = CQLType.parse("frozen<foo_1>");
57- assertEquals(type.name, "foo_1");
58- assertTrue(type.frozen);
59- assertNull(type.subTypes);
60- }
61-
62- @Test(groups = "unit")
63- public void parseNestedFrozenTypeTest() {
64- CQLType type = CQLType.parse("list<frozen<foo>>");
65- assertEquals(type.name, "list");
66- assertFalse(type.frozen);
67- assertEquals(type.subTypes.size(), 1);
68-
69- CQLType subType0 = type.subTypes.get(0);
70- assertEquals(subType0.name, "foo");
71- assertTrue(subType0.frozen);
72- assertNull(subType0.subTypes);
73- }
74-
75- @Test(groups = "unit")
76- public void parseDeeplyNestedTypeTest() {
77- // NB: nested collections are not allowed in C* 2.1, but might be in the future, so we want to handle that
78- CQLType type = CQLType.parse("map<text, map<text, frozen<foo>>>");
79- assertEquals(type.name, "map");
80- assertFalse(type.frozen);
81- assertEquals(type.subTypes.size(), 2);
82-
83- CQLType subType0 = type.subTypes.get(0);
84- assertEquals(subType0.name, "text");
85- assertFalse(subType0.frozen);
86- assertNull(subType0.subTypes);
87-
88- CQLType subType1 = type.subTypes.get(1);
89- assertEquals(subType1.name, "map");
90- assertFalse(subType1.frozen);
91- assertEquals(subType1.subTypes.size(), 2);
92-
93- CQLType subType10 = subType1.subTypes.get(0);
94- assertEquals(subType10.name, "text");
95- assertFalse(subType10.frozen);
96- assertNull(subType10.subTypes);
97-
98- CQLType subType11 = subType1.subTypes.get(1);
99- assertEquals(subType11.name, "foo");
100- assertTrue(subType11.frozen);
101- assertNull(subType11.subTypes);
102- }
103-}
added driver-mapping/src/test/java/com/datastax/driver/mapping/DeclaredFrozenTypeTest.java +103 −0
@@ -0,0 +1,103 @@
1+package com.datastax.driver.mapping;
2+
3+import org.testng.annotations.Test;
4+import static org.testng.Assert.*;
5+
6+public class DeclaredFrozenTypeTest {
7+ @Test(groups = "unit")
8+ public void parseSimpleTypeTest() {
9+ DeclaredFrozenType type = DeclaredFrozenType.parse(" foo");
10+ assertEquals(type.name, "foo");
11+ assertFalse(type.frozen);
12+ assertNull(type.subTypes);
13+ }
14+
15+ @Test(groups = "unit")
16+ public void parseQuotedTypeTest() {
17+ DeclaredFrozenType type = DeclaredFrozenType.parse("\"Foo bar\"");
18+ assertEquals(type.name, "Foo bar");
19+ assertFalse(type.frozen);
20+ assertNull(type.subTypes);
21+ }
22+
23+ @Test(groups = "unit")
24+ public void parseNestedTypeTest() {
25+ // list
26+ DeclaredFrozenType type = DeclaredFrozenType.parse("list<foo1>");
27+ assertEquals(type.name, "list");
28+ assertFalse(type.frozen);
29+ assertEquals(type.subTypes.size(), 1);
30+
31+ DeclaredFrozenType subType0 = type.subTypes.get(0);
32+ assertEquals(subType0.name, "foo1");
33+ assertFalse(subType0.frozen);
34+ assertNull(subType0.subTypes);
35+
36+ // map
37+ type = DeclaredFrozenType.parse("map < foo , bar >");
38+ assertEquals(type.name, "map");
39+ assertFalse(type.frozen);
40+ assertEquals(type.subTypes.size(), 2);
41+
42+ subType0 = type.subTypes.get(0);
43+ assertEquals(subType0.name, "foo");
44+ assertFalse(subType0.frozen);
45+ assertNull(subType0.subTypes);
46+
47+ DeclaredFrozenType subType1 = type.subTypes.get(1);
48+ assertEquals(subType1.name, "bar");
49+ assertFalse(subType1.frozen);
50+ assertNull(subType1.subTypes);
51+
52+ }
53+
54+ @Test(groups = "unit")
55+ public void parseSimpleFrozenTypeTest() {
56+ DeclaredFrozenType type = DeclaredFrozenType.parse("frozen<foo_1>");
57+ assertEquals(type.name, "foo_1");
58+ assertTrue(type.frozen);
59+ assertNull(type.subTypes);
60+ }
61+
62+ @Test(groups = "unit")
63+ public void parseNestedFrozenTypeTest() {
64+ DeclaredFrozenType type = DeclaredFrozenType.parse("list<frozen<foo>>");
65+ assertEquals(type.name, "list");
66+ assertFalse(type.frozen);
67+ assertEquals(type.subTypes.size(), 1);
68+
69+ DeclaredFrozenType subType0 = type.subTypes.get(0);
70+ assertEquals(subType0.name, "foo");
71+ assertTrue(subType0.frozen);
72+ assertNull(subType0.subTypes);
73+ }
74+
75+ @Test(groups = "unit")
76+ public void parseDeeplyNestedTypeTest() {
77+ // NB: nested collections are not allowed in C* 2.1, but might be in the future, so we want to handle that
78+ DeclaredFrozenType type = DeclaredFrozenType.parse("map<text, map<text, frozen<foo>>>");
79+ assertEquals(type.name, "map");
80+ assertFalse(type.frozen);
81+ assertEquals(type.subTypes.size(), 2);
82+
83+ DeclaredFrozenType subType0 = type.subTypes.get(0);
84+ assertEquals(subType0.name, "text");
85+ assertFalse(subType0.frozen);
86+ assertNull(subType0.subTypes);
87+
88+ DeclaredFrozenType subType1 = type.subTypes.get(1);
89+ assertEquals(subType1.name, "map");
90+ assertFalse(subType1.frozen);
91+ assertEquals(subType1.subTypes.size(), 2);
92+
93+ DeclaredFrozenType subType10 = subType1.subTypes.get(0);
94+ assertEquals(subType10.name, "text");
95+ assertFalse(subType10.frozen);
96+ assertNull(subType10.subTypes);
97+
98+ DeclaredFrozenType subType11 = subType1.subTypes.get(1);
99+ assertEquals(subType11.name, "foo");
100+ assertTrue(subType11.frozen);
101+ assertNull(subType11.subTypes);
102+ }
103+}
added driver-mapping/src/test/java/com/datastax/driver/mapping/InferredCQLTypeTest.java +94 −0
@@ -0,0 +1,94 @@
1+package com.datastax.driver.mapping;
2+
3+import java.lang.reflect.Field;
4+import java.util.List;
5+import java.util.Map;
6+import java.util.Set;
7+
8+import org.testng.annotations.BeforeClass;
9+import org.testng.annotations.Test;
10+
11+import static org.mockito.Mockito.mock;
12+import static org.mockito.Mockito.when;
13+
14+import com.datastax.driver.core.CoreHooks;
15+import com.datastax.driver.core.DataType;
16+import com.datastax.driver.core.UserType;
17+import com.datastax.driver.mapping.annotations.UDT;
18+
19+import static com.datastax.driver.core.Assertions.assertThat;
20+
21+public class InferredCQLTypeTest {
22+ MappingManager manager;
23+ UDTMapper mockMapper;
24+ UserType mockUDTType = CoreHooks.MOCK_USER_TYPE;
25+
26+ @BeforeClass(groups = "unit")
27+ @SuppressWarnings("unchecked")
28+ public void setup() {
29+ mockMapper = mock(UDTMapper.class);
30+ when(mockMapper.getUserType()).thenReturn(mockUDTType);
31+
32+ manager = mock(MappingManager.class);
33+ when(manager.udtMapper(MockUDT.class)).thenReturn(mockMapper);
34+ }
35+
36+ @Test(groups = "unit")
37+ public void should_parse_collections_of_primitives() throws Exception {
38+ InferredCQLType instance = newInstanceForField("listOfIntegers");
39+ assertThat(instance.dataType).isEqualTo(DataType.list(DataType.cint()));
40+ assertThat(instance.containsMappedUDT).isFalse();
41+ assertThat(instance.udtMapper).isNull();
42+
43+ instance = newInstanceForField("setOfStrings");
44+ assertThat(instance.dataType).isEqualTo(DataType.set(DataType.text()));
45+ assertThat(instance.containsMappedUDT).isFalse();
46+ assertThat(instance.udtMapper).isNull();
47+
48+ instance = newInstanceForField("mapOfIntegerToString");
49+ assertThat(instance.dataType).isEqualTo(DataType.map(DataType.cint(), DataType.text()));
50+ assertThat(instance.containsMappedUDT).isFalse();
51+ assertThat(instance.udtMapper).isNull();
52+ }
53+
54+ @Test(groups = "unit")
55+ public void should_parse_collection_containing_UDT() throws Exception {
56+ InferredCQLType instance = newInstanceForField("listOfUDT");
57+ assertThat(instance.dataType).isEqualTo(DataType.list(mockUDTType));
58+ assertThat(instance.containsMappedUDT).isTrue();
59+ assertThat(instance.udtMapper).isNull();
60+ assertThat(instance.childTypes.get(0).udtMapper).isEqualTo(mockMapper);
61+
62+ instance = newInstanceForField("complexMap");
63+ assertThat(instance.dataType).isEqualTo(DataType.map(
64+ DataType.list(DataType.cint()),
65+ DataType.map(DataType.text(), DataType.set(mockUDTType))
66+ ));
67+ assertThat(instance.containsMappedUDT).isTrue();
68+ assertThat(instance.udtMapper).isNull();
69+ InferredCQLType key = instance.childTypes.get(0);
70+ assertThat(key.containsMappedUDT).isFalse();
71+ assertThat(key.udtMapper).isNull();
72+ InferredCQLType value = instance.childTypes.get(1);
73+ assertThat(value.containsMappedUDT).isTrue();
74+ assertThat(value.udtMapper).isNull();
75+ assertThat(value.childTypes.get(0).containsMappedUDT).isFalse();
76+ assertThat(value.childTypes.get(1).containsMappedUDT).isTrue();
77+ assertThat(value.childTypes.get(1).childTypes.get(0).udtMapper).isEqualTo(mockMapper);
78+ }
79+
80+ private InferredCQLType newInstanceForField(String name) throws NoSuchFieldException {
81+ Field field = InferredCQLTypeTest.class.getDeclaredField(name);
82+ return InferredCQLType.from(field, manager);
83+ }
84+
85+ @UDT(name = "mock")
86+ static class MockUDT {
87+ }
88+
89+ List<Integer> listOfIntegers;
90+ Set<String> setOfStrings;
91+ Map<Integer, String> mapOfIntegerToString;
92+ List<MockUDT> listOfUDT;
93+ Map<List<Integer>, Map<String, Set<MockUDT>>> complexMap;
94+}
No newline at the end of the file
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperInvalidCollectionTypesTest.java +105 −0
@@ -0,0 +1,105 @@
1+package com.datastax.driver.mapping;
2+
3+import java.util.*;
4+
5+import org.testng.annotations.Test;
6+
7+import com.datastax.driver.core.CCMBridge;
8+import com.datastax.driver.mapping.annotations.PartitionKey;
9+import com.datastax.driver.mapping.annotations.Table;
10+
11+public class MapperInvalidCollectionTypesTest extends CCMBridge.PerClassSingleNodeCluster {
12+ protected Collection<String> getTableDefinitions() {
13+ return Arrays.asList(
14+ "CREATE TABLE table_list (id int PRIMARY KEY, l list<int>)",
15+ "CREATE TABLE table_set (id int PRIMARY KEY, s set<int>)",
16+ "CREATE TABLE table_map (id int PRIMARY KEY, m map<int, int>)");
17+ }
18+
19+ @Table(keyspace="ks", name="table_list")
20+ public class InvalidList {
21+ @PartitionKey
22+ private int id;
23+
24+ private ArrayList<Integer> l;
25+
26+ public int getId() {
27+ return id;
28+ }
29+
30+ public void setId(int id) {
31+ this.id = id;
32+ }
33+
34+ public ArrayList<Integer> getL() {
35+ return l;
36+ }
37+
38+ public void setL(ArrayList<Integer> l) {
39+ this.l = l;
40+ }
41+ }
42+
43+ @Table(keyspace="ks", name="table_set")
44+ public class InvalidSet {
45+ @PartitionKey
46+ private int id;
47+
48+ private HashSet<Integer> s;
49+
50+ public int getId() {
51+ return id;
52+ }
53+
54+ public void setId(int id) {
55+ this.id = id;
56+ }
57+
58+ public HashSet<Integer> getS() {
59+ return s;
60+ }
61+
62+ public void setS(HashSet<Integer> s) {
63+ this.s = s;
64+ }
65+ }
66+
67+ @Table(keyspace="ks", name="table_map")
68+ public class InvalidMap {
69+ @PartitionKey
70+ private int id;
71+
72+ private TreeMap<Integer, Integer> m;
73+
74+ public TreeMap<Integer, Integer> getM() {
75+ return m;
76+ }
77+
78+ public void setM(TreeMap<Integer, Integer> m) {
79+ this.m = m;
80+ }
81+
82+ public int getId() {
83+ return id;
84+ }
85+
86+ public void setId(int id) {
87+ this.id = id;
88+ }
89+ }
90+
91+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
92+ public void list_type_is_enforced() {
93+ new MappingManager(session).mapper(InvalidList.class);
94+ }
95+
96+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
97+ public void map_type_is_enforced() {
98+ new MappingManager(session).mapper(InvalidMap.class);
99+ }
100+
101+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
102+ public void set_type_is_enforced() {
103+ new MappingManager(session).mapper(InvalidSet.class);
104+ }
105+}
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperNestedCollectionsTest.java +179 −0
@@ -0,0 +1,179 @@
1+package com.datastax.driver.mapping;
2+
3+import java.util.*;
4+
5+import com.google.common.collect.ImmutableMap;
6+import com.google.common.collect.Lists;
7+import com.google.common.collect.Sets;
8+import org.testng.annotations.Test;
9+
10+import com.datastax.driver.core.CCMBridge;
11+import com.datastax.driver.core.ResultSet;
12+import com.datastax.driver.core.utils.CassandraVersion;
13+import com.datastax.driver.mapping.annotations.*;
14+
15+import static com.datastax.driver.core.Assertions.assertThat;
16+
17+@CassandraVersion(major=2.1, minor=3)
18+public class MapperNestedCollectionsTest extends CCMBridge.PerClassSingleNodeCluster {
19+
20+ @Override
21+ protected Collection<String> getTableDefinitions() {
22+ return Lists.newArrayList(
23+ "CREATE TYPE testType(i int, ls list<frozen<set<int>>>)",
24+ "CREATE TABLE testTable (k int primary key, "
25+ + "m1 map<text, frozen<map<int, int>>>, " // nested collection
26+ + "m2 map<text, frozen<map<int, frozen<testType>>>>)" // nested collection with UDT
27+ );
28+ }
29+
30+ @Test(groups = "short")
31+ public void should_map_fields_to_nested_collections() {
32+ Mapper<TestTable> mapper = new MappingManager(session).mapper(TestTable.class);
33+
34+ TestTable testTable = new TestTable();
35+ testTable.setK(1);
36+ testTable.setM1(ImmutableMap.<String, Map<Integer, Integer>>of("bar", ImmutableMap.of(1, 2)));
37+
38+ Set<Integer> s1 = Sets.newHashSet(1,2,3);
39+ Set<Integer> s2 = Sets.newHashSet(4,5,6);
40+ List<Set<Integer>> ls = new ArrayList<Set<Integer>>();
41+ ls.add(s1);
42+ ls.add(s2);
43+
44+ testTable.setM2(ImmutableMap.<String, Map<Integer, TestType>>of("bar", ImmutableMap.of(1, new TestType(2, ls))));
45+
46+ mapper.save(testTable);
47+
48+ TestTable testTable2 = mapper.get(1);
49+ assertThat(testTable2.getM1()).isEqualTo(testTable.getM1());
50+ assertThat(testTable2.getM2()).isEqualTo(testTable.getM2());
51+ }
52+
53+ @Test(groups = "short")
54+ public void should_map_accessor_params_to_nested_collections() {
55+ MappingManager manager = new MappingManager(session);
56+ Mapper<TestTable> mapper = manager.mapper(TestTable.class);
57+ TestAccessor accessor = manager.createAccessor(TestAccessor.class);
58+
59+ TestTable testTable = new TestTable();
60+ testTable.setK(1);
61+ mapper.save(testTable);
62+
63+ Map<String, Map<Integer, Integer>> m1 = ImmutableMap.<String, Map<Integer, Integer>>of("bar", ImmutableMap.of(1, 2));
64+ Map<String, Map<Integer, TestType>> m2 = ImmutableMap.<String, Map<Integer, TestType>>of("bar", ImmutableMap.of(1, new TestType(2)));
65+ accessor.setM1(1, m1);
66+ accessor.setM2(1, m2);
67+
68+ TestTable testTable2 = mapper.get(1);
69+ assertThat(testTable2.getM1()).isEqualTo(m1);
70+ assertThat(testTable2.getM2()).isEqualTo(m2);
71+ }
72+
73+ @UDT(keyspace = "ks", name = "testType")
74+ public static class TestType {
75+ private int i;
76+
77+ @Frozen("list<frozen<set<int>>>")
78+ private List<Set<Integer>> ls;
79+
80+ public TestType() {
81+ ls = Lists.newArrayList();
82+ }
83+
84+ public TestType(int i) {
85+ this();
86+ this.i = i;
87+ }
88+
89+ public TestType(int i, List<Set<Integer>> ls) {
90+ this(i);
91+ this.ls = ls;
92+ }
93+
94+ public int getI() {
95+ return i;
96+ }
97+
98+ public void setI(int i) {
99+ this.i = i;
100+ }
101+
102+ public List<Set<Integer>> getLs() {
103+ return ls;
104+ }
105+
106+ public void setLs(List<Set<Integer>> ls) {
107+ this.ls = ls;
108+ }
109+
110+ @Override
111+ public boolean equals(Object o) {
112+ if (this == o)
113+ return true;
114+ if (!(o instanceof TestType))
115+ return false;
116+
117+ TestType testType = (TestType)o;
118+
119+ if (i != testType.i)
120+ return false;
121+ if (!ls.equals(testType.ls))
122+ return false;
123+
124+ return true;
125+ }
126+
127+ @Override
128+ public int hashCode() {
129+ int result = i;
130+ result = 31 * result + ls.hashCode();
131+ return result;
132+ }
133+ }
134+
135+ @Table(keyspace = "ks", name = "testTable")
136+ public static class TestTable {
137+ @PartitionKey
138+ private int k;
139+
140+ @Frozen("map<text, frozen<map<int, int>>>")
141+ private Map<String, Map<Integer, Integer>> m1;
142+
143+ @Frozen("map<text, frozen<map<int, frozen<testType>>>>")
144+ private Map<String, Map<Integer, TestType>> m2;
145+
146+ public int getK() {
147+ return k;
148+ }
149+
150+ public void setK(int k) {
151+ this.k = k;
152+ }
153+
154+ public Map<String, Map<Integer, Integer>> getM1() {
155+ return m1;
156+ }
157+
158+ public void setM1(Map<String, Map<Integer, Integer>> m1) {
159+ this.m1 = m1;
160+ }
161+
162+ public Map<String, Map<Integer, TestType>> getM2() {
163+ return m2;
164+ }
165+
166+ public void setM2(Map<String, Map<Integer, TestType>> m2) {
167+ this.m2 = m2;
168+ }
169+ }
170+
171+ @Accessor
172+ public static interface TestAccessor {
173+ @Query("UPDATE testTable SET m1 = :m1 WHERE k = :k")
174+ ResultSet setM1(@Param("k") int k, @Param("m1") Map<String, Map<Integer, Integer>> m1);
175+
176+ @Query("UPDATE testTable SET m2 = :m2 WHERE k = :k")
177+ ResultSet setM2(@Param("k") int k, @Param("m2") Map<String, Map<Integer, TestType>> m2);
178+ }
179+}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/UDTFieldMapperTest.java +2 −4
@@ -10,14 +10,14 @@
1010 import com.datastax.driver.core.Cluster;
1111 import com.datastax.driver.core.Session;
1212 import com.datastax.driver.core.TestUtils;
13+import com.datastax.driver.core.utils.CassandraVersion;
1314 import com.datastax.driver.mapping.annotations.*;
1415
16+@CassandraVersion(major=2.1)
1517 public class UDTFieldMapperTest {
1618
1719 @Test(groups = "short")
1820 public void udt_and_tables_with_ks_created_in_another_session_should_be_mapped() {
19- TestUtils.versionCheck(2.1, 0, "This will only work with C* 2.1.0");
20-
2121 CCMBridge ccm = null;
2222 Cluster cluster = null;
2323
@@ -65,8 +65,6 @@
6565
6666 @Test(groups = "short")
6767 public void udt_and_tables_without_ks_created_in_another_session_should_be_mapped() {
68- TestUtils.versionCheck(2.1, 0, "This will only work with C* 2.1.0");
69-
7068 CCMBridge ccm = null;
7169 Cluster cluster = null;
7270
modified pom.xml +1 −1
@@ -38,7 +38,7 @@
3838
3939 <properties>
4040 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
41- <cassandra.version>2.1.2</cassandra.version>
41+ <cassandra.version>2.1.3</cassandra.version>
4242 </properties>
4343
4444 <dependencies>