Elffuss BraidHub

kikocis/java-driver public

9b39ff6a48bf · 29.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.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("2.1.0")
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 // Error message varies by C* version.
502 assertThat(e.getMessage()).isIn("Unknown identifier mainaddress", "Undefined column name mainaddress");
503 }
504 try {
505 mapper.get(user.getUserId());
506 fail("Expected InvalidQueryException");
507 } catch (InvalidQueryException e) {
508 // Error message varies by C* version.
509 assertThat(e.getMessage()).isIn("Undefined name mainaddress in selection clause", "Undefined column name mainaddress");
510 }
511 // trying to use a new mapper
512 try {
513 manager.mapper(User.class);
514 fail("Expected IllegalArgumentException");
515 } catch (IllegalArgumentException e) {
516 assertThat(e.getMessage()).isIn(String.format("Column mainaddress does not exist in table \"%s\".users", keyspace));
517 }
518 }
519
520 /**
521 * Ensures that if a UDT is altered after a {@link Mapper} is created that it no longer continues to work if
522 * the change made to the UDT is not compatible. A field is renamed in the UDT in this case, which is not a
523 * compatible change.
524 * <p/>
525 * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
526 * one cannot be created as a declared field is missing from the schema but is present in the class definition.
527 * <p/>
528 * Also verifies that a {@link TypeCodec} cannot be requested for the UDT as well.
529 *
530 * @jira_ticket JAVA-1126
531 * @test_category object_mapper
532 */
533 @Test(groups = "short")
534 public void should_throw_error_when_udt_is_altered_and_is_not_compatible_anymore() {
535 User user = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
536 MappingManager manager = new MappingManager(session());
537 Mapper<User> mapper = manager.mapper(User.class);
538 session().execute("ALTER TYPE address RENAME \"ZIP_code\" to zip_code");
539 // usage of stale mapper
540 try {
541 mapper.save(user);
542 fail("Expected CodecNotFoundException");
543 } catch (CodecNotFoundException e) {
544 // ok, codec could not be created
545 }
546 // insert manually to be able to test retrieval
547 session().execute("INSERT INTO users (user_id, name, mainaddress) VALUES (?, 'Paul', { street : '12 4th Street', zip_code : 12345 })", user.getUserId());
548 try {
549 mapper.get(user.getUserId());
550 fail("Expected CodecNotFoundException");
551 } catch (CodecNotFoundException e) {
552 // ok, codec could not be created
553 }
554 // trying to use a new mapper
555 try {
556 manager.mapper(User.class);
557 fail("Expected IllegalArgumentException");
558 } catch (IllegalArgumentException e) {
559 assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type \"%s\".address", keyspace));
560 }
561 try {
562 manager.udtCodec(Address.class);
563 fail("Expected IllegalArgumentException");
564 } catch (IllegalArgumentException e) {
565 assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type \"%s\".address", keyspace));
566 }
567 }
568
569 @UDT(name = "address")
570 public static class AddressUnknownField {
571
572 private String city;
573
574 private String street;
575
576 @Field(name = "ZIP_code", caseSensitive = true)
577 private int zipCode;
578
579 private Set<String> phones;
580
581 public String province;
582
583 public AddressUnknownField() {
584 }
585
586 public String getStreet() {
587 return street;
588 }
589
590 public void setStreet(String street) {
591 this.street = street;
592 }
593
594 public String getCity() {
595 return city;
596 }
597
598 public void setCity(String city) {
599 this.city = city;
600 }
601
602 public int getZipCode() {
603 return zipCode;
604 }
605
606 public void setZipCode(int zipCode) {
607 this.zipCode = zipCode;
608 }
609
610 public Set<String> getPhones() {
611 return phones;
612 }
613
614 public void setPhones(Set<String> phones) {
615 this.phones = phones;
616 }
617
618 public String getProvince() {
619 return province;
620 }
621
622 public void setProvince(String province) {
623 this.province = province;
624 }
625 }
626
627 /**
628 * Ensures that when attempting to create a {@link TypeCodec} from a class that has a field that does not exist in
629 * the UDT that an {@link IllegalArgumentException} is thrown.
630 *
631 * @jira_ticket JAVA-1126
632 * @test_category object_mapper
633 */
634 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
635 public void should_fail_to_create_codec_if_class_has_field_not_in_udt() {
636 MappingManager manager = new MappingManager(session());
637 manager.getUDTCodec(AddressUnknownField.class);
638 }
639
640 @UDT(name = "nonexistent")
641 public static class NonExistentUDT {
642 public String name;
643
644 public void setName(String name) {
645 this.name = name;
646 }
647
648 public String getName() {
649 return this.name;
650 }
651 }
652
653 /**
654 * Ensures that when attempting to create a {@link TypeCodec} from a class that has a {@link UDT} annotation with
655 * a name that doesn't exist in the current keyspace that an {@link IllegalArgumentException} is thrown.
656 *
657 * @jira_ticket JAVA-1126
658 * @test_category object_mapper
659 */
660 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
661 public void should_fail_to_create_codec_if_udt_does_not_exist() {
662 MappingManager manager = new MappingManager(session());
663 manager.getUDTCodec(NonExistentUDT.class);
664 }
665
666 @Table(name = "users")
667 public static class UserWithAddressUnknownField {
668 @PartitionKey
669 @Column(name = "user_id")
670 private UUID userId;
671
672 private String name;
673
674 @Frozen
675 private AddressUnknownField mainAddress;
676
677 @Column(name = "other_addresses")
678 @FrozenValue
679 private Map<String, Address> otherAddresses = Maps.newHashMap();
680
681 public UserWithAddressUnknownField() {
682 }
683
684 public UUID getUserId() {
685 return userId;
686 }
687
688 public void setUserId(UUID userId) {
689 this.userId = userId;
690 }
691
692 public String getName() {
693 return name;
694 }
695
696 public void setName(String name) {
697 this.name = name;
698 }
699
700 public AddressUnknownField getMainAddress() {
701 return mainAddress;
702 }
703
704 public void setMainAddress(AddressUnknownField address) {
705 this.mainAddress = address;
706 }
707
708 public Map<String, Address> getOtherAddresses() {
709 return otherAddresses;
710 }
711
712 public void setOtherAddresses(Map<String, Address> otherAddresses) {
713 this.otherAddresses = otherAddresses;
714 }
715
716 public void addOtherAddress(String name, Address address) {
717 this.otherAddresses.put(name, address);
718 }
719 }
720
721 /**
722 * Ensures that when attempting to create a {@link Mapper} from a class that has a field that is a class mapping to
723 * a user type that has a field that does not exist in that UDT that an {@link IllegalArgumentException} is thrown.
724 *
725 * @jira_ticket JAVA-1126
726 * @test_category object_mapper
727 */
728 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
729 public void should_fail_to_create_mapper_if_class_has_udt_field_class_that_has_field_not_in_udt() {
730 MappingManager manager = new MappingManager(session());
731 manager.mapper(UserWithAddressUnknownField.class);
732 }
733
734 /**
735 * Ensures that MappedUDTCodec is able to properly format UDTs when printing the query string of a BuiltStatement.
736 *
737 * @jira_ticket JAVA-1272
738 * @test_category object_mapper
739 */
740 @Test(groups = "short")
741 public void should_format_mapped_udt() throws Exception {
742 MappingManager manager = new MappingManager(session());
743 UUID uuid = UUIDs.random();
744 BuiltStatement update =
745 update("users")
746 .with(set("mainaddress", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245")))
747 .where(eq("user_id", uuid));
748 CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
749 codecRegistry.register(manager.udtCodec(Address.class));
750 String queryString = update.getQueryString(codecRegistry);
751 assertThat(queryString)
752 .isEqualTo("UPDATE users SET mainaddress=? WHERE user_id=?;");
753 update.setForceNoValues(true);
754 queryString = update.getQueryString(codecRegistry);
755 assertThat(queryString).isEqualTo(
756 "UPDATE users " +
757 "SET mainaddress={street:'12 4th Street',city:'Springfield',\"ZIP_code\":12345,phones:{'435423245','12341343'}} " +
758 "WHERE user_id=" + uuid + ";");
759 // check that the query string is valid
760 session().execute(queryString);
761 }
762
763 /**
764 * Ensures that MappedUDTCodec is able to properly parse UDTs.
765 *
766 * @jira_ticket JAVA-1272
767 * @test_category object_mapper
768 */
769 @Test(groups = "short")
770 public void should_parse_mapped_udt() throws Exception {
771 MappingManager manager = new MappingManager(session());
772 TypeCodec<Address> codec = manager.udtCodec(Address.class);
773 Address actual = codec.parse("{street:'12 4th Street',city:'Springfield',\"ZIP_code\":12345,phones:{'435423245','12341343'}}");
774 assertThat(actual).isEqualTo(new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
775 }
776
777}