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