Elffuss BraidHub

kikocis/java-driver public

49a36f53dc6d · 13.3 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
34@SuppressWarnings("unused")
35public class MapperUDTTest extends CCMTestsSupport {
36
37 @Override
38 public void onTestContextInitialized() {
39 execute("CREATE TYPE address (street text, city text, \"ZIP_code\" int, phones set<text>)",
40 "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
41 }
42
43 @BeforeMethod(groups = "short")
44 public void clean() {
45 session().execute("TRUNCATE users");
46 }
47
48 @Table(name = "users",
49 readConsistency = "QUORUM",
50 writeConsistency = "QUORUM")
51 public static class User {
52 @PartitionKey
53 @Column(name = "user_id")
54 private UUID userId;
55
56 private String name;
57
58 @Frozen
59 private Address mainAddress;
60
61 @Column(name = "other_addresses")
62 @FrozenValue
63 private Map<String, Address> otherAddresses = Maps.newHashMap();
64
65 public User() {
66 }
67
68 public User(String name, Address address) {
69 this.userId = UUIDs.random();
70 this.name = name;
71 this.mainAddress = address;
72 this.otherAddresses = new HashMap<String, Address>();
73 }
74
75 public UUID getUserId() {
76 return userId;
77 }
78
79 public void setUserId(UUID userId) {
80 this.userId = userId;
81 }
82
83 public String getName() {
84 return name;
85 }
86
87 public void setName(String name) {
88 this.name = name;
89 }
90
91 public Address getMainAddress() {
92 return mainAddress;
93 }
94
95 public void setMainAddress(Address address) {
96 this.mainAddress = address;
97 }
98
99 public Map<String, Address> getOtherAddresses() {
100 return otherAddresses;
101 }
102
103 public void setOtherAddresses(Map<String, Address> otherAddresses) {
104 this.otherAddresses = otherAddresses;
105 }
106
107 public void addOtherAddress(String name, Address address) {
108 this.otherAddresses.put(name, address);
109 }
110
111 @Override
112 public boolean equals(Object other) {
113 if (this == other)
114 return true;
115 if (other instanceof User) {
116 User that = (User) other;
117 return Objects.equal(this.userId, that.userId) &&
118 Objects.equal(this.name, that.name) &&
119 Objects.equal(this.mainAddress, that.mainAddress) &&
120 Objects.equal(this.otherAddresses, that.otherAddresses);
121 }
122 return false;
123 }
124
125 @Override
126 public int hashCode() {
127 return Objects.hashCode(this.userId, this.name, this.mainAddress, this.otherAddresses);
128 }
129
130 @Override
131 public String toString() {
132 return Objects.toStringHelper(User.class)
133 .add("userId", userId)
134 .add("name", name)
135 .add("mainAddress", mainAddress)
136 .add("otherAddresses", otherAddresses)
137 .toString();
138 }
139 }
140
141 @UDT(name = "address")
142 public static class Address {
143
144 // Dummy constant to test that static fields are properly ignored
145 public static final int FOO = 1;
146
147 @Field // not strictly required, but we want to check that the annotation works without a name
148 private String city;
149
150 // Declared out of order compared to the UDT definition, to make sure that we serialize fields in the correct order (JAVA-884)
151 private String street;
152
153 @Field(name = "ZIP_code", caseSensitive = true)
154 private int zipCode;
155
156 private Set<String> phones;
157
158 public Address() {
159 }
160
161 public Address(String street, String city, int zipCode, String... phones) {
162 this.street = street;
163 this.city = city;
164 this.zipCode = zipCode;
165 this.phones = new HashSet<String>();
166 Collections.addAll(this.phones, phones);
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 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 = register(Cluster.builder()
312 .addContactPoints(getContactPoints())
313 .withPort(ccm().getBinaryPort())
314 .build());
315 CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
316 Session session = cluster.connect(keyspace);
317
318 UUID userId = UUIDs.random();
319
320 // Create a user.
321 session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', \"ZIP_code\": 89898, phones: {'8675309'}} " +
322 " WHERE user_id=" + TypeCodec.uuid().format(userId));
323 session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', \"ZIP_code\": 49553, phones: {'8675039'}} " +
324 " WHERE user_Id=" + TypeCodec.uuid().format(userId));
325
326 // Get the user.
327 Row row = session.execute("select * from users where user_id=?", userId).one();
328
329 UDTValue udtValue = row.getUDTValue("mainaddress");
330 assertThat(udtValue.getString("street")).isEqualTo("42 Middle of Nowhere");
331
332 Object udtObject = row.getObject("mainaddress");
333 assertThat(udtObject).isEqualTo(udtValue);
334
335 // There shouldn't be a codec for address.
336 try {
337 assertThat(registry.codecFor(udtValue.getType(), Address.class));
338 fail("Didn't expect to find codec for udtType <-> Address");
339 } catch (CodecNotFoundException e) {
340 // expected.
341 }
342
343 // Expect a this_udt <-> UDTValue codec to exist. This is a pretty safe bet or else we wouldn't get
344 // this value back.
345 TypeCodec<UDTValue> udtCodec = registry.codecFor(udtValue.getType());
346 assertThat(udtCodec.getCqlType()).isEqualTo(udtValue.getType());
347 assertThat(udtCodec.getJavaType().getRawType()).isEqualTo(UDTValue.class);
348
349 // Retrieve codec for Address, if it can be mapped it will be created, if already registered it'll be used.
350 TypeCodec<Address> codec = new MappingManager(session).udtCodec(Address.class);
351
352 // The codec should be registered after we call udtCodec.
353 assertThat(registry.codecFor(udtValue.getType(), Address.class)).isEqualTo(codec);
354
355 // Should be able to retrieve as an Address.
356 Address mainAddress = row.get("mainaddress", Address.class);
357 assertThat(mainAddress.getCity()).isEqualTo("Lake of the Woods");
358 assertThat(mainAddress.getStreet()).isEqualTo("42 Middle of Nowhere");
359 assertThat(mainAddress.getZipCode()).isEqualTo(49553);
360 assertThat(mainAddress.getPhones()).containsExactly("8675039");
361
362 // Should be able to retrieve within a Map.
363 Address expectedOtherAddress = new Address();
364 expectedOtherAddress.setStreet("101 Ocean Ln");
365 expectedOtherAddress.setCity("Jacksonville, FL");
366 expectedOtherAddress.setZipCode(89898);
367 expectedOtherAddress.setPhones(Collections.singleton("8675309"));
368
369 Map<String, Address> otherAddresses = row.getMap("other_addresses", String.class, Address.class);
370 assertThat(otherAddresses).containsOnly(MapEntry.entry("condo", expectedOtherAddress));
371 }
372}