| 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 | */ |
| 16 | package com.datastax.driver.mapping; |
| 17 | |
| 18 | import java.util.*; |
| 19 | |
| 20 | import com.datastax.driver.core.*; |
| 21 | import com.datastax.driver.core.exceptions.CodecNotFoundException; |
| 22 | import com.google.common.collect.Maps; |
| 23 | import org.assertj.core.data.MapEntry; |
| 24 | import org.testng.annotations.BeforeMethod; |
| 25 | |
| 26 | import com.google.common.base.Objects; |
| 27 | import org.testng.annotations.Test; |
| 28 | |
| 29 | import static org.assertj.core.api.Assertions.assertThat; |
| 30 | import static org.assertj.core.api.Assertions.fail; |
| 31 | import static org.testng.Assert.assertEquals; |
| 32 | import static org.testng.Assert.assertNull; |
| 33 | import static org.testng.Assert.assertTrue; |
| 34 | |
| 35 | import com.datastax.driver.core.utils.UUIDs; |
| 36 | |
| 37 | import com.datastax.driver.mapping.annotations.*; |
| 38 | |
| 39 | public class MapperUDTTest extends CCMBridge.PerClassSingleNodeCluster { |
| 40 | |
| 41 | protected Collection<String> getTableDefinitions() { |
| 42 | return Arrays.asList("CREATE TYPE address (street text, city text, \"ZIP_code\" int, phones set<text>)", |
| 43 | "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)"); |
| 44 | } |
| 45 | |
| 46 | @BeforeMethod(groups = "short") |
| 47 | public void clean() { |
| 48 | session.execute("TRUNCATE users"); |
| 49 | } |
| 50 | |
| 51 | @Table(name = "users", |
| 52 | readConsistency = "QUORUM", |
| 53 | writeConsistency = "QUORUM") |
| 54 | public static class User { |
| 55 | @PartitionKey |
| 56 | @Column(name = "user_id") |
| 57 | private UUID userId; |
| 58 | |
| 59 | private String name; |
| 60 | |
| 61 | @Frozen |
| 62 | private Address mainAddress; |
| 63 | |
| 64 | @Column(name = "other_addresses") |
| 65 | @FrozenValue |
| 66 | private Map<String, Address> otherAddresses = Maps.newHashMap(); |
| 67 | |
| 68 | public User() { |
| 69 | } |
| 70 | |
| 71 | public User(String name, Address address) { |
| 72 | this.userId = UUIDs.random(); |
| 73 | this.name = name; |
| 74 | this.mainAddress = address; |
| 75 | this.otherAddresses = new HashMap<String, Address>(); |
| 76 | } |
| 77 | |
| 78 | public UUID getUserId() { |
| 79 | return userId; |
| 80 | } |
| 81 | |
| 82 | public void setUserId(UUID userId) { |
| 83 | this.userId = userId; |
| 84 | } |
| 85 | |
| 86 | public String getName() { |
| 87 | return name; |
| 88 | } |
| 89 | |
| 90 | public void setName(String name) { |
| 91 | this.name = name; |
| 92 | } |
| 93 | |
| 94 | public Address getMainAddress() { |
| 95 | return mainAddress; |
| 96 | } |
| 97 | |
| 98 | public void setMainAddress(Address address) { |
| 99 | this.mainAddress = address; |
| 100 | } |
| 101 | |
| 102 | public Map<String, Address> getOtherAddresses() { |
| 103 | return otherAddresses; |
| 104 | } |
| 105 | |
| 106 | public void setOtherAddresses(Map<String, Address> otherAddresses) { |
| 107 | this.otherAddresses = otherAddresses; |
| 108 | } |
| 109 | |
| 110 | public void addOtherAddress(String name, Address address) { |
| 111 | this.otherAddresses.put(name, address); |
| 112 | } |
| 113 | |
| 114 | @Override |
| 115 | public boolean equals(Object other) { |
| 116 | if (this == other) |
| 117 | return true; |
| 118 | if (other instanceof User) { |
| 119 | User that = (User) other; |
| 120 | return Objects.equal(this.userId, that.userId) && |
| 121 | Objects.equal(this.name, that.name) && |
| 122 | Objects.equal(this.mainAddress, that.mainAddress) && |
| 123 | Objects.equal(this.otherAddresses, that.otherAddresses); |
| 124 | } |
| 125 | return false; |
| 126 | } |
| 127 | |
| 128 | @Override |
| 129 | public int hashCode() { |
| 130 | return Objects.hashCode(this.userId, this.name, this.mainAddress, this.otherAddresses); |
| 131 | } |
| 132 | |
| 133 | @Override |
| 134 | public String toString() { |
| 135 | return Objects.toStringHelper(User.class) |
| 136 | .add("userId", userId) |
| 137 | .add("name", name) |
| 138 | .add("mainAddress", mainAddress) |
| 139 | .add("otherAddresses", otherAddresses) |
| 140 | .toString(); |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | @UDT(name = "address") |
| 145 | public static class Address { |
| 146 | |
| 147 | // Dummy constant to test that static fields are properly ignored |
| 148 | public static final int FOO = 1; |
| 149 | |
| 150 | @Field // not strictly required, but we want to check that the annotation works without a name |
| 151 | private String city; |
| 152 | |
| 153 | // Declared out of order compared to the UDT definition, to make sure that we serialize fields in the correct order (JAVA-884) |
| 154 | private String street; |
| 155 | |
| 156 | @Field(name = "ZIP_code", caseSensitive = true) |
| 157 | private int zipCode; |
| 158 | |
| 159 | private Set<String> phones; |
| 160 | |
| 161 | public Address() { |
| 162 | } |
| 163 | |
| 164 | public Address(String street, String city, int zipCode, String... phones) { |
| 165 | this.street = street; |
| 166 | this.city = city; |
| 167 | this.zipCode = zipCode; |
| 168 | this.phones = new HashSet<String>(); |
| 169 | for (String phone : phones) { |
| 170 | this.phones.add(phone); |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | public String getStreet() { |
| 175 | return street; |
| 176 | } |
| 177 | |
| 178 | public void setStreet(String street) { |
| 179 | this.street = street; |
| 180 | } |
| 181 | |
| 182 | public String getCity() { |
| 183 | return city; |
| 184 | } |
| 185 | |
| 186 | public void setCity(String city) { |
| 187 | this.city = city; |
| 188 | } |
| 189 | |
| 190 | public int getZipCode() { |
| 191 | return zipCode; |
| 192 | } |
| 193 | |
| 194 | public void setZipCode(int zipCode) { |
| 195 | this.zipCode = zipCode; |
| 196 | } |
| 197 | |
| 198 | public Set<String> getPhones() { |
| 199 | return phones; |
| 200 | } |
| 201 | |
| 202 | public void setPhones(Set<String> phones) { |
| 203 | this.phones = phones; |
| 204 | } |
| 205 | |
| 206 | @Override |
| 207 | public boolean equals(Object other) { |
| 208 | if (this == other) |
| 209 | return true; |
| 210 | if (other instanceof Address) { |
| 211 | Address that = (Address) other; |
| 212 | return Objects.equal(this.street, that.street) && |
| 213 | Objects.equal(this.city, that.city) && |
| 214 | Objects.equal(this.zipCode, that.zipCode) && |
| 215 | Objects.equal(this.phones, that.phones); |
| 216 | } |
| 217 | return false; |
| 218 | } |
| 219 | |
| 220 | @Override |
| 221 | public int hashCode() { |
| 222 | return Objects.hashCode(this.street, this.city, this.zipCode, this.phones); |
| 223 | } |
| 224 | |
| 225 | @Override |
| 226 | public String toString() { |
| 227 | return Objects.toStringHelper(Address.class) |
| 228 | .add("street", street) |
| 229 | .add("city", city) |
| 230 | .add("zip", zipCode) |
| 231 | .add("phones", phones) |
| 232 | .toString(); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | @Accessor |
| 237 | public interface UserAccessor { |
| 238 | @Query("SELECT * FROM users WHERE user_id=:userId") |
| 239 | User getOne(@Param("userId") UUID userId); |
| 240 | |
| 241 | @Query("UPDATE users SET other_addresses[:name]=:address WHERE user_id=:id") |
| 242 | ResultSet addAddress(@Param("id") UUID id, @Param("name") String addressName, @Param("address") Address address); |
| 243 | |
| 244 | @Query("UPDATE users SET other_addresses=:addresses where user_id=:id") |
| 245 | ResultSet setOtherAddresses(@Param("id") UUID id, @Param("addresses") Map<String, Address> addresses); |
| 246 | |
| 247 | @Query("SELECT * FROM users") |
| 248 | public Result<User> getAll(); |
| 249 | } |
| 250 | |
| 251 | @Test(groups = "short") |
| 252 | public void testSimpleEntity() throws Exception { |
| 253 | Mapper<User> m = new MappingManager(session).mapper(User.class); |
| 254 | |
| 255 | User u1 = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245")); |
| 256 | u1.addOtherAddress("work", new Address("5 Main Street", "Springfield", 12345, "23431342")); |
| 257 | m.save(u1); |
| 258 | |
| 259 | assertEquals(m.get(u1.getUserId()), u1); |
| 260 | } |
| 261 | |
| 262 | @Test(groups = "short") |
| 263 | public void should_handle_null_UDT_value() throws Exception { |
| 264 | Mapper<User> m = new MappingManager(session).mapper(User.class); |
| 265 | |
| 266 | User u1 = new User("Paul", null); |
| 267 | m.save(u1); |
| 268 | |
| 269 | assertNull(m.get(u1.getUserId()).getMainAddress()); |
| 270 | } |
| 271 | |
| 272 | @Test(groups = "short") |
| 273 | public void testAccessor() throws Exception { |
| 274 | MappingManager manager = new MappingManager(session); |
| 275 | |
| 276 | Mapper<User> m = new MappingManager(session).mapper(User.class); |
| 277 | User u1 = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245")); |
| 278 | m.save(u1); |
| 279 | |
| 280 | UserAccessor userAccessor = manager.createAccessor(UserAccessor.class); |
| 281 | |
| 282 | Address workAddress = new Address("5 Main Street", "Springfield", 12345, "23431342"); |
| 283 | userAccessor.addAddress(u1.getUserId(), "work", workAddress); |
| 284 | |
| 285 | User u2 = userAccessor.getOne(u1.getUserId()); |
| 286 | assertEquals(workAddress, u2.getOtherAddresses().get("work")); |
| 287 | |
| 288 | // Adding a null value should remove it from the list. |
| 289 | userAccessor.addAddress(u1.getUserId(), "work", null); |
| 290 | User u3 = userAccessor.getOne(u1.getUserId()); |
| 291 | assertThat(u3.getOtherAddresses()).doesNotContainKey("work"); |
| 292 | |
| 293 | // Add a bunch of other addresses |
| 294 | Map<String, Address> otherAddresses = Maps.newHashMap(); |
| 295 | otherAddresses.put("work", workAddress); |
| 296 | otherAddresses.put("cabin", new Address("42 Middle of Nowhere", "Lake of the Woods", 49553, "8675309")); |
| 297 | |
| 298 | userAccessor.setOtherAddresses(u1.getUserId(), otherAddresses); |
| 299 | User u4 = userAccessor.getOne(u1.getUserId()); |
| 300 | assertThat(u4.getOtherAddresses()).isEqualTo(otherAddresses); |
| 301 | |
| 302 | // Nullify other addresses |
| 303 | userAccessor.setOtherAddresses(u1.getUserId(), null); |
| 304 | User u5 = userAccessor.getOne(u1.getUserId()); |
| 305 | assertThat(u5.getOtherAddresses()).isEmpty(); |
| 306 | |
| 307 | // No argument call |
| 308 | Result<User> u = userAccessor.getAll(); |
| 309 | assertEquals(u.one(), u5); |
| 310 | assertTrue(u.isExhausted()); |
| 311 | } |
| 312 | |
| 313 | @Test(groups = "short") |
| 314 | public void should_be_able_to_use_udtCodec_standalone() { |
| 315 | // Create a separate Cluster/Session to start with a CodecRegistry from scratch (so not already registered). |
| 316 | Cluster cluster = Cluster.builder().addContactPointsWithPorts(Collections.singleton(hostAddress)).build(); |
| 317 | try { |
| 318 | CodecRegistry registry = cluster.getConfiguration().getCodecRegistry(); |
| 319 | Session session = cluster.connect(keyspace); |
| 320 | |
| 321 | UUID userId = UUIDs.random(); |
| 322 | |
| 323 | // Create a user. |
| 324 | session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', \"ZIP_code\": 89898, phones: {'8675309'}} " + |
| 325 | " WHERE user_id=" + TypeCodec.uuid().format(userId)); |
| 326 | session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', \"ZIP_code\": 49553, phones: {'8675039'}} " + |
| 327 | " WHERE user_Id=" + TypeCodec.uuid().format(userId)); |
| 328 | |
| 329 | // Get the user. |
| 330 | Row row = session.execute("select * from users where user_id=?", userId).one(); |
| 331 | |
| 332 | UDTValue udtValue = row.getUDTValue("mainaddress"); |
| 333 | assertThat(udtValue.getString("street")).isEqualTo("42 Middle of Nowhere"); |
| 334 | |
| 335 | Object udtObject = row.getObject("mainaddress"); |
| 336 | assertThat(udtObject).isEqualTo(udtValue); |
| 337 | |
| 338 | // There shouldn't be a codec for address. |
| 339 | try { |
| 340 | assertThat(registry.codecFor(udtValue.getType(), Address.class)); |
| 341 | fail("Didn't expect to find codec for udtType <-> Address"); |
| 342 | } catch (CodecNotFoundException e) { |
| 343 | // expected. |
| 344 | } |
| 345 | |
| 346 | // Expect a this_udt <-> UDTValue codec to exist. This is a pretty safe bet or else we wouldn't get |
| 347 | // this value back. |
| 348 | TypeCodec<UDTValue> udtCodec = registry.codecFor(udtValue.getType()); |
| 349 | assertThat(udtCodec.getCqlType()).isEqualTo(udtValue.getType()); |
| 350 | assertThat(udtCodec.getJavaType().getRawType()).isEqualTo(UDTValue.class); |
| 351 | |
| 352 | // Retrieve codec for Address, if it can be mapped it will be created, if already registered it'll be used. |
| 353 | TypeCodec<Address> codec = new MappingManager(session).udtCodec(Address.class); |
| 354 | |
| 355 | // The codec should be registered after we call udtCodec. |
| 356 | assertThat(registry.codecFor(udtValue.getType(), Address.class)).isEqualTo(codec); |
| 357 | |
| 358 | // Should be able to retrieve as an Address. |
| 359 | Address mainAddress = row.get("mainaddress", Address.class); |
| 360 | assertThat(mainAddress.getCity()).isEqualTo("Lake of the Woods"); |
| 361 | assertThat(mainAddress.getStreet()).isEqualTo("42 Middle of Nowhere"); |
| 362 | assertThat(mainAddress.getZipCode()).isEqualTo(49553); |
| 363 | assertThat(mainAddress.getPhones()).containsExactly("8675039"); |
| 364 | |
| 365 | // Should be able to retrieve within a Map. |
| 366 | Address expectedOtherAddress = new Address(); |
| 367 | expectedOtherAddress.setStreet("101 Ocean Ln"); |
| 368 | expectedOtherAddress.setCity("Jacksonville, FL"); |
| 369 | expectedOtherAddress.setZipCode(89898); |
| 370 | expectedOtherAddress.setPhones(Collections.singleton("8675309")); |
| 371 | |
| 372 | Map<String, Address> otherAddresses = row.getMap("other_addresses", String.class, Address.class); |
| 373 | assertThat(otherAddresses).containsOnly(MapEntry.entry("condo", expectedOtherAddress)); |
| 374 | } finally { |
| 375 | cluster.close(); |
| 376 | } |
| 377 | } |
| 378 | } |