Elffuss BraidHub

kikocis/java-driver public

98c95c343dd2 · 12.4 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 java.util.*;
19
20import com.datastax.driver.core.*;
21import com.datastax.driver.core.exceptions.CodecNotFoundException;
22import com.google.common.collect.Maps;
23import org.assertj.core.data.MapEntry;
24import org.testng.annotations.BeforeMethod;
25
26import com.google.common.base.Objects;
27import org.testng.annotations.Test;
28
29import static org.assertj.core.api.Assertions.assertThat;
30import static org.assertj.core.api.Assertions.fail;
31import static org.testng.Assert.assertEquals;
32import static org.testng.Assert.assertNull;
33import static org.testng.Assert.assertTrue;
34
35import com.datastax.driver.core.utils.UUIDs;
36
37import com.datastax.driver.mapping.annotations.*;
38
39public 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 (other instanceof User) {
117 User that = (User) other;
118 return Objects.equal(this.userId, that.userId) &&
119 Objects.equal(this.name, that.name) &&
120 Objects.equal(this.mainAddress, that.mainAddress) &&
121 Objects.equal(this.otherAddresses, that.otherAddresses);
122 }
123 return false;
124 }
125 }
126
127 @UDT(name = "address")
128 public static class Address {
129
130 // Dummy constant to test that static fields are properly ignored
131 public static final int FOO = 1;
132
133 private String street;
134
135 @Field // not strictly required, but we want to check that the annotation works without a name
136 private String city;
137
138 @Field(name = "zip_code")
139 private int zipCode;
140
141 private Set<String> phones;
142
143 public Address() {
144 }
145
146 public Address(String street, String city, int zipCode, String... phones) {
147 this.street = street;
148 this.city = city;
149 this.zipCode = zipCode;
150 this.phones = new HashSet<String>();
151 for (String phone : phones) {
152 this.phones.add(phone);
153 }
154 }
155
156 public String getStreet() {
157 return street;
158 }
159
160 public void setStreet(String street) {
161 this.street = street;
162 }
163
164 public String getCity() {
165 return city;
166 }
167
168 public void setCity(String city) {
169 this.city = city;
170 }
171
172 public int getZipCode() {
173 return zipCode;
174 }
175
176 public void setZipCode(int zipCode) {
177 this.zipCode = zipCode;
178 }
179
180 public Set<String> getPhones() {
181 return phones;
182 }
183
184 public void setPhones(Set<String> phones) {
185 this.phones = phones;
186 }
187
188 @Override
189 public boolean equals(Object other) {
190 if (other instanceof Address) {
191 Address that = (Address) other;
192 return Objects.equal(this.street, that.street) &&
193 Objects.equal(this.city, that.city) &&
194 Objects.equal(this.zipCode, that.zipCode) &&
195 Objects.equal(this.phones, that.phones);
196 }
197 return false;
198 }
199 }
200
201 @Accessor
202 public interface UserAccessor {
203 @Query("SELECT * FROM users WHERE user_id=:userId")
204 User getOne(@Param("userId") UUID userId);
205
206 @Query("UPDATE users SET other_addresses[:name]=:address WHERE user_id=:id")
207 ResultSet addAddress(@Param("id") UUID id, @Param("name") String addressName, @Param("address") Address address);
208
209 @Query("UPDATE users SET other_addresses=:addresses where user_id=:id")
210 ResultSet setOtherAddresses(@Param("id") UUID id, @Param("addresses") Map<String, Address> addresses);
211
212 @Query("SELECT * FROM users")
213 public Result<User> getAll();
214 }
215
216 @Test(groups = "short")
217 public void testSimpleEntity() throws Exception {
218 Mapper<User> m = new MappingManager(session).mapper(User.class);
219
220 User u1 = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
221 u1.addOtherAddress("work", new Address("5 Main Street", "Springfield", 12345, "23431342"));
222 m.save(u1);
223
224 assertEquals(m.get(u1.getUserId()), u1);
225 }
226
227 @Test(groups = "short")
228 public void should_handle_null_UDT_value() throws Exception {
229 Mapper<User> m = new MappingManager(session).mapper(User.class);
230
231 User u1 = new User("Paul", null);
232 m.save(u1);
233
234 assertNull(m.get(u1.getUserId()).getMainAddress());
235 }
236
237 @Test(groups = "short")
238 public void testAccessor() throws Exception {
239 MappingManager manager = new MappingManager(session);
240
241 Mapper<User> m = new MappingManager(session).mapper(User.class);
242 User u1 = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
243 m.save(u1);
244
245 UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
246
247 Address workAddress = new Address("5 Main Street", "Springfield", 12345, "23431342");
248 userAccessor.addAddress(u1.getUserId(), "work", workAddress);
249
250 User u2 = userAccessor.getOne(u1.getUserId());
251 assertEquals(workAddress, u2.getOtherAddresses().get("work"));
252
253 // Adding a null value should remove it from the list.
254 userAccessor.addAddress(u1.getUserId(), "work", null);
255 User u3 = userAccessor.getOne(u1.getUserId());
256 assertThat(u3.getOtherAddresses()).doesNotContainKey("work");
257
258 // Add a bunch of other addresses
259 Map<String, Address> otherAddresses = Maps.newHashMap();
260 otherAddresses.put("work", workAddress);
261 otherAddresses.put("cabin", new Address("42 Middle of Nowhere", "Lake of the Woods", 49553, "8675309"));
262
263 userAccessor.setOtherAddresses(u1.getUserId(), otherAddresses);
264 User u4 = userAccessor.getOne(u1.getUserId());
265 assertThat(u4.getOtherAddresses()).isEqualTo(otherAddresses);
266
267 // Nullify other addresses
268 userAccessor.setOtherAddresses(u1.getUserId(), null);
269 User u5 = userAccessor.getOne(u1.getUserId());
270 assertThat(u5.getOtherAddresses()).isEmpty();
271
272 // No argument call
273 Result<User> u = userAccessor.getAll();
274 assertEquals(u.one(), u5);
275 assertTrue(u.isExhausted());
276 }
277
278 @Test(groups = "short")
279 public void should_be_able_to_use_udtCodec_standalone() {
280 // Create a separate Cluster/Session to start with a CodecRegistry from scratch (so not already registered).
281 Cluster cluster = Cluster.builder().addContactPointsWithPorts(Collections.singleton(hostAddress)).build();
282 try {
283 CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
284 Session session = cluster.connect(keyspace);
285
286 UUID userId = UUIDs.random();
287
288 // Create a user.
289 session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', zip_code: 89898, phones: {'8675309'}} " +
290 " WHERE user_id=" + TypeCodec.UUIDCodec.instance.format(userId));
291 session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', zip_code: 49553, phones: {'8675039'}} " +
292 " WHERE user_Id=" + TypeCodec.UUIDCodec.instance.format(userId));
293
294 // Get the user.
295 Row row = session.execute("select * from users where user_id=?", userId).one();
296
297 UDTValue udtValue = row.getUDTValue("mainaddress");
298 assertThat(udtValue.getString("street")).isEqualTo("42 Middle of Nowhere");
299
300 Object udtObject = row.getObject("mainaddress");
301 assertThat(udtObject).isEqualTo(udtValue);
302
303 // There shouldn't be a codec for address.
304 try {
305 assertThat(registry.codecFor(udtValue.getType(), Address.class));
306 fail("Didn't expect to find codec for udtType <-> Address");
307 } catch (CodecNotFoundException e) {
308 // expected.
309 }
310
311 // Expect a this_udt <-> UDTValue codec to exist. This is a pretty safe bet or else we wouldn't get
312 // this value back.
313 TypeCodec<UDTValue> udtCodec = registry.codecFor(udtValue.getType());
314 assertThat(udtCodec.getCqlType()).isEqualTo(udtValue.getType());
315 assertThat(udtCodec.getJavaType().getRawType()).isEqualTo(UDTValue.class);
316
317 // Retrieve codec for Address, if it can be mapped it will be created, if already registered it'll be used.
318 TypeCodec<Address> codec = new MappingManager(session).udtCodec(Address.class);
319
320 // The codec should be registered after we call udtCodec.
321 assertThat(registry.codecFor(udtValue.getType(), Address.class)).isEqualTo(codec);
322
323 // Should be able to retrieve as an Address.
324 Address mainAddress = row.get("mainaddress", Address.class);
325 assertThat(mainAddress.getCity()).isEqualTo("Lake of the Woods");
326 assertThat(mainAddress.getStreet()).isEqualTo("42 Middle of Nowhere");
327 assertThat(mainAddress.getZipCode()).isEqualTo(49553);
328 assertThat(mainAddress.getPhones()).containsExactly("8675039");
329
330 // Should be able to retrieve within a Map.
331 Address expectedOtherAddress = new Address();
332 expectedOtherAddress.setStreet("101 Ocean Ln");
333 expectedOtherAddress.setCity("Jacksonville, FL");
334 expectedOtherAddress.setZipCode(89898);
335 expectedOtherAddress.setPhones(Collections.singleton("8675309"));
336
337 Map<String, Address> otherAddresses = row.getMap("other_addresses", String.class, Address.class);
338 assertThat(otherAddresses).containsOnly(MapEntry.entry("condo", expectedOtherAddress));
339 } finally {
340 cluster.close();
341 }
342 }
343}