Elffuss BraidHub

kikocis/java-driver public

ca32d97e3bd3 · 29.0 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.CodecNotFoundException;
20import com.datastax.driver.core.exceptions.InvalidQueryException;
21import com.datastax.driver.core.querybuilder.BuiltStatement;
22import com.datastax.driver.core.utils.CassandraVersion;
23import com.datastax.driver.core.utils.UUIDs;
24import com.datastax.driver.mapping.annotations.*;
25import com.google.common.base.Objects;
26import com.google.common.collect.Maps;
27import org.assertj.core.data.MapEntry;
28import org.testng.annotations.AfterMethod;
29import org.testng.annotations.BeforeMethod;
30import org.testng.annotations.Test;
31
32import java.util.*;
33
34import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
35import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
36import static org.assertj.core.api.Assertions.assertThat;
37import static org.assertj.core.api.Assertions.fail;
38import static org.testng.Assert.*;
39
40@SuppressWarnings({"unused", "WeakerAccess"})
41@CassandraVersion(major = 2.1)
42@CreateCCM(PER_METHOD)
43public class MapperUDTTest extends CCMTestsSupport {
44
45 @BeforeMethod(groups = "short")
46 public void createObjects() {
47 execute("CREATE TYPE address (street text, city text, \"ZIP_code\" int, phones set<text>)",
48 "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
49 }
50
51 @AfterMethod(groups = "short")
52 public void deleteObjects() {
53 execute("DROP TABLE IF EXISTS users",
54 "DROP TYPE IF EXISTS address");
55 }
56
57 @Table(name = "users",
58 readConsistency = "QUORUM",
59 writeConsistency = "QUORUM")
60 public static class User {
61 @PartitionKey
62 @Column(name = "user_id")
63 private UUID userId;
64
65 private String name;
66
67 @Frozen
68 private Address mainAddress;
69
70 @Column(name = "other_addresses")
71 @FrozenValue
72 private Map<String, Address> otherAddresses = Maps.newHashMap();
73
74 public User() {
75 }
76
77 public User(String name, Address address) {
78 this.userId = UUIDs.random();
79 this.name = name;
80 this.mainAddress = address;
81 this.otherAddresses = new HashMap<String, Address>();
82 }
83
84 public UUID getUserId() {
85 return userId;
86 }
87
88 public void setUserId(UUID userId) {
89 this.userId = userId;
90 }
91
92 public String getName() {
93 return name;
94 }
95
96 public void setName(String name) {
97 this.name = name;
98 }
99
100 public Address getMainAddress() {
101 return mainAddress;
102 }
103
104 public void setMainAddress(Address address) {
105 this.mainAddress = address;
106 }
107
108 public Map<String, Address> getOtherAddresses() {
109 return otherAddresses;
110 }
111
112 public void setOtherAddresses(Map<String, Address> otherAddresses) {
113 this.otherAddresses = otherAddresses;
114 }
115
116 public void addOtherAddress(String name, Address address) {
117 this.otherAddresses.put(name, address);
118 }
119
120 @Override
121 public boolean equals(Object other) {
122 if (this == other)
123 return true;
124 if (other instanceof User) {
125 User that = (User) other;
126 return Objects.equal(this.userId, that.userId) &&
127 Objects.equal(this.name, that.name) &&
128 Objects.equal(this.mainAddress, that.mainAddress) &&
129 Objects.equal(this.otherAddresses, that.otherAddresses);
130 }
131 return false;
132 }
133
134 @Override
135 public int hashCode() {
136 return Objects.hashCode(this.userId, this.name, this.mainAddress, this.otherAddresses);
137 }
138
139 @Override
140 public String toString() {
141 return Objects.toStringHelper(User.class)
142 .add("userId", userId)
143 .add("name", name)
144 .add("mainAddress", mainAddress)
145 .add("otherAddresses", otherAddresses)
146 .toString();
147 }
148 }
149
150 @UDT(name = "address")
151 public static class Address {
152
153 // Dummy constant to test that static fields are properly ignored
154 public static final int FOO = 1;
155
156 @Field // not strictly required, but we want to check that the annotation works without a name
157 private String city;
158
159 // Declared out of order compared to the UDT definition, to make sure that we serialize fields in the correct order (JAVA-884)
160 private String street;
161
162 @Field(name = "ZIP_code", caseSensitive = true)
163 private int zipCode;
164
165 private Set<String> phones;
166
167 public Address() {
168 }
169
170 public Address(String street, String city, int zipCode, String... phones) {
171 this.street = street;
172 this.city = city;
173 this.zipCode = zipCode;
174 this.phones = new HashSet<String>();
175 Collections.addAll(this.phones, phones);
176 }
177
178 public String getStreet() {
179 return street;
180 }
181
182 public void setStreet(String street) {
183 this.street = street;
184 }
185
186 public String getCity() {
187 return city;
188 }
189
190 public void setCity(String city) {
191 this.city = city;
192 }
193
194 public int getZipCode() {
195 return zipCode;
196 }
197
198 public void setZipCode(int zipCode) {
199 this.zipCode = zipCode;
200 }
201
202 public Set<String> getPhones() {
203 return phones;
204 }
205
206 public void setPhones(Set<String> phones) {
207 this.phones = phones;
208 }
209
210 @Override
211 public boolean equals(Object other) {
212 if (this == other)
213 return true;
214 if (other instanceof Address) {
215 Address that = (Address) other;
216 return Objects.equal(this.street, that.street) &&
217 Objects.equal(this.city, that.city) &&
218 Objects.equal(this.zipCode, that.zipCode) &&
219 Objects.equal(this.phones, that.phones);
220 }
221 return false;
222 }
223
224 @Override
225 public int hashCode() {
226 return Objects.hashCode(this.street, this.city, this.zipCode, this.phones);
227 }
228
229 @Override
230 public String toString() {
231 return Objects.toStringHelper(Address.class)
232 .add("street", street)
233 .add("city", city)
234 .add("zip", zipCode)
235 .add("phones", phones)
236 .toString();
237 }
238 }
239
240 @Accessor
241 public interface UserAccessor {
242 @Query("SELECT * FROM users WHERE user_id=:userId")
243 User getOne(@Param("userId") UUID userId);
244
245 @Query("UPDATE users SET other_addresses[:name]=:address WHERE user_id=:id")
246 ResultSet addAddress(@Param("id") UUID id, @Param("name") String addressName, @Param("address") Address address);
247
248 @Query("UPDATE users SET other_addresses=:addresses where user_id=:id")
249 ResultSet setOtherAddresses(@Param("id") UUID id, @Param("addresses") Map<String, Address> addresses);
250
251 @Query("SELECT * FROM users")
252 Result<User> getAll();
253 }
254
255 @Test(groups = "short")
256 public void testSimpleEntity() throws Exception {
257 Mapper<User> m = new MappingManager(session()).mapper(User.class);
258
259 User u1 = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
260 u1.addOtherAddress("work", new Address("5 Main Street", "Springfield", 12345, "23431342"));
261 m.save(u1);
262
263 assertEquals(m.get(u1.getUserId()), u1);
264 }
265
266 @Test(groups = "short")
267 public void should_handle_null_UDT_value() throws Exception {
268 Mapper<User> m = new MappingManager(session()).mapper(User.class);
269
270 User u1 = new User("Paul", null);
271 m.save(u1);
272
273 assertNull(m.get(u1.getUserId()).getMainAddress());
274 }
275
276 @Test(groups = "short")
277 public void testAccessor() throws Exception {
278 MappingManager manager = new MappingManager(session());
279
280 Mapper<User> m = new MappingManager(session()).mapper(User.class);
281 User u1 = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
282 m.save(u1);
283
284 UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
285
286 Address workAddress = new Address("5 Main Street", "Springfield", 12345, "23431342");
287 userAccessor.addAddress(u1.getUserId(), "work", workAddress);
288
289 User u2 = userAccessor.getOne(u1.getUserId());
290 assertEquals(workAddress, u2.getOtherAddresses().get("work"));
291
292 // Adding a null value should remove it from the list.
293 userAccessor.addAddress(u1.getUserId(), "work", null);
294 User u3 = userAccessor.getOne(u1.getUserId());
295 assertThat(u3.getOtherAddresses()).doesNotContainKey("work");
296
297 // Add a bunch of other addresses
298 Map<String, Address> otherAddresses = Maps.newHashMap();
299 otherAddresses.put("work", workAddress);
300 otherAddresses.put("cabin", new Address("42 Middle of Nowhere", "Lake of the Woods", 49553, "8675309"));
301
302 userAccessor.setOtherAddresses(u1.getUserId(), otherAddresses);
303 User u4 = userAccessor.getOne(u1.getUserId());
304 assertThat(u4.getOtherAddresses()).isEqualTo(otherAddresses);
305
306 // Nullify other addresses
307 userAccessor.setOtherAddresses(u1.getUserId(), null);
308 User u5 = userAccessor.getOne(u1.getUserId());
309 assertThat(u5.getOtherAddresses()).isEmpty();
310
311 // No argument call
312 Result<User> u = userAccessor.getAll();
313 assertEquals(u.one(), u5);
314 assertTrue(u.isExhausted());
315 }
316
317 @Test(groups = "short")
318 public void should_be_able_to_use_udtCodec_standalone() {
319 // Create a separate Cluster/Session to start with a CodecRegistry from scratch (so not already registered).
320 Cluster cluster = register(Cluster.builder()
321 .addContactPoints(getContactPoints())
322 .withPort(ccm().getBinaryPort())
323 .build());
324 CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
325 Session session = cluster.connect(keyspace);
326
327 UUID userId = UUIDs.random();
328
329 // Create a user.
330 session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', \"ZIP_code\": 89898, phones: {'8675309'}} " +
331 " WHERE user_id=" + TypeCodec.uuid().format(userId));
332 session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', \"ZIP_code\": 49553, phones: {'8675039'}} " +
333 " WHERE user_Id=" + TypeCodec.uuid().format(userId));
334
335 // Get the user.
336 Row row = session.execute("select * from users where user_id=?", userId).one();
337
338 UDTValue udtValue = row.getUDTValue("mainaddress");
339 assertThat(udtValue.getString("street")).isEqualTo("42 Middle of Nowhere");
340
341 Object udtObject = row.getObject("mainaddress");
342 assertThat(udtObject).isEqualTo(udtValue);
343
344 // There shouldn't be a codec for address.
345 try {
346 assertThat(registry.codecFor(udtValue.getType(), Address.class));
347 fail("Didn't expect to find codec for udtType <-> Address");
348 } catch (CodecNotFoundException e) {
349 // expected.
350 }
351
352 // Expect a this_udt <-> UDTValue codec to exist. This is a pretty safe bet or else we wouldn't get
353 // this value back.
354 TypeCodec<UDTValue> udtCodec = registry.codecFor(udtValue.getType());
355 assertThat(udtCodec.getCqlType()).isEqualTo(udtValue.getType());
356 assertThat(udtCodec.getJavaType().getRawType()).isEqualTo(UDTValue.class);
357
358 // Retrieve codec for Address, if it can be mapped it will be created, if already registered it'll be used.
359 TypeCodec<Address> codec = new MappingManager(session).udtCodec(Address.class);
360
361 // The codec should be registered after we call udtCodec.
362 assertThat(registry.codecFor(udtValue.getType(), Address.class)).isEqualTo(codec);
363
364 // Should be able to retrieve as an Address.
365 Address mainAddress = row.get("mainaddress", Address.class);
366 assertThat(mainAddress.getCity()).isEqualTo("Lake of the Woods");
367 assertThat(mainAddress.getStreet()).isEqualTo("42 Middle of Nowhere");
368 assertThat(mainAddress.getZipCode()).isEqualTo(49553);
369 assertThat(mainAddress.getPhones()).containsExactly("8675039");
370
371 // Should be able to retrieve within a Map.
372 Address expectedOtherAddress = new Address();
373 expectedOtherAddress.setStreet("101 Ocean Ln");
374 expectedOtherAddress.setCity("Jacksonville, FL");
375 expectedOtherAddress.setZipCode(89898);
376 expectedOtherAddress.setPhones(Collections.singleton("8675309"));
377
378 Map<String, Address> otherAddresses = row.getMap("other_addresses", String.class, Address.class);
379 assertThat(otherAddresses).containsOnly(MapEntry.entry("condo", expectedOtherAddress));
380 }
381
382 /**
383 * Ensures that if a table is altered after a {@link Mapper} is created that it continues to work as long as
384 * the change is compatible. A new column is added to the table in this case, which is a compatible change.
385 * <p/>
386 * It also ensures that after the change is made that requesting a new {@link Mapper} returns a different instance
387 * instead of the existing one.
388 *
389 * @jira_ticket JAVA-1126
390 * @test_category object_mapper
391 */
392 @Test(groups = "short")
393 public void should_work_normally_when_when_table_is_altered_but_remains_compatible() {
394 MappingManager manager = new MappingManager(session());
395 User expected = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
396 Mapper<User> m = manager.mapper(User.class);
397 Mapper<User> m1 = manager.mapper(User.class);
398 assertThat(m1).isSameAs(m);
399 session().execute("ALTER TABLE users ADD foo text");
400 m.save(expected);
401 User retrieved = m.get(expected.getUserId());
402 assertThat(retrieved).isEqualTo(expected);
403
404 // Mapper should be recreated since table changed.
405 Mapper<User> m2 = manager.mapper(User.class);
406 assertThat(m2).isNotSameAs(m);
407 }
408
409 /**
410 * Ensures that if a UDT is altered after a {@link Mapper} is created that has a UDT that it continues to work as
411 * long as the change is compatible. A new field is added to the table in this case, which is a compatible change.
412 * <p/>
413 * It also ensures that after the change is made that requesting a new {@link TypeCodec} for that UDT and a new
414 * {@link Mapper} for a table using that UDT returns different instances instead of the existing ones.
415 *
416 * @jira_ticket JAVA-1126
417 * @test_category object_mapper
418 */
419 @Test(groups = "short")
420 public void should_work_normally_when_udt_is_altered_but_remains_compatible() {
421 MappingManager manager = new MappingManager(session());
422 User expected = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
423 Mapper<User> m = manager.mapper(User.class);
424 TypeCodec c = manager.udtCodec(Address.class);
425 TypeCodec c1 = manager.udtCodec(Address.class);
426 assertThat(c1).isSameAs(c);
427 session().execute("ALTER TYPE address ADD foo text");
428 m.save(expected);
429 User retrieved = m.get(expected.getUserId());
430 assertThat(retrieved).isEqualTo(expected);
431
432 // Codec should be recreated when requested since UDT and thus the table changed.
433 Mapper m2 = manager.mapper(User.class);
434 assertThat(m2).isNotSameAs(m);
435
436 // Codec should be recreated when requested since UDT changed.
437 TypeCodec c2 = manager.udtCodec(Address.class);
438 assertThat(c2).isNotSameAs(c);
439 }
440
441 /**
442 * Ensures that if a table is dropped after a {@link Mapper} is created that the {@link Mapper} can no longer
443 * successfully make queries and that attempting to create a new {@link Mapper} throws an
444 * {@link IllegalArgumentException}.
445 * <p/>
446 * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
447 * one cannot be created as the table has been dropped.
448 *
449 * @jira_ticket JAVA-1126
450 * @test_category object_mapper
451 */
452 @Test(groups = "short")
453 public void should_throw_error_when_table_is_dropped() {
454 User user = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
455 MappingManager manager = new MappingManager(session());
456 Mapper<User> mapper = manager.mapper(User.class);
457 session().execute("DROP TABLE users");
458 // usage of stale mapper
459 try {
460 mapper.save(user);
461 fail("Expected InvalidQueryException");
462 } catch (InvalidQueryException e) {
463 assertThat(e.getMessage()).contains("unconfigured", "users");
464 }
465 try {
466 mapper.get(user.getUserId());
467 fail("Expected InvalidQueryException");
468 } catch (InvalidQueryException e) {
469 assertThat(e.getMessage()).contains("unconfigured", "users");
470 }
471 // trying to use a new mapper
472 try {
473 manager.mapper(User.class);
474 fail("Expected IllegalArgumentException");
475 } catch (IllegalArgumentException e) {
476 assertThat(e.getMessage()).isEqualTo("Table or materialized view users does not exist in keyspace \"" + keyspace + "\"");
477 }
478 }
479
480 /**
481 * Ensures that if a table is altered after a {@link Mapper} is created that it no longer continues to work if
482 * the change is not compatible. A column is dropped from the table in this case, which is an incompatible change.
483 * <p/>
484 * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
485 * one cannot be created as a declared column is missing from the schema but is present in the class definition.
486 *
487 * @jira_ticket JAVA-1126
488 * @test_category object_mapper
489 */
490 @Test(groups = "short")
491 public void should_throw_error_when_table_is_altered_and_is_not_compatible_anymore() {
492 User user = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
493 MappingManager manager = new MappingManager(session());
494 Mapper<User> mapper = manager.mapper(User.class);
495 session().execute("ALTER TABLE users DROP mainaddress");
496 // usage of stale mapper
497 try {
498 mapper.save(user);
499 fail("Expected InvalidQueryException");
500 } catch (InvalidQueryException e) {
501 assertThat(e.getMessage()).isEqualTo("Unknown identifier mainaddress");
502 }
503 try {
504 mapper.get(user.getUserId());
505 fail("Expected InvalidQueryException");
506 } catch (InvalidQueryException e) {
507 assertThat(e.getMessage()).isEqualTo("Undefined name mainaddress in selection clause");
508 }
509 // trying to use a new mapper
510 try {
511 manager.mapper(User.class);
512 fail("Expected IllegalArgumentException");
513 } catch (IllegalArgumentException e) {
514 assertThat(e.getMessage()).isEqualTo(String.format("Column mainaddress does not exist in table \"%s\".users", keyspace));
515 }
516 }
517
518 /**
519 * Ensures that if a UDT is altered after a {@link Mapper} is created that it no longer continues to work if
520 * the change made to the UDT is not compatible. A field is renamed in the UDT in this case, which is not a
521 * compatible change.
522 * <p/>
523 * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
524 * one cannot be created as a declared field is missing from the schema but is present in the class definition.
525 * <p/>
526 * Also verifies that a {@link TypeCodec} cannot be requested for the UDT as well.
527 *
528 * @jira_ticket JAVA-1126
529 * @test_category object_mapper
530 */
531 @Test(groups = "short")
532 public void should_throw_error_when_udt_is_altered_and_is_not_compatible_anymore() {
533 User user = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
534 MappingManager manager = new MappingManager(session());
535 Mapper<User> mapper = manager.mapper(User.class);
536 session().execute("ALTER TYPE address RENAME \"ZIP_code\" to zip_code");
537 // usage of stale mapper
538 try {
539 mapper.save(user);
540 fail("Expected CodecNotFoundException");
541 } catch (CodecNotFoundException e) {
542 // ok, codec could not be created
543 }
544 // insert manually to be able to test retrieval
545 session().execute("INSERT INTO users (user_id, name, mainaddress) VALUES (?, 'Paul', { street : '12 4th Street', zip_code : 12345 })", user.getUserId());
546 try {
547 mapper.get(user.getUserId());
548 fail("Expected CodecNotFoundException");
549 } catch (CodecNotFoundException e) {
550 // ok, codec could not be created
551 }
552 // trying to use a new mapper
553 try {
554 manager.mapper(User.class);
555 fail("Expected IllegalArgumentException");
556 } catch (IllegalArgumentException e) {
557 assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type \"%s\".address", keyspace));
558 }
559 try {
560 manager.udtCodec(Address.class);
561 fail("Expected IllegalArgumentException");
562 } catch (IllegalArgumentException e) {
563 assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type \"%s\".address", keyspace));
564 }
565 }
566
567 @UDT(name = "address")
568 public static class AddressUnknownField {
569
570 private String city;
571
572 private String street;
573
574 @Field(name = "ZIP_code", caseSensitive = true)
575 private int zipCode;
576
577 private Set<String> phones;
578
579 public String province;
580
581 public AddressUnknownField() {
582 }
583
584 public String getStreet() {
585 return street;
586 }
587
588 public void setStreet(String street) {
589 this.street = street;
590 }
591
592 public String getCity() {
593 return city;
594 }
595
596 public void setCity(String city) {
597 this.city = city;
598 }
599
600 public int getZipCode() {
601 return zipCode;
602 }
603
604 public void setZipCode(int zipCode) {
605 this.zipCode = zipCode;
606 }
607
608 public Set<String> getPhones() {
609 return phones;
610 }
611
612 public void setPhones(Set<String> phones) {
613 this.phones = phones;
614 }
615
616 public String getProvince() {
617 return province;
618 }
619
620 public void setProvince(String province) {
621 this.province = province;
622 }
623 }
624
625
626 /**
627 * Ensures that when attempting to create a {@link TypeCodec} from a class that has a field that does not exist in
628 * the UDT that an {@link IllegalArgumentException} is thrown.
629 *
630 * @jira_ticket JAVA-1126
631 * @test_category object_mapper
632 */
633 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
634 public void should_fail_to_create_codec_if_class_has_field_not_in_udt() {
635 MappingManager manager = new MappingManager(session());
636 manager.getUDTCodec(AddressUnknownField.class);
637 }
638
639 @UDT(name = "nonexistent")
640 public static class NonExistentUDT {
641 public String name;
642
643 public void setName(String name) {
644 this.name = name;
645 }
646
647 public String getName() {
648 return this.name;
649 }
650 }
651
652 /**
653 * Ensures that when attempting to create a {@link TypeCodec} from a class that has a {@link UDT} annotation with
654 * a name that doesn't exist in the current keyspace that an {@link IllegalArgumentException} is thrown.
655 *
656 * @jira_ticket JAVA-1126
657 * @test_category object_mapper
658 */
659 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
660 public void should_fail_to_create_codec_if_udt_does_not_exist() {
661 MappingManager manager = new MappingManager(session());
662 manager.getUDTCodec(NonExistentUDT.class);
663 }
664
665 @Table(name = "users")
666 public static class UserWithAddressUnknownField {
667 @PartitionKey
668 @Column(name = "user_id")
669 private UUID userId;
670
671 private String name;
672
673 @Frozen
674 private AddressUnknownField mainAddress;
675
676 @Column(name = "other_addresses")
677 @FrozenValue
678 private Map<String, Address> otherAddresses = Maps.newHashMap();
679
680 public UserWithAddressUnknownField() {
681 }
682
683 public UUID getUserId() {
684 return userId;
685 }
686
687 public void setUserId(UUID userId) {
688 this.userId = userId;
689 }
690
691 public String getName() {
692 return name;
693 }
694
695 public void setName(String name) {
696 this.name = name;
697 }
698
699 public AddressUnknownField getMainAddress() {
700 return mainAddress;
701 }
702
703 public void setMainAddress(AddressUnknownField address) {
704 this.mainAddress = address;
705 }
706
707 public Map<String, Address> getOtherAddresses() {
708 return otherAddresses;
709 }
710
711 public void setOtherAddresses(Map<String, Address> otherAddresses) {
712 this.otherAddresses = otherAddresses;
713 }
714
715 public void addOtherAddress(String name, Address address) {
716 this.otherAddresses.put(name, address);
717 }
718 }
719
720 /**
721 * Ensures that when attempting to create a {@link Mapper} from a class that has a field that is a class mapping to
722 * a user type that has a field that does not exist in that UDT that an {@link IllegalArgumentException} is thrown.
723 *
724 * @jira_ticket JAVA-1126
725 * @test_category object_mapper
726 */
727 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
728 public void should_fail_to_create_mapper_if_class_has_udt_field_class_that_has_field_not_in_udt() {
729 MappingManager manager = new MappingManager(session());
730 manager.mapper(UserWithAddressUnknownField.class);
731 }
732
733 /**
734 * Ensures that MappedUDTCodec is able to properly format UDTs when printing the query string of a BuiltStatement.
735 *
736 * @jira_ticket JAVA-1272
737 * @test_category object_mapper
738 */
739 @Test(groups = "short")
740 public void should_format_mapped_udt() throws Exception {
741 MappingManager manager = new MappingManager(session());
742 UUID uuid = UUIDs.random();
743 BuiltStatement update =
744 update("users")
745 .with(set("mainaddress", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245")))
746 .where(eq("user_id", uuid));
747 CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
748 codecRegistry.register(manager.udtCodec(Address.class));
749 String queryString = update.getQueryString(codecRegistry);
750 assertThat(queryString)
751 .isEqualTo("UPDATE users SET mainaddress=? WHERE user_id=?;");
752 update.setForceNoValues(true);
753 queryString = update.getQueryString(codecRegistry);
754 assertThat(queryString).isEqualTo(
755 "UPDATE users " +
756 "SET mainaddress={street:'12 4th Street',city:'Springfield',\"ZIP_code\":12345,phones:{'435423245','12341343'}} " +
757 "WHERE user_id=" + uuid + ";");
758 // check that the query string is valid
759 session().execute(queryString);
760 }
761
762 /**
763 * Ensures that MappedUDTCodec is able to properly parse UDTs.
764 *
765 * @jira_ticket JAVA-1272
766 * @test_category object_mapper
767 */
768 @Test(groups = "short")
769 public void should_parse_mapped_udt() throws Exception {
770 MappingManager manager = new MappingManager(session());
771 TypeCodec<Address> codec = manager.udtCodec(Address.class);
772 Address actual = codec.parse("{street:'12 4th Street',city:'Springfield',\"ZIP_code\":12345,phones:{'435423245','12341343'}}");
773 assertThat(actual).isEqualTo(new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
774 }
775
776}