Elffuss BraidHub

kikocis/java-driver public

Merge pull request #563 from datastax/java1015b

Minor enhancements to CodecRegistry and TypeCodec.
Changeset28f8bbec5132f5ee29d7d7ca2e768a070f8e02702d2a138021ae1f4de9420995
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-12-18 15:36 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-12-18 15:36 +01:00
Parents24fd40390128, 132d405ba3c4

Browse the files at this changeset

6 files changed

modified driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java +13 −6
@@ -240,7 +240,7 @@
240240
241241 @Override
242242 public int weigh(CacheKey key, TypeCodec<?> value) {
243- return codecs.contains(value) ? 0 : weigh(key.cqlType, 0);
243+ return codecs.contains(value) ? 0 : weigh(value.cqlType, 0);
244244 }
245245
246246 private int weigh(DataType cqlType, int level) {
@@ -484,7 +484,8 @@
484484 @SuppressWarnings("unchecked")
485485 private <T> TypeCodec<T> lookupCodec(DataType cqlType, TypeToken<T> javaType) {
486486 checkNotNull(cqlType, "Parameter cqlType cannot be null");
487- logger.trace("Querying cache for codec [{} <-> {}]", cqlType, javaType == null ? "ANY" : javaType);
487+ if (logger.isTraceEnabled())
488+ logger.trace("Querying cache for codec [{} <-> {}]", toString(cqlType), toString(javaType));
488489 CacheKey cacheKey = new CacheKey(cqlType, javaType);
489490 try {
490491 TypeCodec<?> codec = cache.get(cacheKey);
@@ -505,7 +506,8 @@
505506 @SuppressWarnings("unchecked")
506507 private <T> TypeCodec<T> findCodec(DataType cqlType, TypeToken<T> javaType) {
507508 checkNotNull(cqlType, "Parameter cqlType cannot be null");
508- logger.trace("Looking for codec [{} <-> {}]", cqlType, javaType == null ? "ANY" : javaType);
509+ if (logger.isTraceEnabled())
510+ logger.trace("Looking for codec [{} <-> {}]", toString(cqlType), toString(javaType));
509511 for (TypeCodec<?> codec : codecs) {
510512 if (codec.accepts(cqlType) && (javaType == null || codec.accepts(javaType))) {
511513 logger.trace("Codec found: {}", codec);
@@ -518,7 +520,8 @@
518520 @SuppressWarnings("unchecked")
519521 private <T> TypeCodec<T> findCodec(DataType cqlType, T value) {
520522 checkNotNull(value, "Parameter value cannot be null");
521- logger.trace("Looking for codec [{} <-> {}]", cqlType == null ? "ANY" : cqlType, value.getClass());
523+ if (logger.isTraceEnabled())
524+ logger.trace("Looking for codec [{} <-> {}]", toString(cqlType), value.getClass());
522525 for (TypeCodec<?> codec : codecs) {
523526 if ((cqlType == null || codec.accepts(cqlType)) && codec.accepts(value)) {
524527 logger.trace("Codec found: {}", codec);
@@ -682,9 +685,13 @@
682685
683686 private static CodecNotFoundException notFound(DataType cqlType, TypeToken<?> javaType) {
684687 String msg = String.format("Codec not found for requested operation: [%s <-> %s]",
685- cqlType == null ? "ANY" : cqlType,
686- javaType == null ? "ANY" : javaType);
688+ toString(cqlType),
689+ toString(javaType));
687690 return new CodecNotFoundException(msg, cqlType, javaType);
688691 }
689692
693+ private static String toString(Object value) {
694+ return value == null ? "ANY" : value.toString();
695+ }
696+
690697 }
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +21 −20
@@ -17,7 +17,6 @@
1717
1818 import com.datastax.driver.core.exceptions.InvalidTypeException;
1919 import com.datastax.driver.core.utils.Bytes;
20-import com.google.common.collect.ImmutableMap;
2120 import com.google.common.reflect.TypeToken;
2221
2322 import java.math.BigDecimal;
@@ -99,17 +98,6 @@
9998 */
10099 public abstract class TypeCodec<T> {
101100
102- private static final Map<TypeToken<?>, TypeToken<?>> primitiveToWrapperMap = ImmutableMap.<TypeToken<?>, TypeToken<?>>builder()
103- .put(TypeToken.of(Boolean.TYPE), TypeToken.of(Boolean.class))
104- .put(TypeToken.of(Byte.TYPE), TypeToken.of(Byte.class))
105- .put(TypeToken.of(Character.TYPE), TypeToken.of(Character.class))
106- .put(TypeToken.of(Short.TYPE), TypeToken.of(Short.class))
107- .put(TypeToken.of(Integer.TYPE), TypeToken.of(Integer.class))
108- .put(TypeToken.of(Long.TYPE), TypeToken.of(Long.class))
109- .put(TypeToken.of(Double.TYPE), TypeToken.of(Double.class))
110- .put(TypeToken.of(Float.TYPE), TypeToken.of(Float.class))
111- .build();
112-
113101 /**
114102 * Return the default codec for the CQL type {@code boolean}.
115103 * The returned codec maps the CQL type {@code boolean} into the Java type {@link Boolean}.
@@ -531,7 +519,7 @@
531519 * The implementation is <em>invariant</em> with respect to the passed
532520 * argument (through the usage of {@link TypeToken#equals(Object)}
533521 * and <em>it's strongly recommended not to modify this behavior</em>.
534- * This means that a codec will only ever accept the
522+ * This means that a codec will only ever return {@code true} for the
535523 * <em>exact</em> Java type that it has been created for.
536524 * <p/>
537525 * If the argument represents a Java primitive type, its wrapper type
@@ -543,11 +531,24 @@
543531 * @throws NullPointerException if {@code javaType} is {@code null}.
544532 */
545533 public boolean accepts(TypeToken javaType) {
546- checkNotNull(javaType);
547- if (javaType.isPrimitive()) {
548- javaType = primitiveToWrapperMap.get(javaType);
549- }
550- return this.javaType.equals(javaType);
534+ checkNotNull(javaType, "Parameter javaType cannot be null");
535+ return this.javaType.equals(javaType.wrap());
536+ }
537+
538+ /**
539+ * Return {@code true} if this codec is capable of serializing
540+ * the given {@code javaType}.
541+ * <p/>
542+ * This implementation simply calls {@link #accepts(TypeToken)}.
543+ *
544+ * @param javaType The Java type this codec should serialize from and deserialize to; cannot be {@code null}.
545+ * @return {@code true} if the codec is capable of serializing
546+ * the given {@code javaType}, and {@code false} otherwise.
547+ * @throws NullPointerException if {@code javaType} is {@code null}.
548+ */
549+ public boolean accepts(Class<?> javaType) {
550+ checkNotNull(javaType, "Parameter javaType cannot be null");
551+ return accepts(TypeToken.of(javaType));
551552 }
552553
553554 /**
@@ -560,7 +561,7 @@
560561 * @throws NullPointerException if {@code cqlType} is {@code null}.
561562 */
562563 public boolean accepts(DataType cqlType) {
563- checkNotNull(cqlType);
564+ checkNotNull(cqlType, "Parameter cqlType cannot be null");
564565 return this.cqlType.equals(cqlType);
565566 }
566567
@@ -596,7 +597,7 @@
596597 * @throws NullPointerException if {@code value} is {@code null}.
597598 */
598599 public boolean accepts(Object value) {
599- checkNotNull(value);
600+ checkNotNull(value, "Parameter value cannot be null");
600601 return this.javaType.isAssignableFrom(TypeToken.of(value.getClass()));
601602 }
602603
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +2 −2
@@ -76,8 +76,8 @@
7676 return new IndexMetadataAssert(index);
7777 }
7878
79- public static TypeCodecAssert assertThat(TypeCodec codec) {
80- return new TypeCodecAssert(codec);
79+ public static <T> TypeCodecAssert<T> assertThat(TypeCodec<T> codec) {
80+ return new TypeCodecAssert<T>(codec);
8181 }
8282
8383 public static MaterializedViewMetadataAssert assertThat(MaterializedViewMetadata view) {
modified driver-core/src/test/java/com/datastax/driver/core/CodecRegistryTest.java +429 −16
@@ -15,19 +15,427 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.CodecNotFoundException;
1819 import com.google.common.reflect.TypeToken;
1920 import org.apache.log4j.Level;
2021 import org.apache.log4j.Logger;
22+import org.testng.annotations.DataProvider;
2123 import org.testng.annotations.Test;
2224
23-import java.util.List;
25+import java.math.BigDecimal;
26+import java.math.BigInteger;
27+import java.net.InetAddress;
28+import java.nio.ByteBuffer;
29+import java.util.*;
2430
2531 import static com.datastax.driver.core.Assertions.assertThat;
32+import static com.datastax.driver.core.DataType.*;
33+import static com.datastax.driver.core.DataType.list;
34+import static com.datastax.driver.core.ProtocolVersion.V4;
35+import static com.datastax.driver.core.TypeTokens.*;
36+import static com.google.common.reflect.TypeToken.of;
37+import static java.util.Collections.*;
2638 import static org.mockito.Mockito.mock;
2739 import static org.mockito.Mockito.when;
40+import static org.testng.Assert.fail;
2841
2942 public class CodecRegistryTest {
30- TypeToken<List<Integer>> LIST_OF_INT_TOKEN = TypeTokens.listOf(Integer.class);
43+
44+ @DataProvider
45+ public static Object[][] cql() {
46+ return new Object[][]{
47+ {DataType.blob(), TypeCodec.blob()},
48+ {DataType.cboolean(), TypeCodec.cboolean()},
49+ {DataType.smallint(), TypeCodec.smallInt()},
50+ {DataType.tinyint(), TypeCodec.tinyInt()},
51+ {DataType.cint(), TypeCodec.cint()},
52+ {DataType.bigint(), TypeCodec.bigint()},
53+ {DataType.counter(), TypeCodec.counter()},
54+ {DataType.cdouble(), TypeCodec.cdouble()},
55+ {DataType.cfloat(), TypeCodec.cfloat()},
56+ {DataType.varint(), TypeCodec.varint()},
57+ {DataType.decimal(), TypeCodec.decimal()},
58+ {DataType.varchar(), TypeCodec.varchar()},
59+ {DataType.ascii(), TypeCodec.ascii()},
60+ {DataType.timestamp(), TypeCodec.timestamp()},
61+ {DataType.date(), TypeCodec.date()},
62+ {DataType.time(), TypeCodec.time()},
63+ {DataType.uuid(), TypeCodec.uuid()},
64+ {DataType.timeuuid(), TypeCodec.timeUUID()},
65+ {DataType.inet(), TypeCodec.inet()}
66+ };
67+ }
68+
69+ @DataProvider
70+ public static Object[][] cqlAndJava() {
71+ return new Object[][]{
72+ {DataType.blob(), ByteBuffer.class, TypeCodec.blob()},
73+ {DataType.cboolean(), Boolean.class, TypeCodec.cboolean()},
74+ {DataType.smallint(), Short.class, TypeCodec.smallInt()},
75+ {DataType.tinyint(), Byte.class, TypeCodec.tinyInt()},
76+ {DataType.cint(), Integer.class, TypeCodec.cint()},
77+ {DataType.bigint(), Long.class, TypeCodec.bigint()},
78+ {DataType.counter(), Long.class, TypeCodec.counter()},
79+ {DataType.cdouble(), Double.class, TypeCodec.cdouble()},
80+ {DataType.cfloat(), Float.class, TypeCodec.cfloat()},
81+ {DataType.varint(), BigInteger.class, TypeCodec.varint()},
82+ {DataType.decimal(), BigDecimal.class, TypeCodec.decimal()},
83+ {DataType.varchar(), String.class, TypeCodec.varchar()},
84+ {DataType.ascii(), String.class, TypeCodec.ascii()},
85+ {DataType.timestamp(), Date.class, TypeCodec.timestamp()},
86+ {DataType.date(), LocalDate.class, TypeCodec.date()},
87+ {DataType.time(), Long.class, TypeCodec.time()},
88+ {DataType.uuid(), UUID.class, TypeCodec.uuid()},
89+ {DataType.timeuuid(), UUID.class, TypeCodec.timeUUID()},
90+ {DataType.inet(), InetAddress.class, TypeCodec.inet()}
91+ };
92+ }
93+
94+ @DataProvider
95+ public static Object[][] value() {
96+ return new Object[][]{
97+ {ByteBuffer.allocate(0), TypeCodec.blob()},
98+ {Boolean.TRUE, TypeCodec.cboolean()},
99+ {(short) 42, TypeCodec.smallInt()},
100+ {(byte) 42, TypeCodec.tinyInt()},
101+ {42, TypeCodec.cint()},
102+ {42L, TypeCodec.bigint()},
103+ {42D, TypeCodec.cdouble()},
104+ {42F, TypeCodec.cfloat()},
105+ {new BigInteger("1234"), TypeCodec.varint()},
106+ {new BigDecimal("123.45"), TypeCodec.decimal()},
107+ {"foo", TypeCodec.varchar()},
108+ {new Date(42), TypeCodec.timestamp()},
109+ {LocalDate.fromDaysSinceEpoch(42), TypeCodec.date()},
110+ {UUID.randomUUID(), TypeCodec.uuid()},
111+ {mock(InetAddress.class), TypeCodec.inet()}
112+ };
113+ }
114+
115+ @DataProvider
116+ public static Object[][] cqlAndValue() {
117+ return new Object[][]{
118+ {DataType.blob(), ByteBuffer.allocate(0), TypeCodec.blob()},
119+ {DataType.cboolean(), true, TypeCodec.cboolean()},
120+ {DataType.smallint(), (short) 42, TypeCodec.smallInt()},
121+ {DataType.tinyint(), (byte) 42, TypeCodec.tinyInt()},
122+ {DataType.cint(), 42, TypeCodec.cint()},
123+ {DataType.bigint(), 42L, TypeCodec.bigint()},
124+ {DataType.counter(), 42L, TypeCodec.counter()},
125+ {DataType.cdouble(), 42D, TypeCodec.cdouble()},
126+ {DataType.cfloat(), 42F, TypeCodec.cfloat()},
127+ {DataType.varint(), new BigInteger("1234"), TypeCodec.varint()},
128+ {DataType.decimal(), new BigDecimal("123.45"), TypeCodec.decimal()},
129+ {DataType.varchar(), "foo", TypeCodec.varchar()},
130+ {DataType.ascii(), "foo", TypeCodec.ascii()},
131+ {DataType.timestamp(), new Date(42), TypeCodec.timestamp()},
132+ {DataType.date(), LocalDate.fromDaysSinceEpoch(42), TypeCodec.date()},
133+ {DataType.time(), 42L, TypeCodec.time()},
134+ {DataType.uuid(), UUID.randomUUID(), TypeCodec.uuid()},
135+ {DataType.timeuuid(), UUID.randomUUID(), TypeCodec.timeUUID()},
136+ {DataType.inet(), mock(InetAddress.class), TypeCodec.inet()}
137+ };
138+ }
139+
140+ @Test(groups = "unit", dataProvider = "cql")
141+ public void should_find_codec_by_cql_type(DataType cqlType, TypeCodec<?> expected) {
142+ // given
143+ CodecRegistry registry = new CodecRegistry();
144+ // when
145+ TypeCodec<?> actual = registry.codecFor(cqlType);
146+ // then
147+ assertThat(actual)
148+ .isNotNull()
149+ .accepts(cqlType)
150+ .isSameAs(expected);
151+ }
152+
153+ @Test(groups = "unit", dataProvider = "cqlAndJava")
154+ public void should_find_codec_by_cql_type_java_type(DataType cqlType, Class<?> javaType, TypeCodec<?> expected) {
155+ // given
156+ CodecRegistry registry = new CodecRegistry();
157+ // when
158+ TypeCodec<?> actual = registry.codecFor(cqlType, javaType);
159+ // then
160+ assertThat(actual)
161+ .isNotNull()
162+ .accepts(cqlType)
163+ .accepts(javaType)
164+ .isSameAs(expected);
165+ }
166+
167+ @Test(groups = "unit", dataProvider = "value")
168+ public void should_find_codec_by_value(Object value, TypeCodec<?> expected) {
169+ // given
170+ CodecRegistry registry = new CodecRegistry();
171+ // when
172+ TypeCodec<?> actual = registry.codecFor(value);
173+ // then
174+ assertThat(actual)
175+ .isNotNull()
176+ .accepts(value)
177+ .isSameAs(expected);
178+ }
179+
180+ @Test(groups = "unit", dataProvider = "cqlAndValue")
181+ public void should_find_codec_by_cql_type_and_value(DataType cqlType, Object value, TypeCodec<?> expected) {
182+ // given
183+ CodecRegistry registry = new CodecRegistry();
184+ // when
185+ TypeCodec<?> actual = registry.codecFor(cqlType, value);
186+ // then
187+ assertThat(actual)
188+ .isNotNull()
189+ .accepts(cqlType)
190+ .accepts(value)
191+ .isSameAs(expected);
192+ }
193+
194+ @Test(groups = "unit")
195+ public void should_find_newly_registered_codec_by_cql_type() {
196+ // given
197+ CodecRegistry registry = new CodecRegistry();
198+ TypeCodec expected = mockCodec(list(text()), listOf(String.class));
199+ registry.register(expected);
200+ // when
201+ TypeCodec<?> actual = registry.codecFor(list(text()));
202+ // then
203+ assertThat(actual)
204+ .isNotNull()
205+ .isSameAs(expected);
206+ }
207+
208+ @Test(groups = "unit")
209+ public void should_find_default_codec_if_cql_type_already_registered() {
210+ // given
211+ CodecRegistry registry = new CodecRegistry();
212+ TypeCodec newCodec = mockCodec(text(), of(StringBuilder.class));
213+ registry.register(newCodec);
214+ // when
215+ TypeCodec<?> actual = registry.codecFor(text());
216+ // then
217+ assertThat(actual)
218+ .isNotNull()
219+ .isNotSameAs(newCodec)
220+ .accepts(text())
221+ .accepts(String.class)
222+ .doesNotAccept(StringBuilder.class);
223+ }
224+
225+ @Test(groups = "unit")
226+ public void should_find_newly_registered_codec_by_cql_type_and_java_type() {
227+ // given
228+ CodecRegistry registry = new CodecRegistry();
229+ TypeCodec expected = mockCodec(list(text()), listOf(String.class));
230+ registry.register(expected);
231+ // when
232+ TypeCodec<?> actual = registry.codecFor(list(text()), listOf(String.class));
233+ // then
234+ assertThat(actual)
235+ .isNotNull()
236+ .isSameAs(expected);
237+ }
238+
239+ @Test(groups = "unit")
240+ public void should_create_list_codec() {
241+ CollectionType cqlType = list(cint());
242+ TypeToken<List<Integer>> javaType = listOf(Integer.class);
243+ assertThat(new CodecRegistry().codecFor(cqlType))
244+ .isNotNull()
245+ .accepts(cqlType)
246+ .accepts(javaType);
247+ assertThat(new CodecRegistry().codecFor(cqlType, javaType))
248+ .isNotNull()
249+ .accepts(cqlType)
250+ .accepts(javaType);
251+ assertThat(new CodecRegistry().codecFor(singletonList(42)))
252+ .isNotNull()
253+ .accepts(cqlType)
254+ .accepts(javaType);
255+ assertThat(new CodecRegistry().codecFor(cqlType, singletonList(42)))
256+ .isNotNull()
257+ .accepts(cqlType)
258+ .accepts(javaType);
259+ assertThat(new CodecRegistry().codecFor(new ArrayList<Integer>()))
260+ .isNotNull()
261+ // empty collections are mapped to blob codec if no CQL type provided
262+ .accepts(list(blob()))
263+ .accepts(listOf(ByteBuffer.class));
264+ assertThat(new CodecRegistry().codecFor(cqlType, new ArrayList<Integer>()))
265+ .isNotNull()
266+ .accepts(cqlType)
267+ .accepts(javaType);
268+ }
269+
270+ @Test(groups = "unit")
271+ public void should_create_set_codec() {
272+ CollectionType cqlType = set(cint());
273+ TypeToken<Set<Integer>> javaType = setOf(Integer.class);
274+ assertThat(new CodecRegistry().codecFor(cqlType))
275+ .isNotNull()
276+ .accepts(cqlType)
277+ .accepts(javaType);
278+ assertThat(new CodecRegistry().codecFor(cqlType, javaType))
279+ .isNotNull()
280+ .accepts(cqlType)
281+ .accepts(javaType);
282+ assertThat(new CodecRegistry().codecFor(singleton(42)))
283+ .isNotNull()
284+ .accepts(cqlType)
285+ .accepts(javaType);
286+ assertThat(new CodecRegistry().codecFor(cqlType, singleton(42)))
287+ .isNotNull()
288+ .accepts(cqlType)
289+ .accepts(javaType);
290+ assertThat(new CodecRegistry().codecFor(new HashSet<Integer>()))
291+ .isNotNull()
292+ // empty collections are mapped to blob codec if no CQL type provided
293+ .accepts(set(blob()))
294+ .accepts(setOf(ByteBuffer.class));
295+ assertThat(new CodecRegistry().codecFor(cqlType, new HashSet<Integer>()))
296+ .isNotNull()
297+ .accepts(cqlType)
298+ .accepts(javaType);
299+ }
300+
301+ @Test(groups = "unit")
302+ public void should_create_map_codec() {
303+ CollectionType cqlType = map(cint(), list(varchar()));
304+ TypeToken<Map<Integer, List<String>>> javaType = mapOf(of(Integer.class), listOf(String.class));
305+ assertThat(new CodecRegistry().codecFor(cqlType))
306+ .isNotNull()
307+ .accepts(cqlType)
308+ .accepts(javaType);
309+ assertThat(new CodecRegistry().codecFor(cqlType, javaType))
310+ .isNotNull()
311+ .accepts(cqlType)
312+ .accepts(javaType);
313+ assertThat(new CodecRegistry().codecFor(singletonMap(42, singletonList("foo"))))
314+ .isNotNull()
315+ .accepts(cqlType)
316+ .accepts(javaType);
317+ assertThat(new CodecRegistry().codecFor(cqlType, singletonMap(42, singletonList("foo"))))
318+ .isNotNull()
319+ .accepts(cqlType)
320+ .accepts(javaType);
321+ assertThat(new CodecRegistry().codecFor(new HashMap<Integer, List<String>>()))
322+ .isNotNull()
323+ // empty collections are mapped to blob codec if no CQL type provided
324+ .accepts(map(blob(), blob()))
325+ .accepts(mapOf(ByteBuffer.class, ByteBuffer.class));
326+ assertThat(new CodecRegistry().codecFor(cqlType, new HashMap<Integer, List<String>>()))
327+ .isNotNull()
328+ .accepts(cqlType)
329+ .accepts(javaType);
330+ }
331+
332+ @Test(groups = "unit")
333+ public void should_create_tuple_codec() {
334+ CodecRegistry registry = new CodecRegistry();
335+ TupleType tupleType = TupleType.of(V4, registry, cint(), varchar());
336+ assertThat(registry.codecFor(tupleType))
337+ .isNotNull()
338+ .accepts(tupleType)
339+ .accepts(TupleValue.class);
340+ registry = new CodecRegistry();
341+ tupleType = TupleType.of(V4, registry, cint(), varchar());
342+ assertThat(registry.codecFor(tupleType, TupleValue.class))
343+ .isNotNull()
344+ .accepts(tupleType)
345+ .accepts(TupleValue.class);
346+ registry = new CodecRegistry();
347+ tupleType = TupleType.of(V4, registry, cint(), varchar());
348+ assertThat(registry.codecFor(new TupleValue(tupleType)))
349+ .isNotNull()
350+ .accepts(tupleType)
351+ .accepts(TupleValue.class);
352+ assertThat(registry.codecFor(tupleType, new TupleValue(tupleType)))
353+ .isNotNull()
354+ .accepts(tupleType)
355+ .accepts(TupleValue.class);
356+ }
357+
358+ @Test(groups = "unit")
359+ public void should_create_udt_codec() {
360+ CodecRegistry registry = new CodecRegistry();
361+ UserType udt = new UserType("ks", "test", Collections.<UserType.Field>emptyList(), V4, registry);
362+ assertThat(registry.codecFor(udt))
363+ .isNotNull()
364+ .accepts(udt)
365+ .accepts(UDTValue.class);
366+ registry = new CodecRegistry();
367+ udt = new UserType("ks", "test", Collections.<UserType.Field>emptyList(), V4, registry);
368+ assertThat(registry.codecFor(udt, UDTValue.class))
369+ .isNotNull()
370+ .accepts(udt)
371+ .accepts(UDTValue.class);
372+ registry = new CodecRegistry();
373+ udt = new UserType("ks", "test", Collections.<UserType.Field>emptyList(), V4, registry);
374+ assertThat(registry.codecFor(new UDTValue(udt)))
375+ .isNotNull()
376+ .accepts(udt)
377+ .accepts(UDTValue.class);
378+ registry = new CodecRegistry();
379+ udt = new UserType("ks", "test", Collections.<UserType.Field>emptyList(), V4, registry);
380+ assertThat(registry.codecFor(udt, new UDTValue(udt)))
381+ .isNotNull()
382+ .accepts(udt)
383+ .accepts(UDTValue.class);
384+ }
385+
386+ @Test(groups = "unit")
387+ public void should_create_codec_for_custom_cql_type() {
388+ DataType custom = DataType.custom("foo");
389+ assertThat(new CodecRegistry().codecFor(custom))
390+ .isNotNull()
391+ .accepts(custom)
392+ .accepts(ByteBuffer.class);
393+ assertThat(new CodecRegistry().codecFor(custom, ByteBuffer.class))
394+ .isNotNull()
395+ .accepts(custom)
396+ .accepts(ByteBuffer.class);
397+ assertThat(new CodecRegistry().codecFor(custom, ByteBuffer.allocate(0)))
398+ .isNotNull()
399+ .accepts(custom)
400+ .accepts(ByteBuffer.class);
401+ }
402+
403+ @Test(groups = "unit")
404+ public void should_create_derived_codecs_for_java_type_handled_by_custom_codec() {
405+ TypeCodec<?> newCodec = mockCodec(varchar(), of(StringBuilder.class));
406+ CodecRegistry registry = new CodecRegistry().register(newCodec);
407+ // lookup by CQL type only returns default codec
408+ assertThat(registry.codecFor(list(varchar()))).doesNotAccept(listOf(StringBuilder.class));
409+ assertThat(registry.codecFor(list(varchar()), listOf(StringBuilder.class))).isNotNull();
410+ }
411+
412+ @Test(groups = "unit")
413+ public void should_not_find_codec_if_java_type_unknown() {
414+ try {
415+ new CodecRegistry().codecFor(StringBuilder.class);
416+ fail("Should not have found a codec for ANY <-> StringBuilder");
417+ } catch (CodecNotFoundException e) {
418+ // expected
419+ }
420+ try {
421+ new CodecRegistry().codecFor(varchar(), StringBuilder.class);
422+ fail("Should not have found a codec for varchar <-> StringBuilder");
423+ } catch (CodecNotFoundException e) {
424+ // expected
425+ }
426+ try {
427+ new CodecRegistry().codecFor(new StringBuilder());
428+ fail("Should not have found a codec for ANY <-> StringBuilder");
429+ } catch (CodecNotFoundException e) {
430+ // expected
431+ }
432+ try {
433+ new CodecRegistry().codecFor(varchar(), new StringBuilder());
434+ fail("Should not have found a codec for varchar <-> StringBuilder");
435+ } catch (CodecNotFoundException e) {
436+ // expected
437+ }
438+ }
31439
32440 @Test(groups = "unit")
33441 public void should_ignore_codec_colliding_with_already_registered_codec() {
@@ -35,16 +443,13 @@
35443
36444 CodecRegistry registry = new CodecRegistry();
37445
38- TypeCodec newCodec = mock(TypeCodec.class);
39- when(newCodec.getCqlType()).thenReturn(DataType.cint());
40- when(newCodec.getJavaType()).thenReturn(TypeToken.of(Integer.class));
41- when(newCodec.toString()).thenReturn("newCodec");
446+ TypeCodec newCodec = mockCodec(cint(), of(Integer.class));
42447
43448 registry.register(newCodec);
44449
45- assertThat(logs.getNext()).contains("Ignoring codec newCodec");
450+ assertThat(logs.getNext()).contains("Ignoring codec MockCodec");
46451 assertThat(
47- registry.codecFor(DataType.cint(), Integer.class)
452+ registry.codecFor(cint(), Integer.class)
48453 ).isNotSameAs(newCodec);
49454
50455 stopCapturingLogs(logs);
@@ -57,18 +462,15 @@
57462 CodecRegistry registry = new CodecRegistry();
58463
59464 // Force generation of a list token from the default token
60- registry.codecFor(DataType.list(DataType.cint()), LIST_OF_INT_TOKEN);
465+ registry.codecFor(list(cint()), listOf(Integer.class));
61466
62- TypeCodec newCodec = mock(TypeCodec.class);
63- when(newCodec.getCqlType()).thenReturn(DataType.list(DataType.cint()));
64- when(newCodec.getJavaType()).thenReturn(LIST_OF_INT_TOKEN);
65- when(newCodec.toString()).thenReturn("newCodec");
467+ TypeCodec newCodec = mockCodec(list(cint()), listOf(Integer.class));
66468
67469 registry.register(newCodec);
68470
69- assertThat(logs.getNext()).contains("Ignoring codec newCodec");
471+ assertThat(logs.getNext()).contains("Ignoring codec MockCodec");
70472 assertThat(
71- registry.codecFor(DataType.list(DataType.cint()), LIST_OF_INT_TOKEN)
473+ registry.codecFor(list(cint()), listOf(Integer.class))
72474 ).isNotSameAs(newCodec);
73475
74476 stopCapturingLogs(logs);
@@ -87,4 +489,15 @@
87489 registryLogger.setLevel(null);
88490 registryLogger.removeAppender(logs);
89491 }
90-}
No newline at the end of the file
492+
493+ private TypeCodec<?> mockCodec(DataType cqlType, TypeToken<?> javaType) {
494+ TypeCodec newCodec = mock(TypeCodec.class);
495+ when(newCodec.getCqlType()).thenReturn(cqlType);
496+ when(newCodec.getJavaType()).thenReturn(javaType);
497+ when(newCodec.accepts(cqlType)).thenReturn(true);
498+ when(newCodec.accepts(javaType)).thenReturn(true);
499+ when(newCodec.toString()).thenReturn(String.format("MockCodec [%s <-> %s]", cqlType, javaType));
500+ return newCodec;
501+ }
502+
503+}
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecAssert.java +28 −24
@@ -21,62 +21,66 @@
2121 import static org.assertj.core.api.Assertions.assertThat;
2222 import static org.assertj.core.api.Fail.fail;
2323
24-/**
25- */
2624 @SuppressWarnings("unused")
27-public class TypeCodecAssert extends AbstractAssert<TypeCodecAssert, TypeCodec> {
25+public class TypeCodecAssert<T> extends AbstractAssert<TypeCodecAssert<T>, TypeCodec<T>> {
2826
2927 private ProtocolVersion version = TestUtils.getDesiredProtocolVersion();
3028
31- protected TypeCodecAssert(TypeCodec<?> actual) {
29+ protected TypeCodecAssert(TypeCodec<T> actual) {
3230 super(actual, TypeCodecAssert.class);
3331 }
3432
35- public TypeCodecAssert accepts(Class<?> clazz) {
36- return accepts(TypeToken.of(clazz));
33+ public TypeCodecAssert<T> accepts(TypeToken<?> javaType) {
34+ assertThat(actual.accepts(javaType)).as("Codec %s should accept %s but it does not", actual, javaType).isTrue();
35+ return this;
36+ }
37+
38+ public TypeCodecAssert<T> doesNotAccept(TypeToken<?> javaType) {
39+ assertThat(actual.accepts(javaType)).as("Codec %s should not accept %s but it does", actual, javaType).isFalse();
40+ return this;
3741 }
3842
39- public TypeCodecAssert accepts(TypeToken<?> javaType) {
40- assertThat(actual.accepts(javaType)).isTrue();
43+ public TypeCodecAssert<T> accepts(Class<?> javaType) {
44+ assertThat(actual.accepts(javaType)).as("Codec %s should accept %s but it does not", actual, javaType).isTrue();
4145 return this;
4246 }
4347
44- public TypeCodecAssert doesNotAccept(TypeToken<?> javaType) {
45- assertThat(actual.accepts(javaType)).isFalse();
48+ public TypeCodecAssert<T> doesNotAccept(Class<?> javaType) {
49+ assertThat(actual.accepts(javaType)).as("Codec %s should not accept %s but it does", actual, javaType).isFalse();
4650 return this;
4751 }
4852
49- public TypeCodecAssert accepts(Object value) {
53+ public TypeCodecAssert<T> accepts(Object value) {
5054 assertThat(actual.accepts(value)).as("Codec %s should accept %s but it does not", actual, value).isTrue();
5155 return this;
5256 }
5357
54- public TypeCodecAssert doesNotAccept(Object value) {
55- assertThat(actual.accepts(value)).isFalse();
58+ public TypeCodecAssert<T> doesNotAccept(Object value) {
59+ assertThat(actual.accepts(value)).as("Codec %s should not accept %s but it does", actual, value).isFalse();
5660 return this;
5761 }
5862
59- public TypeCodecAssert accepts(DataType cqlType) {
60- assertThat(actual.accepts(cqlType)).isTrue();
63+ public TypeCodecAssert<T> accepts(DataType cqlType) {
64+ assertThat(actual.accepts(cqlType)).as("Codec %s should accept %s but it does not", actual, cqlType).isTrue();
6165 return this;
6266 }
6367
64- public TypeCodecAssert doesNotAccept(DataType cqlType) {
65- assertThat(actual.accepts(cqlType)).isFalse();
68+ public TypeCodecAssert<T> doesNotAccept(DataType cqlType) {
69+ assertThat(actual.accepts(cqlType)).as("Codec %s should not accept %s but it does", actual, cqlType).isFalse();
6670 return this;
6771 }
6872
69- public TypeCodecAssert withProtocolVersion(ProtocolVersion version) {
73+ public TypeCodecAssert<T> withProtocolVersion(ProtocolVersion version) {
7074 if (version == null) fail("ProtocolVersion cannot be null");
7175 this.version = version;
7276 return this;
7377 }
7478
7579 @SuppressWarnings("unchecked")
76- public TypeCodecAssert canSerialize(Object value) {
80+ public TypeCodecAssert<T> canSerialize(Object value) {
7781 if (version == null) fail("ProtocolVersion cannot be null");
7882 try {
79- assertThat(actual.deserialize(actual.serialize(value, version), version)).isEqualTo(value);
83+ assertThat(actual.deserialize(actual.serialize((T) value, version), version)).isEqualTo(value);
8084 } catch (Exception e) {
8185 fail(String.format("Codec is supposed to serialize this value but it actually doesn't: %s", value), e);
8286 }
@@ -84,10 +88,10 @@
8488 }
8589
8690 @SuppressWarnings("unchecked")
87- public TypeCodecAssert cannotSerialize(Object value) {
91+ public TypeCodecAssert<T> cannotSerialize(Object value) {
8892 if (version == null) fail("ProtocolVersion cannot be null");
8993 try {
90- actual.serialize(value, version);
94+ actual.serialize((T) value, version);
9195 fail("Should not have been able to serialize " + value + " with " + actual);
9296 } catch (Exception e) {
9397 //ok
@@ -96,9 +100,9 @@
96100 }
97101
98102 @SuppressWarnings("unchecked")
99- public TypeCodecAssert cannotFormat(Object value) {
103+ public TypeCodecAssert<T> cannotFormat(Object value) {
100104 try {
101- actual.format(value);
105+ actual.format((T) value);
102106 fail("Should not have been able to format " + value + " with " + actual);
103107 } catch (Exception e) {
104108 // ok
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java +27 −0
@@ -272,6 +272,33 @@
272272 assertThat(formatted).isEqualTo("'2015-12-08T00:53:46.999+0000'");
273273 }
274274
275+ /**
276+ * Ensures that primitive types are correctly handled and wrapped when necessary.
277+ */
278+ @Test(groups = "unit")
279+ public void should_wrap_primitive_types() {
280+ assertThat(TypeCodec.cboolean())
281+ .accepts(Boolean.class)
282+ .accepts(Boolean.TYPE)
283+ .accepts(true);
284+ assertThat(TypeCodec.cint())
285+ .accepts(Integer.class)
286+ .accepts(Integer.TYPE)
287+ .accepts(42);
288+ assertThat(TypeCodec.bigint())
289+ .accepts(Long.class)
290+ .accepts(Long.TYPE)
291+ .accepts(42L);
292+ assertThat(TypeCodec.cfloat())
293+ .accepts(Float.class)
294+ .accepts(Float.TYPE)
295+ .accepts(42.0F);
296+ assertThat(TypeCodec.cdouble())
297+ .accepts(Double.class)
298+ .accepts(Double.TYPE)
299+ .accepts(42.0D);
300+ }
301+
275302 private class ListVarcharToListListInteger extends TypeCodec<List<List<Integer>>> {
276303
277304 private final TypeCodec<List<String>> codec = TypeCodec.list(TypeCodec.varchar());