Elffuss BraidHub

kikocis/java-driver public

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