Elffuss BraidHub

kikocis/java-driver public

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