Elffuss BraidHub

kikocis/java-driver public

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