Elffuss BraidHub

kikocis/java-driver public

3.1.x · 19.2 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2015 DataStax Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.datastax.driver.mapping;
17
18import com.datastax.driver.core.*;
19import com.datastax.driver.core.exceptions.InvalidTypeException;
20import com.datastax.driver.core.utils.CassandraVersion;
21import com.datastax.driver.mapping.annotations.*;
22import com.google.common.base.Optional;
23import com.google.common.base.Predicate;
24import com.google.common.collect.ImmutableMap;
25import com.google.common.reflect.TypeParameter;
26import com.google.common.reflect.TypeToken;
27import org.testng.annotations.Test;
28
29import java.nio.ByteBuffer;
30import java.util.Collection;
31import java.util.Map;
32
33import static org.assertj.core.api.Assertions.assertThat;
34import static org.assertj.core.api.Assertions.fail;
35
36@CassandraVersion("2.1.0")
37@SuppressWarnings("unused")
38public class MapperCustomCodecTest extends CCMTestsSupport {
39
40 @Override
41 public void onTestContextInitialized() {
42 execute(
43 // Columns mapped to custom types
44 "CREATE TABLE data1 (i int PRIMARY KEY, l bigint)",
45 "INSERT INTO data1 (i, l) VALUES (1, 11)",
46
47 // UDT fields mapped to custom types
48 "CREATE TYPE holder(i int, l bigint)",
49 "CREATE TABLE data2(i int primary key, data frozen<holder>)",
50 "INSERT INTO data2 (i, data) values (1, {i: 1, l: 11})",
51
52 // nested UDT
53 // both UDT fields and non-UDT elements in the collection are mapped to custom types
54 "CREATE TABLE data3(i int primary key, data map<int, frozen<holder>>)",
55 "INSERT INTO data3 (i, data) values (1, {1: {i: 1, l: 11}})"
56 );
57 }
58
59 @Override
60 public Cluster.Builder createClusterBuilder() {
61 return Cluster.builder().withCodecRegistry(new CodecRegistry()
62 .register(new CustomInt.Codec()));
63 }
64
65 @Test(groups = "short")
66 public void should_use_custom_codecs_with_basic_operations() {
67 Mapper<Data1> mapper = new MappingManager(session()).mapper(Data1.class);
68
69 // Get
70 Data1 data11 = mapper.get(new CustomInt(1));
71 assertThat(data11.getI()).isEqualTo(new CustomInt(1));
72 assertThat(data11.getL()).isEqualTo(new CustomLong(11));
73
74 // Save
75 Data1 data12 = new Data1();
76 data12.setI(new CustomInt(2));
77 data12.setL(new CustomLong(12));
78 mapper.save(data12);
79
80 Row row = session().execute("select * from data1 where i = 2").one();
81 assertThat(row.getInt(0)).isEqualTo(2);
82 assertThat(row.getLong(1)).isEqualTo(12);
83
84 // Delete
85 mapper.delete(new CustomInt(2));
86 row = session().execute("select * from data1 where i = 2").one();
87 assertThat(row).isNull();
88 }
89
90 @Test(groups = "short")
91 public void should_use_custom_codecs_with_accessors() {
92 Data1Accessor accessor = new MappingManager(session()).createAccessor(Data1Accessor.class);
93 Data1 data1 = accessor.get(new CustomInt(1));
94 assertThat(data1.getI()).isEqualTo(new CustomInt(1));
95 assertThat(data1.getL()).isEqualTo(new CustomLong(11));
96
97 accessor.setL(1, new CustomLong(12));
98 Row row = session().execute("select l from data1 where i = 1").one();
99 assertThat(row.getLong(0)).isEqualTo(12);
100
101 accessor.setL(1, new CustomLong(11));
102 }
103
104 @Test(groups = "short")
105 public void should_use_custom_codecs_in_UDTs() {
106 Mapper<Data2> mapper = new MappingManager(session()).mapper(Data2.class);
107
108 // Get
109 Data2 data21 = mapper.get(1);
110 assertThat(data21.getData().getI()).isEqualTo(new CustomInt(1));
111 assertThat(data21.getData().getL()).isEqualTo(new CustomLong(11));
112
113 // Save
114 Data2 data22 = new Data2();
115 data22.setI(2);
116 data22.setData(new Holder(2, 22));
117 mapper.save(data22);
118
119 Row row = session().execute("select * from data2 where i = 2").one();
120 assertThat(row.getUDTValue(1).getInt("i")).isEqualTo(2);
121 assertThat(row.getUDTValue(1).getLong("l")).isEqualTo(22);
122
123 // cleanup
124 mapper.delete(2);
125 }
126
127 @Test(groups = "short")
128 public void should_use_custom_codecs_in_nested_structures() {
129 Mapper<Data3> mapper = new MappingManager(session()).mapper(Data3.class);
130
131 // Get
132 Data3 data31 = mapper.get(1);
133 assertThat(data31.getData().containsKey(new CustomInt(1)));
134 assertThat(data31.getData().get(new CustomInt(1)).getI()).isEqualTo(new CustomInt(1));
135
136 // Save
137 Data3 data32 = new Data3();
138 data32.setI(2);
139 data32.setData(ImmutableMap.of(new CustomInt(2), new Holder(2, 22)));
140 mapper.save(data32);
141
142 Row row = session().execute("select * from data3 where i = 2").one();
143 Map<Integer, UDTValue> data = row.getMap(1, Integer.class, UDTValue.class);
144 assertThat(data.containsKey(2));
145 assertThat(data.get(2).getInt("i")).isEqualTo(2);
146 assertThat(data.get(2).getLong("l")).isEqualTo(22);
147
148 // cleanup
149 mapper.delete(2);
150 }
151
152 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
153 public void should_fail_when_invalid_codec_with_no_default_ctor_provided() {
154 new MappingManager(session()).mapper(Data1InvalidCodecNoDefaultConstructor.class);
155 }
156
157 @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
158 public void should_fail_when_invalid_codec_type_mapping() {
159 Mapper<Data1InvalidCodecTypeMapping> mapper = new MappingManager(session()).mapper(Data1InvalidCodecTypeMapping.class);
160
161 // Get should return an InvalidTypeException.
162 try {
163 mapper.get(1);
164 fail("Should not have been able to retrieve.");
165 } catch (InvalidTypeException e) {
166 // expected.
167 }
168
169 // Set should also return an InvalidTypeException.
170 Data1InvalidCodecTypeMapping data12 = new Data1InvalidCodecTypeMapping();
171 data12.setI(2);
172 data12.setL(Optional.of(1L));
173 mapper.save(data12);
174 }
175
176 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
177 public void should_fail_when_invalid_codec_with_no_default_ctor_provided_in_accessor() {
178 new MappingManager(session()).createAccessor(Data1AccessorNoDefaultConstructor.class);
179 }
180
181 @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
182 public void should_fail_when_invalid_codec_type_mapping_in_accessor() {
183 Data1AccessorInvalidCodecTypeMapping accessor = new MappingManager(session()).createAccessor(Data1AccessorInvalidCodecTypeMapping.class);
184
185 // Get should return an InvalidTypeException.
186 try {
187 accessor.get(1);
188 fail("Should not have been able to retrieve.");
189 } catch (InvalidTypeException e) {
190 // expected.
191 }
192
193 accessor.setL(1, Optional.of(2L));
194 }
195
196 @Test(groups = "short")
197 public void should_be_able_to_use_parameterized_type() {
198 Mapper<Data1ParameterizedType> mapper = new MappingManager(session()).mapper(Data1ParameterizedType.class);
199
200 Data1ParameterizedType data1 = mapper.get(1);
201 assertThat(data1.getL()).isEqualTo(Optional.of(11L));
202
203 // Set with an absent ('null') value.
204 Data1ParameterizedType empty1 = new Data1ParameterizedType();
205 empty1.setI(1000);
206 empty1.setL(Optional.<Long>absent());
207 mapper.save(empty1);
208
209 // Value should come back absent.
210 Data1ParameterizedType empty1r = mapper.get(1000);
211 assertThat(empty1r.getL()).isEqualTo(Optional.<Long>absent());
212
213 // Value should come back absent with codec, otherwise null with getObject, 0 with getLong.
214 Row row = session().execute("select l from data1 where i=1000").one();
215 assertThat(row.getObject(0)).isEqualTo(null); // should map to long codec and return null.
216 assertThat(row.getLong(0)).isEqualTo(0L); // default boxed primitive value.
217 assertThat(row.get(0, new OptionalOfLong())).isEqualTo(Optional.<Long>absent());
218
219 // Set with a present value.
220 Data1ParameterizedType present1 = new Data1ParameterizedType();
221 present1.setI(1001);
222 present1.setL(Optional.of(20L));
223 mapper.save(present1);
224
225 // Value should come back present with codec, otherwise 20L.
226 row = session().execute("select l from data1 where i=1001").one();
227 assertThat(row.getObject(0)).isEqualTo(20L); // should map to long codec.
228 assertThat(row.getLong(0)).isEqualTo(20L);
229 assertThat(row.get(0, new OptionalOfLong())).isEqualTo(Optional.of(20L));
230 }
231
232 @Table(name = "data1")
233 public static class Data1 {
234 @PartitionKey
235 private CustomInt i;
236
237 @Column(codec = CustomLong.Codec.class)
238 private CustomLong l;
239
240 public CustomInt getI() {
241 return i;
242 }
243
244 public void setI(CustomInt i) {
245 this.i = i;
246 }
247
248 public CustomLong getL() {
249 return l;
250 }
251
252 public void setL(CustomLong l) {
253 this.l = l;
254 }
255 }
256
257 @Table(name = "data1")
258 public static class Data1InvalidCodecNoDefaultConstructor {
259
260 @PartitionKey
261 private int i;
262
263 @Column(codec = NoDefaultConstructorCodec.class)
264 private long l;
265
266 public int getI() {
267 return i;
268 }
269
270 public void setI(int i) {
271 this.i = i;
272 }
273
274 public long getL() {
275 return l;
276 }
277
278 public void setL(long l) {
279 this.l = l;
280 }
281 }
282
283 @Table(name = "data1")
284 public static class Data1InvalidCodecTypeMapping {
285
286 @PartitionKey
287 private int i;
288
289 @Column(codec = OptionalOfString.class)
290 private Optional<Long> l;
291
292 public int getI() {
293 return i;
294 }
295
296 public void setI(int i) {
297 this.i = i;
298 }
299
300 public Optional<Long> getL() {
301 return l;
302 }
303
304 public void setL(Optional<Long> l) {
305 this.l = l;
306 }
307 }
308
309 @Table(name = "data1")
310 public static class Data1ParameterizedType {
311
312 @PartitionKey
313 private int i;
314
315 @Column(codec = OptionalOfLong.class)
316 private Optional<Long> l;
317
318 public int getI() {
319 return i;
320 }
321
322 public void setI(int i) {
323 this.i = i;
324 }
325
326 public Optional<Long> getL() {
327 return l;
328 }
329
330 public void setL(Optional<Long> l) {
331 this.l = l;
332 }
333 }
334
335 @Accessor
336 public interface Data1Accessor {
337 @Query("select * from data1 where i = :i")
338 Data1 get(@Param("i") CustomInt i);
339
340 @Query("update data1 set l = :l where i = :i")
341 void setL(@Param("i") int i,
342 @Param(value = "l", codec = CustomLong.Codec.class) CustomLong l);
343 }
344
345 @Accessor
346 public interface Data1AccessorNoDefaultConstructor {
347
348 @Query("update data1 set l = :l where i = :i")
349 void setL(@Param("i") int i,
350 @Param(value = "l", codec = NoDefaultConstructorCodec.class) long l);
351 }
352
353 @Accessor
354 public interface Data1AccessorInvalidCodecTypeMapping {
355
356 @Query("select * from data1 where i = :i")
357 Data1InvalidCodecTypeMapping get(@Param("i") int i);
358
359 @Query("update data1 set l = :l where i = :i")
360 void setL(@Param("i") int i,
361 @Param(value = "l", codec = OptionalOfString.class) Optional<Long> l);
362 }
363
364 @UDT(name = "holder")
365 public static class Holder {
366 private CustomInt i;
367
368 @Field(codec = CustomLong.Codec.class)
369 private CustomLong l;
370
371 public Holder() {
372 }
373
374 public Holder(int i, long l) {
375 this.i = new CustomInt(i);
376 this.l = new CustomLong(l);
377 }
378
379 public CustomInt getI() {
380 return i;
381 }
382
383 public void setI(CustomInt i) {
384 this.i = i;
385 }
386
387 public CustomLong getL() {
388 return l;
389 }
390
391 public void setL(CustomLong l) {
392 this.l = l;
393 }
394 }
395
396 @Table(name = "data2")
397 public static class Data2 {
398 @PartitionKey
399 private int i;
400
401 @Frozen
402 private Holder data;
403
404 public int getI() {
405 return i;
406 }
407
408 public void setI(int i) {
409 this.i = i;
410 }
411
412 public Holder getData() {
413 return data;
414 }
415
416 public void setData(Holder data) {
417 this.data = data;
418 }
419 }
420
421 @Table(name = "data3")
422 public static class Data3 {
423 @PartitionKey
424 private int i;
425
426 @FrozenValue
427 private Map<CustomInt, Holder> data;
428
429 public int getI() {
430 return i;
431 }
432
433 public void setI(int i) {
434 this.i = i;
435 }
436
437 public Map<CustomInt, Holder> getData() {
438 return data;
439 }
440
441 public void setData(Map<CustomInt, Holder> data) {
442 this.data = data;
443 }
444 }
445
446 public static class CustomInt {
447 public final int value;
448
449 public CustomInt(int value) {
450 this.value = value;
451 }
452
453 @Override
454 public boolean equals(Object other) {
455 if (other instanceof CustomInt) {
456 CustomInt that = (CustomInt) other;
457 return this.value == that.value;
458 }
459 return false;
460 }
461
462 @Override
463 public int hashCode() {
464 return value;
465 }
466
467 public static class Codec extends TypeCodec<CustomInt> {
468 public Codec() {
469 super(DataType.cint(), CustomInt.class);
470 }
471
472 @Override
473 public ByteBuffer serialize(CustomInt value, ProtocolVersion protocolVersion) throws InvalidTypeException {
474 return TypeCodec.cint().serialize(value.value, protocolVersion);
475 }
476
477 @Override
478 public CustomInt deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
479 Integer i = TypeCodec.cint().deserialize(bytes, protocolVersion);
480 return new CustomInt(i);
481 }
482
483 @Override
484 public CustomInt parse(String value) throws InvalidTypeException {
485 throw new UnsupportedOperationException();
486 }
487
488 @Override
489 public String format(CustomInt value) throws InvalidTypeException {
490 throw new UnsupportedOperationException();
491 }
492 }
493 }
494
495 public static class CustomLong {
496 public final long value;
497
498 public CustomLong(long value) {
499 this.value = value;
500 }
501
502 @Override
503 public boolean equals(Object other) {
504 if (other instanceof CustomLong) {
505 CustomLong that = (CustomLong) other;
506 return this.value == that.value;
507 }
508 return false;
509 }
510
511 @Override
512 public int hashCode() {
513 return (int) (value ^ (value >>> 32));
514 }
515
516 public static class Codec extends TypeCodec<CustomLong> {
517 public Codec() {
518 super(DataType.bigint(), CustomLong.class);
519 }
520
521 @Override
522 public ByteBuffer serialize(CustomLong value, ProtocolVersion protocolVersion) throws InvalidTypeException {
523 return TypeCodec.bigint().serialize(value.value, protocolVersion);
524 }
525
526 @Override
527 public CustomLong deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
528 Long l = TypeCodec.bigint().deserialize(bytes, protocolVersion);
529 return new CustomLong(l);
530 }
531
532 @Override
533 public CustomLong parse(String value) throws InvalidTypeException {
534 throw new UnsupportedOperationException();
535 }
536
537 @Override
538 public String format(CustomLong value) throws InvalidTypeException {
539 throw new UnsupportedOperationException();
540 }
541 }
542 }
543
544 public static class OptionalOfLong extends OptionalCodec<Long> {
545 private static final CodecRegistry registry = new CodecRegistry();
546
547 public OptionalOfLong() {
548 super(registry.codecFor(DataType.bigint(), Long.class));
549 }
550 }
551
552 public static class OptionalOfString extends OptionalCodec<String> {
553
554 private static final CodecRegistry registry = new CodecRegistry();
555
556 public OptionalOfString() {
557 super(registry.codecFor(DataType.text(), String.class));
558 }
559 }
560
561 /**
562 * This class is a copy of GuavaOptionalCodec declared in the extras module,
563 * to avoid circular dependencies between Maven modules.
564 */
565 public static class OptionalCodec<T> extends MappingCodec<Optional<T>, T> {
566
567 private final Predicate<T> isAbsent;
568
569 public OptionalCodec(TypeCodec<T> codec) {
570 // @formatter:off
571 super(codec,
572 new TypeToken<Optional<T>>() {}.where(new TypeParameter<T>() {}, codec.getJavaType()));
573 // @formatter:on
574 this.isAbsent = new Predicate<T>() {
575 @Override
576 public boolean apply(T input) {
577 return input == null
578 || input instanceof Collection && ((Collection) input).isEmpty()
579 || input instanceof Map && ((Map) input).isEmpty();
580 }
581 };
582 }
583
584 @Override
585 protected Optional<T> deserialize(T value) {
586 return isAbsent(value) ? Optional.<T>absent() : Optional.fromNullable(value);
587 }
588
589 @Override
590 protected T serialize(Optional<T> value) {
591 return value.isPresent() ? value.get() : absentValue();
592 }
593
594 protected T absentValue() {
595 return null;
596 }
597
598 protected boolean isAbsent(T value) {
599 return isAbsent.apply(value);
600 }
601
602 }
603
604 private static class NoDefaultConstructorCodec extends TypeCodec<String> {
605
606 public NoDefaultConstructorCodec(DataType cqlType, Class<String> javaClass) {
607 super(cqlType, javaClass);
608 }
609
610 @Override
611 public ByteBuffer serialize(String value, ProtocolVersion protocolVersion) throws InvalidTypeException {
612 return null;
613 }
614
615 @Override
616 public String deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
617 return null;
618 }
619
620 @Override
621 public String parse(String value) throws InvalidTypeException {
622 return null;
623 }
624
625 @Override
626 public String format(String value) throws InvalidTypeException {
627 return null;
628 }
629
630 }
631
632}