Elffuss BraidHub

kikocis/java-driver public

Format all Java sources with Intellij default settings.
Changeset9737075342ee5fbba847829b1c898cfda9f0e85646dd59c17757ce435da36652
Authorolim7t <omichallat+github@gmail.com> · 2015-12-09 18:45 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-12-09 18:45 +01:00
Parentsc200baed5144

Browse the files at this changeset

More than 300 files changed

modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +64 −60
@@ -15,9 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.util.*;
20-
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.datastax.driver.core.policies.LoadBalancingPolicy;
20+import com.datastax.driver.core.policies.RoundRobinPolicy;
21+import com.datastax.driver.core.policies.WhiteListPolicy;
22+import com.datastax.driver.core.utils.CassandraVersion;
2123 import com.google.common.base.Function;
2224 import com.google.common.collect.Iterables;
2325 import com.google.common.collect.Lists;
@@ -25,30 +27,29 @@
2527 import org.testng.annotations.BeforeClass;
2628 import org.testng.annotations.Test;
2729
28-import com.datastax.driver.core.exceptions.InvalidTypeException;
29-import com.datastax.driver.core.policies.LoadBalancingPolicy;
30-import com.datastax.driver.core.policies.RoundRobinPolicy;
31-import com.datastax.driver.core.policies.WhiteListPolicy;
32-import com.datastax.driver.core.utils.CassandraVersion;
30+import java.net.InetSocketAddress;
31+import java.util.HashSet;
32+import java.util.List;
33+import java.util.Set;
3334
3435 import static com.datastax.driver.core.Assertions.assertThat;
3536
3637 /**
3738 * This class uses subclasses for each type of partitioner.
38- *
39+ * <p/>
3940 * There's normally a way to parametrize a TestNG class with @Factory and @DataProvider,
4041 * but it doesn't seem to work with multiple methods.
4142 */
4243 public abstract class TokenIntegrationTest {
4344
4445 List<String> schema = Lists.newArrayList(
45- "CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}",
46- "CREATE KEYSPACE test2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}",
47- "USE test",
48- "CREATE TABLE foo(i int primary key)",
49- "INSERT INTO foo (i) VALUES (1)",
50- "INSERT INTO foo (i) VALUES (2)",
51- "INSERT INTO foo (i) VALUES (3)"
46+ "CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}",
47+ "CREATE KEYSPACE test2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}",
48+ "USE test",
49+ "CREATE TABLE foo(i int primary key)",
50+ "INSERT INTO foo (i) VALUES (1)",
51+ "INSERT INTO foo (i) VALUES (2)",
52+ "INSERT INTO foo (i) VALUES (3)"
5253 );
5354
5455 private final String ccmOptions;
@@ -76,17 +77,17 @@
7677
7778 // Only connect to node 1, which makes it easier to query system tables in should_expose_tokens_per_host()
7879 LoadBalancingPolicy lbp = new WhiteListPolicy(new RoundRobinPolicy(),
79- Lists.newArrayList(new InetSocketAddress(CCMBridge.ipOfNode(1), 9042)));
80+ Lists.newArrayList(new InetSocketAddress(CCMBridge.ipOfNode(1), 9042)));
8081
8182 cluster = Cluster.builder()
82- .addContactPoints(CCMBridge.ipOfNode(1))
83- .withLoadBalancingPolicy(lbp)
84- .withQueryOptions(new QueryOptions()
85- .setRefreshNodeIntervalMillis(0)
86- .setRefreshNodeListIntervalMillis(0)
87- .setRefreshSchemaIntervalMillis(0)
88- )
89- .build();
83+ .addContactPoints(CCMBridge.ipOfNode(1))
84+ .withLoadBalancingPolicy(lbp)
85+ .withQueryOptions(new QueryOptions()
86+ .setRefreshNodeIntervalMillis(0)
87+ .setRefreshNodeListIntervalMillis(0)
88+ .setRefreshSchemaIntervalMillis(0)
89+ )
90+ .build();
9091 cluster.init();
9192 session = cluster.connect();
9293
@@ -94,7 +95,7 @@
9495 session.execute(statement);
9596 }
9697
97- @AfterClass(groups = "short", alwaysRun=true)
98+ @AfterClass(groups = "short", alwaysRun = true)
9899 public void teardown() {
99100 if (cluster != null)
100101 cluster.close();
@@ -135,8 +136,8 @@
135136 if (row.getInt("i") == testKey) {
136137 // We should find our test key exactly once
137138 assertThat(foundRange)
138- .describedAs("found the same key in two ranges: " + foundRange + " and " + range)
139- .isNull();
139+ .describedAs("found the same key in two ranges: " + foundRange + " and " + range)
140+ .isNull();
140141 foundRange = range;
141142 // That range should be managed by the replica
142143 assertThat(metadata.getReplicas("test", range)).contains(replica);
@@ -160,16 +161,16 @@
160161 * Validates that a {@link Token} can be retrieved and parsed by executing 'select token(name)' and
161162 * then used to find data matching that token.
162163 * </p>
163- *
164- * <p>
164+ * <p/>
165+ * <p/>
165166 * This test does the following:
166- *
167+ * <p/>
167168 * <ol>
168- * <li>Retrieve the token for the key with value '1', get it by index, and ensure if is of the expected token type.</li>
169- * <li>Retrieve the token for the partition key with getPartitionKeyToken</li>
170- * <li>Select data by token with a BoundStatement.</li>
171- * <li>Select data by token using setToken by index.</li>
172- * <li>Select data by token with setPartitionKeyToken.</li>
169+ * <li>Retrieve the token for the key with value '1', get it by index, and ensure if is of the expected token type.</li>
170+ * <li>Retrieve the token for the partition key with getPartitionKeyToken</li>
171+ * <li>Select data by token with a BoundStatement.</li>
172+ * <li>Select data by token using setToken by index.</li>
173+ * <li>Select data by token with setPartitionKeyToken.</li>
173174 * </ol>
174175 *
175176 * @test_category token
@@ -185,7 +186,7 @@
185186 assertThat(token.getType()).isEqualTo(expectedTokenType);
186187
187188 assertThat(
188- row.getPartitionKeyToken()
189+ row.getPartitionKeyToken()
189190 ).isEqualTo(token);
190191
191192 PreparedStatement pst = session.prepare("SELECT * FROM test.foo WHERE token(i) = ?");
@@ -204,17 +205,17 @@
204205 * Validates that a {@link Token} can be retrieved and parsed by using bind variables and
205206 * aliasing.
206207 * </p>
207- *
208- * <p>
208+ * <p/>
209+ * <p/>
209210 * This test does the following:
210- *
211+ * <p/>
211212 * <ol>
212- * <li>Retrieve the token by alias for the key '1', and ensure it matches the token by index.</li>
213- * <li>Select data by token using setToken by name.</li>
213+ * <li>Retrieve the token by alias for the key '1', and ensure it matches the token by index.</li>
214+ * <li>Select data by token using setToken by name.</li>
214215 * </ol>
215216 */
216217 @Test(groups = "short")
217- @CassandraVersion(major=2)
218+ @CassandraVersion(major = 2)
218219 public void should_get_token_from_row_and_set_token_in_query_with_binding_and_aliasing() {
219220 Row row = session.execute("SELECT token(i) AS t FROM test.foo WHERE i = 1").one();
220221 Token token = row.getToken("t");
@@ -249,7 +250,7 @@
249250 * Ensures that @{link TokenRange}s are exposed at a per host level, the ranges are complete,
250251 * the entire ring is represented, and that ranges do not overlap.
251252 * </p>
252- *
253+ * <p/>
253254 * <p>
254255 * Also ensures that ranges from another replica are present when a Host is a replica for
255256 * another node.
@@ -275,7 +276,7 @@
275276 Host host = TestUtils.findHost(cluster, i);
276277 Set<TokenRange> hostRanges = cluster.getMetadata().getTokenRanges(keyspace, host);
277278 // Special case: When using vnodes the tokens are not evenly assigned to each replica.
278- if(!useVnodes) {
279+ if (!useVnodes) {
279280 assertThat(hostRanges).hasSize(replicationFactor * numTokens);
280281 }
281282 allRangesWithReplicas.addAll(hostRanges);
@@ -286,7 +287,7 @@
286287
287288 // Once we ignore duplicates, the number of ranges should match the number of nodes.
288289 Set<TokenRange> allRanges = new HashSet<TokenRange>(allRangesWithReplicas);
289- assertThat(allRanges).hasSize(3*numTokens);
290+ assertThat(allRanges).hasSize(3 * numTokens);
290291
291292 // And the ranges should cover the whole ring and no ranges intersect.
292293 assertThat(cluster).hasValidTokenRanges(keyspace);
@@ -296,7 +297,7 @@
296297 * <p>
297298 * Ensures that Tokens are exposed for each Host and that the match those in the system tables.
298299 * </p>
299- *
300+ * <p/>
300301 * <p>
301302 * Also validates that tokens are not present for multiple hosts.
302303 * </p>
@@ -315,12 +316,13 @@
315316 // constructed in the first place, but there's not much else we can do.
316317 // Note that this relies on all queries going to node 1, which is why we use a WhiteList LBP in setup().
317318 Row row = (host.listenAddress == null)
318- ? session.execute("select tokens from system.local").one()
319- : session.execute("select tokens from system.peers where peer = '" + host.listenAddress.getHostAddress() + "'").one();
319+ ? session.execute("select tokens from system.local").one()
320+ : session.execute("select tokens from system.peers where peer = '" + host.listenAddress.getHostAddress() + "'").one();
320321 Set<String> tokenStrings = row.getSet("tokens", String.class);
321322 assertThat(tokenStrings).hasSize(numTokens);
322323 Iterable<Token> tokensFromSystemTable = Iterables.transform(tokenStrings, new Function<String, Token>() {
323- @Override public Token apply(String input) {
324+ @Override
325+ public Token apply(String input) {
324326 return tokenFactory().fromString(input);
325327 }
326328 });
@@ -348,11 +350,12 @@
348350 assertOnlyOneWrapped(ranges);
349351
350352 Iterable<TokenRange> splitRanges = Iterables.concat(Iterables.transform(ranges,
351- new Function<TokenRange, Iterable<TokenRange>>() {
352- @Override public Iterable<TokenRange> apply(TokenRange input) {
353- return input.splitEvenly(10);
354- }
355- })
353+ new Function<TokenRange, Iterable<TokenRange>>() {
354+ @Override
355+ public Iterable<TokenRange> apply(TokenRange input) {
356+ return input.splitEvenly(10);
357+ }
358+ })
356359 );
357360
358361 assertOnlyOneWrapped(splitRanges);
@@ -360,16 +363,17 @@
360363
361364 /**
362365 * Asserts that given the input {@link TokenRange}s that at most one of them wraps the token ring.
366+ *
363367 * @param ranges Ranges to validate against.
364368 */
365369 protected void assertOnlyOneWrapped(Iterable<TokenRange> ranges) {
366370 TokenRange wrappedRange = null;
367371
368- for(TokenRange range : ranges) {
369- if(range.isWrappedAround()) {
372+ for (TokenRange range : ranges) {
373+ if (range.isWrappedAround()) {
370374 assertThat(wrappedRange)
371- .as("Found a wrapped around TokenRange (%s) when one already exists (%s).", range, wrappedRange)
372- .isNull();
375+ .as("Found a wrapped around TokenRange (%s) when one already exists (%s).", range, wrappedRange)
376+ .isNull();
373377 wrappedRange = range;
374378
375379 assertThat(range).isWrappedAround(); // this also checks the unwrapped ranges
@@ -390,7 +394,7 @@
390394 Token end = metadata.newToken(range.getEnd().toString());
391395
392396 assertThat(metadata.newTokenRange(start, end))
393- .isEqualTo(range);
397+ .isEqualTo(range);
394398 }
395399
396400 protected abstract Token.Factory tokenFactory();
modified driver-core/src/test/java/com/datastax/driver/core/TokenRangeAssert.java +14 −14
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.assertj.core.api.AbstractAssert;
19+
1820 import java.util.Iterator;
1921 import java.util.List;
2022
21-import org.assertj.core.api.AbstractAssert;
22-
2323 import static com.datastax.driver.core.Assertions.assertThat;
2424
2525 public class TokenRangeAssert extends AbstractAssert<TokenRangeAssert, TokenRange> {
@@ -54,8 +54,8 @@
5454
5555 List<TokenRange> unwrapped = actual.unwrap();
5656 assertThat(unwrapped.size())
57- .as("%s should unwrap to two ranges, but unwrapped to %s", actual, unwrapped)
58- .isEqualTo(2);
57+ .as("%s should unwrap to two ranges, but unwrapped to %s", actual, unwrapped)
58+ .isEqualTo(2);
5959
6060 Iterator<TokenRange> unwrappedIt = unwrapped.iterator();
6161 TokenRange firstRange = unwrappedIt.next();
@@ -80,22 +80,22 @@
8080
8181 public TokenRangeAssert intersects(TokenRange that) {
8282 assertThat(actual.intersects(that))
83- .as("%s should intersect %s", actual, that)
84- .isTrue();
83+ .as("%s should intersect %s", actual, that)
84+ .isTrue();
8585 assertThat(that.intersects(actual))
86- .as("%s should intersect %s", that, actual)
87- .isTrue();
86+ .as("%s should intersect %s", that, actual)
87+ .isTrue();
8888 return this;
8989 }
9090
91- public TokenRangeAssert doesNotIntersect(TokenRange ... that) {
92- for(TokenRange thatRange : that) {
91+ public TokenRangeAssert doesNotIntersect(TokenRange... that) {
92+ for (TokenRange thatRange : that) {
9393 assertThat(actual.intersects(thatRange))
94- .as("%s should not intersect %s", actual, thatRange)
95- .isFalse();
94+ .as("%s should not intersect %s", actual, thatRange)
95+ .isFalse();
9696 assertThat(thatRange.intersects(actual))
97- .as("%s should not intersect %s", thatRange, actual)
98- .isFalse();
97+ .as("%s should not intersect %s", thatRange, actual)
98+ .isFalse();
9999 }
100100 return this;
101101 }
modified driver-core/src/test/java/com/datastax/driver/core/TokenRangeTest.java +50 −51
@@ -15,14 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-
2018 import com.google.common.collect.ImmutableList;
2119 import org.testng.annotations.Test;
2220
23-import static org.testng.Assert.fail;
21+import java.util.List;
2422
2523 import static com.datastax.driver.core.Assertions.assertThat;
24+import static org.testng.Assert.fail;
2625
2726 public class TokenRangeTest {
2827 // The tests in this class don't depend on the kind of factory used, so use Murmur3 everywhere
@@ -33,74 +32,74 @@
3332 public void should_check_intersection() {
3433 // NB - to make the test more visual, we use watch face numbers
3534 assertThat(tokenRange(3, 9))
36- .doesNotIntersect(tokenRange(11, 1))
37- .doesNotIntersect(tokenRange(1, 2))
38- .doesNotIntersect(tokenRange(11, 3))
39- .doesNotIntersect(tokenRange(2, 3))
40- .doesNotIntersect(tokenRange(3, 3))
41- .intersects(tokenRange(2, 6))
42- .intersects(tokenRange(2, 10))
43- .intersects(tokenRange(6, 10))
44- .intersects(tokenRange(4, 8))
45- .intersects(tokenRange(3, 9))
46- .doesNotIntersect(tokenRange(9, 10))
47- .doesNotIntersect(tokenRange(10, 11))
35+ .doesNotIntersect(tokenRange(11, 1))
36+ .doesNotIntersect(tokenRange(1, 2))
37+ .doesNotIntersect(tokenRange(11, 3))
38+ .doesNotIntersect(tokenRange(2, 3))
39+ .doesNotIntersect(tokenRange(3, 3))
40+ .intersects(tokenRange(2, 6))
41+ .intersects(tokenRange(2, 10))
42+ .intersects(tokenRange(6, 10))
43+ .intersects(tokenRange(4, 8))
44+ .intersects(tokenRange(3, 9))
45+ .doesNotIntersect(tokenRange(9, 10))
46+ .doesNotIntersect(tokenRange(10, 11))
4847 ;
4948 assertThat(tokenRange(9, 3))
50- .doesNotIntersect(tokenRange(5, 7))
51- .doesNotIntersect(tokenRange(7, 8))
52- .doesNotIntersect(tokenRange(5, 9))
53- .doesNotIntersect(tokenRange(8, 9))
54- .doesNotIntersect(tokenRange(9, 9))
55- .intersects(tokenRange(8, 2))
56- .intersects(tokenRange(8, 4))
57- .intersects(tokenRange(2, 4))
58- .intersects(tokenRange(10, 2))
59- .intersects(tokenRange(9, 3))
60- .doesNotIntersect(tokenRange(3, 4))
61- .doesNotIntersect(tokenRange(4, 5))
49+ .doesNotIntersect(tokenRange(5, 7))
50+ .doesNotIntersect(tokenRange(7, 8))
51+ .doesNotIntersect(tokenRange(5, 9))
52+ .doesNotIntersect(tokenRange(8, 9))
53+ .doesNotIntersect(tokenRange(9, 9))
54+ .intersects(tokenRange(8, 2))
55+ .intersects(tokenRange(8, 4))
56+ .intersects(tokenRange(2, 4))
57+ .intersects(tokenRange(10, 2))
58+ .intersects(tokenRange(9, 3))
59+ .doesNotIntersect(tokenRange(3, 4))
60+ .doesNotIntersect(tokenRange(4, 5))
6261 ;
6362 assertThat(tokenRange(3, 3)).doesNotIntersect(tokenRange(3, 3));
6463
6564 // Reminder: minToken serves as both lower and upper bound
6665 assertThat(tokenRange(minToken, 5))
67- .doesNotIntersect(tokenRange(6, 7))
68- .doesNotIntersect(tokenRange(6, minToken))
69- .intersects(tokenRange(6, 4))
70- .intersects(tokenRange(2, 4))
71- .intersects(tokenRange(minToken, 4))
72- .intersects(tokenRange(minToken, 5))
66+ .doesNotIntersect(tokenRange(6, 7))
67+ .doesNotIntersect(tokenRange(6, minToken))
68+ .intersects(tokenRange(6, 4))
69+ .intersects(tokenRange(2, 4))
70+ .intersects(tokenRange(minToken, 4))
71+ .intersects(tokenRange(minToken, 5))
7372 ;
7473
7574 assertThat(tokenRange(5, minToken))
76- .doesNotIntersect(tokenRange(3, 4))
77- .doesNotIntersect(tokenRange(minToken, 4))
78- .intersects(tokenRange(6, 7))
79- .intersects(tokenRange(4, 1))
80- .intersects(tokenRange(6, minToken))
81- .intersects(tokenRange(5, minToken))
75+ .doesNotIntersect(tokenRange(3, 4))
76+ .doesNotIntersect(tokenRange(minToken, 4))
77+ .intersects(tokenRange(6, 7))
78+ .intersects(tokenRange(4, 1))
79+ .intersects(tokenRange(6, minToken))
80+ .intersects(tokenRange(5, minToken))
8281 ;
8382
8483 assertThat(tokenRange(minToken, minToken))
85- .intersects(tokenRange(3, 4))
86- .intersects(tokenRange(3, minToken))
87- .intersects(tokenRange(minToken, 3))
88- .doesNotIntersect(tokenRange(3, 3))
84+ .intersects(tokenRange(3, 4))
85+ .intersects(tokenRange(3, minToken))
86+ .intersects(tokenRange(minToken, 3))
87+ .doesNotIntersect(tokenRange(3, 3))
8988 ;
9089 }
9190
9291 @Test(groups = "unit")
9392 public void should_compute_intersection() {
9493 assertThat(tokenRange(3, 9).intersectWith(tokenRange(2, 4)))
95- .isEqualTo(ImmutableList.of(tokenRange(3, 4)));
94+ .isEqualTo(ImmutableList.of(tokenRange(3, 4)));
9695 assertThat(tokenRange(3, 9).intersectWith(tokenRange(3, 5)))
97- .isEqualTo(ImmutableList.of(tokenRange(3, 5)));
96+ .isEqualTo(ImmutableList.of(tokenRange(3, 5)));
9897 assertThat(tokenRange(3, 9).intersectWith(tokenRange(4, 6)))
99- .isEqualTo(ImmutableList.of(tokenRange(4, 6)));
98+ .isEqualTo(ImmutableList.of(tokenRange(4, 6)));
10099 assertThat(tokenRange(3, 9).intersectWith(tokenRange(7, 9)))
101- .isEqualTo(ImmutableList.of(tokenRange(7, 9)));
100+ .isEqualTo(ImmutableList.of(tokenRange(7, 9)));
102101 assertThat(tokenRange(3, 9).intersectWith(tokenRange(8, 10)))
103- .isEqualTo(ImmutableList.of(tokenRange(8, 9)));
102+ .isEqualTo(ImmutableList.of(tokenRange(8, 9)));
104103 }
105104
106105 @Test(groups = "unit")
@@ -108,14 +107,14 @@
108107 // If a range wraps the ring like 10, -10 does this will produce two separate
109108 // intersected ranges.
110109 assertThat(tokenRange(10, -10).intersectWith(tokenRange(-20, 20)))
111- .isEqualTo(ImmutableList.of(tokenRange(10, 20), tokenRange(-20, -10)));
110+ .isEqualTo(ImmutableList.of(tokenRange(10, 20), tokenRange(-20, -10)));
112111 assertThat(tokenRange(-20, 20).intersectWith(tokenRange(10, -10)))
113- .isEqualTo(ImmutableList.of(tokenRange(10, 20), tokenRange(-20, -10)));
112+ .isEqualTo(ImmutableList.of(tokenRange(10, 20), tokenRange(-20, -10)));
114113
115114 // If both ranges wrap the ring, they should be merged together wrapping across
116115 // the range.
117116 assertThat(tokenRange(10, -30).intersectWith(tokenRange(20, -20)))
118- .isEqualTo(ImmutableList.of(tokenRange(20, -30)));
117+ .isEqualTo(ImmutableList.of(tokenRange(20, -30)));
119118 }
120119
121120 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
modified driver-core/src/test/java/com/datastax/driver/core/TracingTest.java +8 −8
@@ -15,19 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.Collections;
20-import java.util.List;
21-import java.util.UUID;
22-
2318 import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
2419 import com.datastax.driver.core.utils.CassandraVersion;
2520 import org.testng.annotations.BeforeClass;
2621 import org.testng.annotations.Test;
2722
23+import java.util.Collection;
24+import java.util.Collections;
25+import java.util.List;
26+import java.util.UUID;
27+
2828 import static org.assertj.core.api.Assertions.assertThat;
2929
30-@CassandraVersion(major=2.0)
30+@CassandraVersion(major = 2.0)
3131 public class TracingTest extends CCMBridge.PerClassSingleNodeCluster {
3232
3333 @Override
@@ -73,12 +73,12 @@
7373 }
7474
7575 assertThat(result.getExecutionInfo().getQueryTrace().getEvents()).isNotNull()
76- .isNotEmpty();
76+ .isNotEmpty();
7777 }
7878
7979 /**
8080 * Validates that if a query gets retried, the second internal query will still have tracing enabled.
81- *
81+ * <p/>
8282 * To force a retry, we use the downgrading policy with an impossible CL.
8383 *
8484 * @test_category tracing
modified driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +21 −16
@@ -15,20 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.*;
20-
2118 import com.beust.jcommander.internal.Lists;
19+import com.datastax.driver.core.utils.CassandraVersion;
2220 import com.google.common.base.Joiner;
2321 import org.testng.annotations.Test;
2422
23+import java.nio.ByteBuffer;
24+import java.util.*;
25+
2526 import static org.assertj.core.api.Assertions.assertThat;
2627 import static org.testng.Assert.assertEquals;
2728 import static org.testng.Assert.fail;
2829
29-import com.datastax.driver.core.utils.CassandraVersion;
30-
31-@CassandraVersion(major=2.1)
30+@CassandraVersion(major = 2.1)
3231 public class TupleTest extends CCMBridge.PerClassSingleNodeCluster {
3332
3433 ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
@@ -92,13 +91,14 @@
9291 /**
9392 * Basic test of tuple functionality.
9493 * Original code found in python-driver:integration.standard.test_types.py:test_tuple_type
94+ *
9595 * @throws Exception
9696 */
9797 @Test(groups = "short")
9898 public void tupleTypeTest() throws Exception {
9999 try {
100100 session.execute("CREATE KEYSPACE test_tuple_type " +
101- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
101+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
102102 session.execute("USE test_tuple_type");
103103 session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)");
104104
@@ -114,7 +114,8 @@
114114 try {
115115 TupleValue partial = t.newValue("bar", 456);
116116 fail();
117- } catch (IllegalArgumentException e) {}
117+ } catch (IllegalArgumentException e) {
118+ }
118119
119120 // test incomplete tuples with new TupleType
120121 TupleType t1 = cluster.getMetadata().newTupleType(DataType.ascii(), DataType.cint());
@@ -128,7 +129,8 @@
128129 try {
129130 TupleValue subpartial = t.newValue("zoo");
130131 fail();
131- } catch (IllegalArgumentException e) {}
132+ } catch (IllegalArgumentException e) {
133+ }
132134
133135 // test single value tuples with new TupleType
134136 TupleType t2 = cluster.getMetadata().newTupleType(DataType.ascii());
@@ -166,7 +168,7 @@
166168 public void tupleTestTypeVaryingLengths() throws Exception {
167169 try {
168170 session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " +
169- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
171+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
170172 session.execute("USE test_tuple_type_varying_lengths");
171173
172174 // programmatically create the table with tuples of said sizes
@@ -221,7 +223,7 @@
221223
222224 try {
223225 session.execute("CREATE KEYSPACE test_tuple_subtypes " +
224- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
226+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
225227 session.execute("USE test_tuple_subtypes");
226228
227229 // programmatically create the table with a tuple of all datatypes
@@ -287,7 +289,7 @@
287289
288290 try {
289291 session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
290- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
292+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
291293 session.execute("USE test_tuple_non_primitive_subtypes");
292294
293295 ArrayList<String> values = new ArrayList<String>();
@@ -398,7 +400,7 @@
398400 @Test(groups = "short")
399401 public void detachedTupleTypeTest() {
400402 TupleType detachedType = TupleType.of(TestUtils.getDesiredProtocolVersion(), CodecRegistry.DEFAULT_INSTANCE,
401- DataType.cint(), DataType.text(), DataType.cfloat());
403+ DataType.cint(), DataType.text(), DataType.cfloat());
402404 TupleValue detachedValue = detachedType.newValue(1, "hello", 2.0f);
403405
404406 TupleType attachedType = cluster.getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat());
@@ -409,6 +411,7 @@
409411
410412 /**
411413 * Helper method for creating nested tuple schema
414+ *
412415 * @param depth
413416 * @return
414417 */
@@ -421,6 +424,7 @@
421424
422425 /**
423426 * Helper method for creating nested tuples
427+ *
424428 * @param depth
425429 * @return
426430 */
@@ -456,9 +460,9 @@
456460 "v_2 %s, " +
457461 "v_3 %s, " +
458462 "v_64 %s)", nestedTuplesSchemaHelper(1),
459- nestedTuplesSchemaHelper(2),
460- nestedTuplesSchemaHelper(3),
461- nestedTuplesSchemaHelper(64)));
463+ nestedTuplesSchemaHelper(2),
464+ nestedTuplesSchemaHelper(3),
465+ nestedTuplesSchemaHelper(64)));
462466
463467 for (int i : Arrays.asList(1, 2, 3, 64)) {
464468 // create tuple
@@ -482,6 +486,7 @@
482486 /**
483487 * Test for inserting null Tuple values into UDT's
484488 * Original code found in python-driver:integration.standard.test_types.py:test_tuples_with_nulls
489+ *
485490 * @throws Exception
486491 */
487492 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecAssert.java +3 −3
@@ -67,14 +67,14 @@
6767 }
6868
6969 public TypeCodecAssert withProtocolVersion(ProtocolVersion version) {
70- if(version == null) fail("ProtocolVersion cannot be null");
70+ if (version == null) fail("ProtocolVersion cannot be null");
7171 this.version = version;
7272 return this;
7373 }
7474
7575 @SuppressWarnings("unchecked")
7676 public TypeCodecAssert canSerialize(Object value) {
77- if(version == null) fail("ProtocolVersion cannot be null");
77+ if (version == null) fail("ProtocolVersion cannot be null");
7878 try {
7979 assertThat(actual.deserialize(actual.serialize(value, version), version)).isEqualTo(value);
8080 } catch (Exception e) {
@@ -85,7 +85,7 @@
8585
8686 @SuppressWarnings("unchecked")
8787 public TypeCodecAssert cannotSerialize(Object value) {
88- if(version == null) fail("ProtocolVersion cannot be null");
88+ if (version == null) fail("ProtocolVersion cannot be null");
8989 try {
9090 actual.serialize(value, version);
9191 fail("Should not have been able to serialize " + value + " with " + actual);
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java +51 −55
@@ -15,6 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.querybuilder.BuiltStatement;
19+import com.datastax.driver.core.utils.CassandraVersion;
20+import com.google.common.collect.ImmutableMap;
21+import com.google.common.reflect.TypeToken;
22+import org.testng.annotations.BeforeMethod;
23+import org.testng.annotations.Test;
24+
1825 import java.math.BigDecimal;
1926 import java.math.BigInteger;
2027 import java.util.Collection;
@@ -22,24 +29,12 @@
2229 import java.util.Map;
2330 import java.util.Set;
2431
25-import com.google.common.collect.ImmutableMap;
26-import com.google.common.reflect.TypeToken;
27-import org.testng.annotations.BeforeMethod;
28-import org.testng.annotations.Test;
29-
32+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3033 import static com.google.common.collect.Lists.newArrayList;
3134 import static com.google.common.collect.Sets.newHashSet;
3235 import static org.assertj.core.api.Assertions.assertThat;
3336
34-import com.datastax.driver.core.querybuilder.BuiltStatement;
35-import com.datastax.driver.core.utils.CassandraVersion;
36-
37-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
38-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
39-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
40-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
41-
42-@CassandraVersion(major=2.0)
37+@CassandraVersion(major = 2.0)
4338 public class TypeCodecCollectionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
4439
4540 private final String insertQuery = "INSERT INTO \"myTable2\" (c_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal) VALUES (?, ?, ?, ?, ?, ?, ?)";
@@ -60,30 +55,30 @@
6055 @Override
6156 protected Collection<String> getTableDefinitions() {
6257 return newArrayList(
63- "CREATE TABLE IF NOT EXISTS \"myTable2\" ("
64- + "c_int int PRIMARY KEY, "
65- + "l_int list<int>, "
66- + "l_bigint list<bigint>, "
67- + "s_float set<float>, "
68- + "s_double set<double>, "
69- + "m_varint map<int,varint>, "
70- + "m_decimal map<int,decimal>"
71- + ")");
58+ "CREATE TABLE IF NOT EXISTS \"myTable2\" ("
59+ + "c_int int PRIMARY KEY, "
60+ + "l_int list<int>, "
61+ + "l_bigint list<bigint>, "
62+ + "s_float set<float>, "
63+ + "s_double set<double>, "
64+ + "m_varint map<int,varint>, "
65+ + "m_decimal map<int,decimal>"
66+ + ")");
7267 }
7368
7469 @BeforeMethod(groups = "short")
7570 public void createBuiltStatements() throws Exception {
7671 insertStmt = insertInto("\"myTable2\"")
77- .value("c_int", bindMarker())
78- .value("l_int", bindMarker())
79- .value("l_bigint", bindMarker())
80- .value("s_float", bindMarker())
81- .value("s_double", bindMarker())
82- .value("m_varint", bindMarker())
83- .value("m_decimal", bindMarker());
72+ .value("c_int", bindMarker())
73+ .value("l_int", bindMarker())
74+ .value("l_bigint", bindMarker())
75+ .value("s_float", bindMarker())
76+ .value("s_double", bindMarker())
77+ .value("m_varint", bindMarker())
78+ .value("m_decimal", bindMarker());
8479 selectStmt = select("c_int", "l_int", "l_bigint", "s_float", "s_double", "m_varint", "m_decimal")
85- .from("\"myTable2\"")
86- .where(eq("c_int", bindMarker()));
80+ .from("\"myTable2\"")
81+ .where(eq("c_int", bindMarker()));
8782 }
8883
8984 @Test(groups = "short")
@@ -106,17 +101,17 @@
106101 @Test(groups = "short")
107102 public void should_use_collection_codecs_with_prepared_statements_2() {
108103 session.execute(session.prepare(insertQuery).bind()
109- .setInt(0, n_int)
110- .setList(1, l_int)
111- .setList(2, l_bigint, Long.class) // variant with element type explicitly set
112- .setSet(3, s_float)
113- .setSet(4, s_double, TypeToken.of(Double.class)) // variant with element type explicitly set
114- .setMap(5, m_varint)
115- .setMap(6, m_decimal, Integer.class, BigDecimal.class) // variant with element type explicitly set
104+ .setInt(0, n_int)
105+ .setList(1, l_int)
106+ .setList(2, l_bigint, Long.class) // variant with element type explicitly set
107+ .setSet(3, s_float)
108+ .setSet(4, s_double, TypeToken.of(Double.class)) // variant with element type explicitly set
109+ .setMap(5, m_varint)
110+ .setMap(6, m_decimal, Integer.class, BigDecimal.class) // variant with element type explicitly set
116111 );
117112 PreparedStatement ps = session.prepare(selectQuery);
118113 ResultSet rows = session.execute(ps.bind()
119- .setInt(0, n_int)
114+ .setInt(0, n_int)
120115 );
121116 Row row = rows.one();
122117 assertRow(row);
@@ -125,13 +120,13 @@
125120 @Test(groups = "short")
126121 public void should_use_collection_codecs_with_prepared_statements_3() {
127122 session.execute(session.prepare(insertQuery).bind()
128- .setInt(0, n_int)
129- .set(1, l_int, TypeTokens.listOf(Integer.class))
130- .set(2, l_bigint, TypeTokens.listOf(Long.class))
131- .set(3, s_float, TypeTokens.setOf(Float.class))
132- .set(4, s_double, TypeTokens.setOf(Double.class))
133- .set(5, m_varint, TypeTokens.mapOf(Integer.class, BigInteger.class))
134- .set(6, m_decimal, TypeTokens.mapOf(Integer.class, BigDecimal.class))
123+ .setInt(0, n_int)
124+ .set(1, l_int, TypeTokens.listOf(Integer.class))
125+ .set(2, l_bigint, TypeTokens.listOf(Long.class))
126+ .set(3, s_float, TypeTokens.setOf(Float.class))
127+ .set(4, s_double, TypeTokens.setOf(Double.class))
128+ .set(5, m_varint, TypeTokens.mapOf(Integer.class, BigInteger.class))
129+ .set(6, m_decimal, TypeTokens.mapOf(Integer.class, BigDecimal.class))
135130 );
136131 PreparedStatement ps = session.prepare(selectQuery);
137132 ResultSet rows = session.execute(ps.bind()
@@ -144,21 +139,22 @@
144139 @Test(groups = "short")
145140 public void should_use_collection_codecs_with_built_statements() {
146141 session.execute(session.prepare(insertStmt).bind()
147- .setInt(0, n_int)
148- .set(1, l_int, TypeTokens.listOf(Integer.class))
149- .set(2, l_bigint, TypeTokens.listOf(Long.class))
150- .set(3, s_float, TypeTokens.setOf(Float.class))
151- .set(4, s_double, TypeTokens.setOf(Double.class))
152- .set(5, m_varint, TypeTokens.mapOf(Integer.class, BigInteger.class))
153- .set(6, m_decimal, TypeTokens.mapOf(Integer.class, BigDecimal.class))
142+ .setInt(0, n_int)
143+ .set(1, l_int, TypeTokens.listOf(Integer.class))
144+ .set(2, l_bigint, TypeTokens.listOf(Long.class))
145+ .set(3, s_float, TypeTokens.setOf(Float.class))
146+ .set(4, s_double, TypeTokens.setOf(Double.class))
147+ .set(5, m_varint, TypeTokens.mapOf(Integer.class, BigInteger.class))
148+ .set(6, m_decimal, TypeTokens.mapOf(Integer.class, BigDecimal.class))
154149 );
155150 PreparedStatement ps = session.prepare(selectStmt);
156151 ResultSet rows = session.execute(ps.bind()
157- .setInt(0, n_int)
152+ .setInt(0, n_int)
158153 );
159154 Row row = rows.one();
160155 assertRow(row);
161156 }
157+
162158 private void assertRow(Row row) {
163159 assertThat(row.getInt(0)).isEqualTo(n_int);
164160 assertThat(row.getList(1, Integer.class)).isEqualTo(l_int);
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecEncapsulationIntegrationTest.java +104 −85
@@ -15,29 +15,24 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.math.BigDecimal;
19-import java.math.BigInteger;
20-import java.nio.ByteBuffer;
21-import java.util.Collection;
22-
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.datastax.driver.core.querybuilder.BuiltStatement;
20+import com.datastax.driver.core.utils.CassandraVersion;
2321 import com.google.common.base.Objects;
2422 import com.google.common.reflect.TypeParameter;
2523 import com.google.common.reflect.TypeToken;
2624 import org.testng.annotations.BeforeMethod;
2725 import org.testng.annotations.Test;
2826
27+import java.math.BigDecimal;
28+import java.math.BigInteger;
29+import java.nio.ByteBuffer;
30+import java.util.Collection;
31+
32+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2933 import static com.google.common.collect.Lists.newArrayList;
3034 import static org.assertj.core.api.Assertions.assertThat;
3135
32-import com.datastax.driver.core.exceptions.InvalidTypeException;
33-import com.datastax.driver.core.querybuilder.BuiltStatement;
34-import com.datastax.driver.core.utils.CassandraVersion;
35-
36-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
37-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
38-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
39-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
40-
4136 public class TypeCodecEncapsulationIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
4237
4338 private final String insertQuery = "INSERT INTO \"myTable\" (c_int, c_bigint, c_float, c_double, c_varint, c_decimal) VALUES (?, ?, ?, ?, ?, ?)";
@@ -57,58 +52,58 @@
5752 @Override
5853 protected Collection<String> getTableDefinitions() {
5954 return newArrayList(
60- "CREATE TABLE \"myTable\" ("
61- + "c_int int, "
62- + "c_bigint bigint, "
63- + "c_float float, "
64- + "c_double double, "
65- + "c_varint varint, "
66- + "c_decimal decimal, "
67- + "PRIMARY KEY (c_int, c_bigint)"
68- + ")"
55+ "CREATE TABLE \"myTable\" ("
56+ + "c_int int, "
57+ + "c_bigint bigint, "
58+ + "c_float float, "
59+ + "c_double double, "
60+ + "c_varint varint, "
61+ + "c_decimal decimal, "
62+ + "PRIMARY KEY (c_int, c_bigint)"
63+ + ")"
6964 );
7065 }
7166
7267 @Override
7368 protected Cluster.Builder configure(Cluster.Builder builder) {
7469 return builder.withCodecRegistry(
75- new CodecRegistry()
76- .register(
77- new NumberBoxCodec<Integer>(TypeCodec.cint()),
78- new NumberBoxCodec<Long>(TypeCodec.bigint()),
79- new NumberBoxCodec<Float>(TypeCodec.cfloat()),
80- new NumberBoxCodec<Double>(TypeCodec.cdouble()),
81- new NumberBoxCodec<BigInteger>(TypeCodec.varint()),
82- new NumberBoxCodec<BigDecimal>(TypeCodec.decimal())
83- )
70+ new CodecRegistry()
71+ .register(
72+ new NumberBoxCodec<Integer>(TypeCodec.cint()),
73+ new NumberBoxCodec<Long>(TypeCodec.bigint()),
74+ new NumberBoxCodec<Float>(TypeCodec.cfloat()),
75+ new NumberBoxCodec<Double>(TypeCodec.cdouble()),
76+ new NumberBoxCodec<BigInteger>(TypeCodec.varint()),
77+ new NumberBoxCodec<BigDecimal>(TypeCodec.decimal())
78+ )
8479 );
8580 }
8681
8782 @BeforeMethod(groups = "short")
8883 public void createBuiltStatements() throws Exception {
8984 insertStmt = insertInto("\"myTable\"")
90- .value("c_int", bindMarker())
91- .value("c_bigint", bindMarker())
92- .value("c_float", bindMarker())
93- .value("c_double", bindMarker())
94- .value("c_varint", bindMarker())
95- .value("c_decimal", bindMarker());
85+ .value("c_int", bindMarker())
86+ .value("c_bigint", bindMarker())
87+ .value("c_float", bindMarker())
88+ .value("c_double", bindMarker())
89+ .value("c_varint", bindMarker())
90+ .value("c_decimal", bindMarker());
9691 selectStmt = select("c_int", "c_bigint", "c_float", "c_double", "c_varint", "c_decimal")
97- .from("\"myTable\"")
98- .where(eq("c_int", bindMarker()))
99- .and(eq("c_bigint", bindMarker()));
92+ .from("\"myTable\"")
93+ .where(eq("c_int", bindMarker()))
94+ .and(eq("c_bigint", bindMarker()));
10095 }
10196
10297 @Test(groups = "short")
103- @CassandraVersion(major=2.0)
98+ @CassandraVersion(major = 2.0)
10499 public void should_use_custom_codecs_with_simple_statements() {
105100 session.execute(insertQuery,
106- n_int,
107- new NumberBox<Long>(n_bigint),
108- new NumberBox<Float>(n_float),
109- new NumberBox<Double>(n_double),
110- new NumberBox<BigInteger>(n_varint),
111- new NumberBox<BigDecimal>(n_decimal));
101+ n_int,
102+ new NumberBox<Long>(n_bigint),
103+ new NumberBox<Float>(n_float),
104+ new NumberBox<Double>(n_double),
105+ new NumberBox<BigInteger>(n_varint),
106+ new NumberBox<BigDecimal>(n_decimal));
112107 ResultSet rows = session.execute(selectQuery, n_int, new NumberBox<Long>(n_bigint));
113108 Row row = rows.one();
114109 assertRow(row);
@@ -117,12 +112,12 @@
117112 @Test(groups = "short")
118113 public void should_use_custom_codecs_with_prepared_statements_1() {
119114 session.execute(session.prepare(insertQuery).bind(
120- n_int,
121- new NumberBox<Long>(n_bigint),
122- new NumberBox<Float>(n_float),
123- new NumberBox<Double>(n_double),
124- new NumberBox<BigInteger>(n_varint),
125- new NumberBox<BigDecimal>(n_decimal)));
115+ n_int,
116+ new NumberBox<Long>(n_bigint),
117+ new NumberBox<Float>(n_float),
118+ new NumberBox<Double>(n_double),
119+ new NumberBox<BigInteger>(n_varint),
120+ new NumberBox<BigDecimal>(n_decimal)));
126121 PreparedStatement ps = session.prepare(selectQuery);
127122 ResultSet rows = session.execute(ps.bind(n_int, new NumberBox<Long>(n_bigint)));
128123 Row row = rows.one();
@@ -132,17 +127,25 @@
132127 @Test(groups = "short")
133128 public void should_use_custom_codecs_with_prepared_statements_2() {
134129 session.execute(session.prepare(insertQuery).bind()
135- .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {})
136- .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {})
137- .set(2, new NumberBox<Float>(n_float), new TypeToken<NumberBox<Float>>() {})
138- .set(3, new NumberBox<Double>(n_double), new TypeToken<NumberBox<Double>>() {})
139- .set(4, new NumberBox<BigInteger>(n_varint), new TypeToken<NumberBox<BigInteger>>() {})
140- .set(5, new NumberBox<BigDecimal>(n_decimal), new TypeToken<NumberBox<BigDecimal>>() {})
130+ .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {
131+ })
132+ .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {
133+ })
134+ .set(2, new NumberBox<Float>(n_float), new TypeToken<NumberBox<Float>>() {
135+ })
136+ .set(3, new NumberBox<Double>(n_double), new TypeToken<NumberBox<Double>>() {
137+ })
138+ .set(4, new NumberBox<BigInteger>(n_varint), new TypeToken<NumberBox<BigInteger>>() {
139+ })
140+ .set(5, new NumberBox<BigDecimal>(n_decimal), new TypeToken<NumberBox<BigDecimal>>() {
141+ })
141142 );
142143 PreparedStatement ps = session.prepare(selectQuery);
143144 ResultSet rows = session.execute(ps.bind()
144- .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {})
145- .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {})
145+ .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {
146+ })
147+ .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {
148+ })
146149 );
147150 Row row = rows.one();
148151 assertRow(row);
@@ -151,12 +154,12 @@
151154 @Test(groups = "short")
152155 public void should_use_custom_codecs_with_built_statements_1() {
153156 session.execute(session.prepare(insertStmt).bind(
154- n_int,
155- new NumberBox<Long>(n_bigint),
156- new NumberBox<Float>(n_float),
157- new NumberBox<Double>(n_double),
158- new NumberBox<BigInteger>(n_varint),
159- new NumberBox<BigDecimal>(n_decimal)));
157+ n_int,
158+ new NumberBox<Long>(n_bigint),
159+ new NumberBox<Float>(n_float),
160+ new NumberBox<Double>(n_double),
161+ new NumberBox<BigInteger>(n_varint),
162+ new NumberBox<BigDecimal>(n_decimal)));
160163 PreparedStatement ps = session.prepare(selectStmt);
161164 ResultSet rows = session.execute(ps.bind(n_int, new NumberBox<Long>(n_bigint)));
162165 Row row = rows.one();
@@ -166,17 +169,25 @@
166169 @Test(groups = "short")
167170 public void should_use_custom_codecs_with_built_statements_2() {
168171 session.execute(session.prepare(insertStmt).bind()
169- .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {})
170- .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {})
171- .set(2, new NumberBox<Float>(n_float), new TypeToken<NumberBox<Float>>() {})
172- .set(3, new NumberBox<Double>(n_double), new TypeToken<NumberBox<Double>>() {})
173- .set(4, new NumberBox<BigInteger>(n_varint), new TypeToken<NumberBox<BigInteger>>() {})
174- .set(5, new NumberBox<BigDecimal>(n_decimal), new TypeToken<NumberBox<BigDecimal>>() {})
172+ .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {
173+ })
174+ .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {
175+ })
176+ .set(2, new NumberBox<Float>(n_float), new TypeToken<NumberBox<Float>>() {
177+ })
178+ .set(3, new NumberBox<Double>(n_double), new TypeToken<NumberBox<Double>>() {
179+ })
180+ .set(4, new NumberBox<BigInteger>(n_varint), new TypeToken<NumberBox<BigInteger>>() {
181+ })
182+ .set(5, new NumberBox<BigDecimal>(n_decimal), new TypeToken<NumberBox<BigDecimal>>() {
183+ })
175184 );
176185 PreparedStatement ps = session.prepare(selectStmt);
177186 ResultSet rows = session.execute(ps.bind()
178- .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {})
179- .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {})
187+ .set(0, new NumberBox<Integer>(n_int), new TypeToken<NumberBox<Integer>>() {
188+ })
189+ .set(1, new NumberBox<Long>(n_bigint), new TypeToken<NumberBox<Long>>() {
190+ })
180191 );
181192 Row row = rows.one();
182193 assertRow(row);
@@ -208,12 +219,18 @@
208219 assertThat(row.get(5, BigDecimal.class)).isEqualTo(n_decimal);
209220 // with get + type, but enforcing NumberBox types
210221 // we get the NumberBox codecs instead
211- assertThat(row.get(0, new TypeToken<NumberBox<Integer>>() {})).isEqualTo(new NumberBox<Integer>(n_int));
212- assertThat(row.get(1, new TypeToken<NumberBox<Long>>() {})).isEqualTo(new NumberBox<Long>(n_bigint));
213- assertThat(row.get(2, new TypeToken<NumberBox<Float>>() {})).isEqualTo(new NumberBox<Float>(n_float));
214- assertThat(row.get(3, new TypeToken<NumberBox<Double>>() {})).isEqualTo(new NumberBox<Double>(n_double));
215- assertThat(row.get(4, new TypeToken<NumberBox<BigInteger>>() {})).isEqualTo(new NumberBox<BigInteger>(n_varint));
216- assertThat(row.get(5, new TypeToken<NumberBox<BigDecimal>>() {})).isEqualTo(new NumberBox<BigDecimal>(n_decimal));
222+ assertThat(row.get(0, new TypeToken<NumberBox<Integer>>() {
223+ })).isEqualTo(new NumberBox<Integer>(n_int));
224+ assertThat(row.get(1, new TypeToken<NumberBox<Long>>() {
225+ })).isEqualTo(new NumberBox<Long>(n_bigint));
226+ assertThat(row.get(2, new TypeToken<NumberBox<Float>>() {
227+ })).isEqualTo(new NumberBox<Float>(n_float));
228+ assertThat(row.get(3, new TypeToken<NumberBox<Double>>() {
229+ })).isEqualTo(new NumberBox<Double>(n_double));
230+ assertThat(row.get(4, new TypeToken<NumberBox<BigInteger>>() {
231+ })).isEqualTo(new NumberBox<BigInteger>(n_varint));
232+ assertThat(row.get(5, new TypeToken<NumberBox<BigDecimal>>() {
233+ })).isEqualTo(new NumberBox<BigDecimal>(n_decimal));
217234 }
218235
219236 private class NumberBoxCodec<T extends Number> extends TypeCodec<NumberBox<T>> {
@@ -221,12 +238,14 @@
221238 private final TypeCodec<T> numberCodec;
222239
223240 protected NumberBoxCodec(TypeCodec<T> numberCodec) {
224- super(numberCodec.getCqlType(), new TypeToken<NumberBox<T>>(){}.where(new TypeParameter<T>(){}, numberCodec.getJavaType()));
241+ super(numberCodec.getCqlType(), new TypeToken<NumberBox<T>>() {
242+ }.where(new TypeParameter<T>() {
243+ }, numberCodec.getJavaType()));
225244 this.numberCodec = numberCodec;
226245 }
227246
228247 public boolean accepts(Object value) {
229- return value instanceof NumberBox && numberCodec.accepts(((NumberBox)value).getNumber());
248+ return value instanceof NumberBox && numberCodec.accepts(((NumberBox) value).getNumber());
230249 }
231250
232251 @Override
@@ -269,7 +288,7 @@
269288 return true;
270289 if (o == null || getClass() != o.getClass())
271290 return false;
272- NumberBox numberBox = (NumberBox)o;
291+ NumberBox numberBox = (NumberBox) o;
273292 return Objects.equal(number, numberBox.number);
274293 }
275294
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedCollectionsIntegrationTest.java +31 −34
@@ -15,9 +15,9 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.*;
20-
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.datastax.driver.core.querybuilder.BuiltStatement;
20+import com.datastax.driver.core.utils.CassandraVersion;
2121 import com.google.common.base.Objects;
2222 import com.google.common.collect.ImmutableMap;
2323 import com.google.common.reflect.TypeToken;
@@ -25,23 +25,18 @@
2525 import org.testng.annotations.BeforeMethod;
2626 import org.testng.annotations.Test;
2727
28+import java.nio.ByteBuffer;
29+import java.util.*;
30+
31+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2832 import static com.google.common.collect.Lists.newArrayList;
2933 import static org.assertj.core.api.Assertions.assertThat;
3034
31-import com.datastax.driver.core.exceptions.InvalidTypeException;
32-import com.datastax.driver.core.querybuilder.BuiltStatement;
33-import com.datastax.driver.core.utils.CassandraVersion;
34-
35-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
36-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
37-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
38-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
39-
4035 /**
4136 * Validates that nested collections are properly encoded,
4237 * even if some inner type requires a custom codec.
4338 */
44-@CassandraVersion(major=2.1)
39+@CassandraVersion(major = 2.1)
4540 public class TypeCodecNestedCollectionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
4641
4742 private final String insertQuery = "INSERT INTO \"myTable\" (pk, v) VALUES (?, ?)";
@@ -54,23 +49,25 @@
5449 private int pk = 42;
5550 private List<Set<Map<MyInt, String>>> v;
5651
57- private TypeToken<List<Set<Map<MyInt, String>>>> listType = new TypeToken<List<Set<Map<MyInt, String>>>>(){};
58- private TypeToken<Set<Map<MyInt, String>>> elementsType = new TypeToken<Set<Map<MyInt, String>>>(){};
52+ private TypeToken<List<Set<Map<MyInt, String>>>> listType = new TypeToken<List<Set<Map<MyInt, String>>>>() {
53+ };
54+ private TypeToken<Set<Map<MyInt, String>>> elementsType = new TypeToken<Set<Map<MyInt, String>>>() {
55+ };
5956
6057 @Override
6158 protected Collection<String> getTableDefinitions() {
6259 return newArrayList(
63- "CREATE TABLE IF NOT EXISTS \"myTable\" ("
64- + "pk int PRIMARY KEY, "
65- + "v frozen<list<frozen<set<frozen<map<int,text>>>>>>"
66- + ")"
60+ "CREATE TABLE IF NOT EXISTS \"myTable\" ("
61+ + "pk int PRIMARY KEY, "
62+ + "v frozen<list<frozen<set<frozen<map<int,text>>>>>>"
63+ + ")"
6764 );
6865 }
6966
7067 @Override
7168 protected Cluster.Builder configure(Cluster.Builder builder) {
7269 return builder.withCodecRegistry(
73- new CodecRegistry().register(new MyIntCodec()) // global User <-> varchar codec
70+ new CodecRegistry().register(new MyIntCodec()) // global User <-> varchar codec
7471 );
7572 }
7673
@@ -86,11 +83,11 @@
8683 @BeforeMethod(groups = "short")
8784 public void createBuiltStatements() throws Exception {
8885 insertStmt = insertInto("\"myTable\"")
89- .value("pk", bindMarker())
90- .value("v", bindMarker());
86+ .value("pk", bindMarker())
87+ .value("v", bindMarker());
9188 selectStmt = select("pk", "v")
92- .from("\"myTable\"")
93- .where(eq("pk", bindMarker()));
89+ .from("\"myTable\"")
90+ .where(eq("pk", bindMarker()));
9491 }
9592
9693 @Test(groups = "short")
@@ -113,12 +110,12 @@
113110 @Test(groups = "short")
114111 public void should_work_with_prepared_statements_2() {
115112 session.execute(session.prepare(insertQuery).bind()
116- .setInt(0, pk)
117- .setList(1, v, elementsType) // variant with element type explicitly set
113+ .setInt(0, pk)
114+ .setList(1, v, elementsType) // variant with element type explicitly set
118115 );
119116 PreparedStatement ps = session.prepare(selectQuery);
120117 ResultSet rows = session.execute(ps.bind()
121- .setInt(0, pk)
118+ .setInt(0, pk)
122119 );
123120 Row row = rows.one();
124121 assertRow(row);
@@ -127,12 +124,12 @@
127124 @Test(groups = "short")
128125 public void should_work_with_prepared_statements_3() {
129126 session.execute(session.prepare(insertQuery).bind()
130- .setInt(0, pk)
131- .set(1, v, listType)
127+ .setInt(0, pk)
128+ .set(1, v, listType)
132129 );
133130 PreparedStatement ps = session.prepare(selectQuery);
134131 ResultSet rows = session.execute(ps.bind()
135- .setInt(0, pk)
132+ .setInt(0, pk)
136133 );
137134 Row row = rows.one();
138135 assertRow(row);
@@ -141,12 +138,12 @@
141138 @Test(groups = "short")
142139 public void should_work_with_built_statements() {
143140 session.execute(session.prepare(insertStmt).bind()
144- .setInt(0, pk)
145- .set(1, v, listType)
141+ .setInt(0, pk)
142+ .set(1, v, listType)
146143 );
147144 PreparedStatement ps = session.prepare(selectStmt);
148145 ResultSet rows = session.execute(ps.bind()
149- .setInt(0, pk)
146+ .setInt(0, pk)
150147 );
151148 Row row = rows.one();
152149 assertRow(row);
@@ -171,7 +168,7 @@
171168 return true;
172169 if (o == null || getClass() != o.getClass())
173170 return false;
174- MyInt myInt = (MyInt)o;
171+ MyInt myInt = (MyInt) o;
175172 return Objects.equal(i, myInt.i);
176173 }
177174
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedUDTAndTupleIntegrationTest.java +17 −19
@@ -15,15 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.utils.CassandraVersion;
2019 import com.google.common.collect.Lists;
21-import com.google.common.collect.Sets;
2220 import org.testng.annotations.Test;
2321
24-import static org.assertj.core.api.Assertions.assertThat;
22+import java.util.Collection;
2523
26-import com.datastax.driver.core.utils.CassandraVersion;
24+import static org.assertj.core.api.Assertions.assertThat;
2725
2826 /**
2927 * This tests that the CodecRegistry is able to create codecs on the fly
@@ -39,20 +37,20 @@
3937 @Override
4038 protected Collection<String> getTableDefinitions() {
4139 return Lists.newArrayList(
42- "CREATE TYPE IF NOT EXISTS \"udt3\" (f3 text)",
43- "CREATE TYPE IF NOT EXISTS \"udt2\" (f2 frozen<udt3>)",
44- "CREATE TYPE IF NOT EXISTS \"udt1\" (f1 frozen<udt2>)",
45- "CREATE TABLE IF NOT EXISTS \"t1\" (pk int PRIMARY KEY, "
46- + "c1 frozen<udt1>, "
47- + "c2 frozen<tuple<tuple<tuple<text>>>>, "
48- + "c3 frozen<tuple<tuple<tuple<udt1>>>>"
49- + ")",
50- // it's important to insert values using CQL literals
51- // so that the CodecRegistry will not be required until
52- // we receive a ResultSet
53- "INSERT INTO t1 (pk, c1) VALUES (1, {f1:{f2:{f3:'foo'}}})",
54- "INSERT INTO t1 (pk, c2) VALUES (2, ((('foo'))))",
55- "INSERT INTO t1 (pk, c3) VALUES (3, ((({f1:{f2:{f3:'foo'}}}))))"
40+ "CREATE TYPE IF NOT EXISTS \"udt3\" (f3 text)",
41+ "CREATE TYPE IF NOT EXISTS \"udt2\" (f2 frozen<udt3>)",
42+ "CREATE TYPE IF NOT EXISTS \"udt1\" (f1 frozen<udt2>)",
43+ "CREATE TABLE IF NOT EXISTS \"t1\" (pk int PRIMARY KEY, "
44+ + "c1 frozen<udt1>, "
45+ + "c2 frozen<tuple<tuple<tuple<text>>>>, "
46+ + "c3 frozen<tuple<tuple<tuple<udt1>>>>"
47+ + ")",
48+ // it's important to insert values using CQL literals
49+ // so that the CodecRegistry will not be required until
50+ // we receive a ResultSet
51+ "INSERT INTO t1 (pk, c1) VALUES (1, {f1:{f2:{f3:'foo'}}})",
52+ "INSERT INTO t1 (pk, c2) VALUES (2, ((('foo'))))",
53+ "INSERT INTO t1 (pk, c3) VALUES (3, ((({f1:{f2:{f3:'foo'}}}))))"
5654 );
5755 }
5856
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecNumbersIntegrationTest.java +30 −31
@@ -15,18 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.CassandraVersion;
19+import org.testng.annotations.Test;
20+
1821 import java.math.BigDecimal;
1922 import java.math.BigInteger;
2023 import java.util.Collection;
2124
22-import org.testng.annotations.Test;
23-
2425 import static com.google.common.collect.Lists.newArrayList;
2526 import static org.assertj.core.api.Assertions.assertThat;
2627
27-import com.datastax.driver.core.utils.CassandraVersion;
28-
29-public class TypeCodecNumbersIntegrationTest extends CCMBridge.PerClassSingleNodeCluster{
28+public class TypeCodecNumbersIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
3029
3130 private final String insertQuery = "INSERT INTO \"myTable\" (c_int, c_bigint, c_float, c_double, c_varint, c_decimal) VALUES (?, ?, ?, ?, ?, ?)";
3231
@@ -43,20 +42,20 @@
4342 @Override
4443 protected Collection<String> getTableDefinitions() {
4544 return newArrayList(
46- "CREATE TABLE \"myTable\" ("
47- + "c_int int, "
48- + "c_bigint bigint, "
49- + "c_float float, "
50- + "c_double double, "
51- + "c_varint varint, "
52- + "c_decimal decimal, "
53- + "PRIMARY KEY (c_int, c_bigint)"
54- + ")"
45+ "CREATE TABLE \"myTable\" ("
46+ + "c_int int, "
47+ + "c_bigint bigint, "
48+ + "c_float float, "
49+ + "c_double double, "
50+ + "c_varint varint, "
51+ + "c_decimal decimal, "
52+ + "PRIMARY KEY (c_int, c_bigint)"
53+ + ")"
5554 );
5655 }
5756
5857 @Test(groups = "short")
59- @CassandraVersion(major=2.0)
58+ @CassandraVersion(major = 2.0)
6059 public void should_use_defaut_codecs_with_simple_statements() {
6160 session.execute(insertQuery, n_int, n_bigint, n_float, n_double, n_varint, n_decimal);
6261 ResultSet rows = session.execute(selectQuery, n_int, n_bigint);
@@ -76,17 +75,17 @@
7675 @Test(groups = "short")
7776 public void should_use_default_codecs_with_prepared_statements_2() {
7877 session.execute(session.prepare(insertQuery).bind()
79- .setInt(0, n_int)
80- .setLong(1, n_bigint)
81- .setFloat(2, n_float)
82- .setDouble(3, n_double)
83- .setVarint(4, n_varint)
84- .setDecimal(5, n_decimal)
78+ .setInt(0, n_int)
79+ .setLong(1, n_bigint)
80+ .setFloat(2, n_float)
81+ .setDouble(3, n_double)
82+ .setVarint(4, n_varint)
83+ .setDecimal(5, n_decimal)
8584 );
8685 PreparedStatement ps = session.prepare(selectQuery);
8786 ResultSet rows = session.execute(ps.bind()
88- .setInt(0, n_int)
89- .setLong(1, n_bigint)
87+ .setInt(0, n_int)
88+ .setLong(1, n_bigint)
9089 );
9190 Row row = rows.one();
9291 assertRow(row);
@@ -95,17 +94,17 @@
9594 @Test(groups = "short")
9695 public void should_use_default_codecs_with_prepared_statements_3() {
9796 session.execute(session.prepare(insertQuery).bind()
98- .set(0, n_int, Integer.class)
99- .set(1, n_bigint, Long.class)
100- .set(2, n_float, Float.class)
101- .set(3, n_double, Double.class)
102- .set(4, n_varint, BigInteger.class)
103- .set(5, n_decimal, BigDecimal.class)
97+ .set(0, n_int, Integer.class)
98+ .set(1, n_bigint, Long.class)
99+ .set(2, n_float, Float.class)
100+ .set(3, n_double, Double.class)
101+ .set(4, n_varint, BigInteger.class)
102+ .set(5, n_decimal, BigDecimal.class)
104103 );
105104 PreparedStatement ps = session.prepare(selectQuery);
106105 ResultSet rows = session.execute(ps.bind()
107- .setInt(0, n_int)
108- .setLong(1, n_bigint)
106+ .setInt(0, n_int)
107+ .setLong(1, n_bigint)
109108 );
110109 Row row = rows.one();
111110 assertRow(row);
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java +22 −21
@@ -15,18 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.google.common.reflect.TypeToken;
20+import org.testng.annotations.Test;
21+
1822 import java.nio.ByteBuffer;
1923 import java.util.Collection;
2024 import java.util.List;
2125
22-import com.google.common.reflect.TypeToken;
23-import org.testng.annotations.Test;
24-
2526 import static com.google.common.collect.Lists.newArrayList;
2627 import static org.assertj.core.api.Assertions.assertThat;
2728
28-import com.datastax.driver.core.exceptions.InvalidTypeException;
29-
3029 /**
3130 * Test an edge case where the user register 2 codecs for the same Java type (here, String).
3231 * SimpleStatements become almost unusable in these cases, but we are adding tests
@@ -41,18 +40,18 @@
4140 @Override
4241 protected Collection<String> getTableDefinitions() {
4342 return newArrayList(
44- "CREATE TABLE \"myTable\" ("
45- + "c_int int PRIMARY KEY, "
46- + "l_int list<int>, "
47- + "c_text text "
48- + ")"
43+ "CREATE TABLE \"myTable\" ("
44+ + "c_int int PRIMARY KEY, "
45+ + "l_int list<int>, "
46+ + "c_text text "
47+ + ")"
4948 );
5049 }
5150
5251 @Override
5352 protected Cluster.Builder configure(Cluster.Builder builder) {
5453 return builder.withCodecRegistry(
55- new CodecRegistry().register(new IntToStringCodec())
54+ new CodecRegistry().register(new IntToStringCodec())
5655 );
5756 }
5857
@@ -60,16 +59,16 @@
6059 public void should_use_custom_codecs_with_prepared_statements() {
6160 PreparedStatement ps = session.prepare(insertQuery);
6261 session.execute(
63- ps.bind()
64- .setInt(0, 42)
65- .setList(1, newArrayList(42))
66- .setString(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
62+ ps.bind()
63+ .setInt(0, 42)
64+ .setList(1, newArrayList(42))
65+ .setString(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
6766 );
6867 session.execute(
69- ps.bind()
70- .setString(0, "42")
71- .setList(1, newArrayList("42"), String.class)
72- .setString(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
68+ ps.bind()
69+ .setString(0, "42")
70+ .setList(1, newArrayList("42"), String.class)
71+ .setString(2, "42") // here we have the CQL type so VarcharCodec will be used even if IntToStringCodec accepts it
7372 );
7473 ps = session.prepare(selectQuery);
7574 assertRow(session.execute(ps.bind().setInt(0, 42)).one());
@@ -85,8 +84,10 @@
8584 assertThat(row.getList(1, Integer.class)).isEqualTo(newArrayList(42));
8685 assertThat(row.getList(1, String.class)).isEqualTo(newArrayList("42"));
8786 assertThat(row.getObject(1)).isEqualTo(newArrayList(42)); // uses the default codec
88- assertThat(row.get(1, new TypeToken<List<Integer>>() {})).isEqualTo(newArrayList(42));
89- assertThat(row.get(1, new TypeToken<List<String>>() {})).isEqualTo(newArrayList("42"));
87+ assertThat(row.get(1, new TypeToken<List<Integer>>() {
88+ })).isEqualTo(newArrayList(42));
89+ assertThat(row.get(1, new TypeToken<List<String>>() {
90+ })).isEqualTo(newArrayList("42"));
9091 }
9192
9293 private class IntToStringCodec extends TypeCodec<String> {
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java +56 −55
@@ -15,9 +15,9 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.*;
20-
18+import com.datastax.driver.core.UserType.Field;
19+import com.datastax.driver.core.exceptions.CodecNotFoundException;
20+import com.datastax.driver.core.exceptions.InvalidTypeException;
2121 import com.google.common.base.Function;
2222 import com.google.common.base.Joiner;
2323 import com.google.common.base.Strings;
@@ -25,17 +25,14 @@
2525 import com.google.common.reflect.TypeToken;
2626 import org.testng.annotations.Test;
2727
28-import static com.google.common.collect.Lists.newArrayList;
29-import static org.testng.Assert.fail;
30-
31-import com.datastax.driver.core.UserType.Field;
32-import com.datastax.driver.core.exceptions.CodecNotFoundException;
33-import com.datastax.driver.core.exceptions.InvalidTypeException;
28+import java.nio.ByteBuffer;
29+import java.util.*;
3430
3531 import static com.datastax.driver.core.Assertions.assertThat;
36-import static com.datastax.driver.core.TypeTokens.listOf;
3732 import static com.datastax.driver.core.DataType.*;
3833 import static com.datastax.driver.core.ProtocolVersion.V3;
34+import static com.google.common.collect.Lists.newArrayList;
35+import static org.testng.Assert.fail;
3936
4037 public class TypeCodecTest {
4138
@@ -71,7 +68,7 @@
7168 assertThat(codec).isNotNull().accepts(cqlType);
7269 }
7370
74- @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
71+ @Test(groups = "unit", expectedExceptions = {IllegalArgumentException.class})
7572 public void collectionTooLargeTest() throws Exception {
7673 DataType cqlType = DataType.list(DataType.cint());
7774 List<Integer> list = Collections.nCopies(65536, 1);
@@ -79,7 +76,7 @@
7976 codec.serialize(list, ProtocolVersion.V2);
8077 }
8178
82- @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
79+ @Test(groups = "unit", expectedExceptions = {IllegalArgumentException.class})
8380 public void collectionElementTooLargeTest() throws Exception {
8481 DataType cqlType = DataType.list(DataType.text());
8582 List<String> list = newArrayList(Strings.repeat("a", 65536));
@@ -103,57 +100,57 @@
103100 String ascii = "The quick brown fox jumps over the lazy dog!";
104101 String utf8 = "Dès Noël, où un zéphyr haï me vêt de glaçons würmiens, je dîne d’exquis rôtis de bœuf au kir à l’aÿ d’âge mûr & cætera!";
105102 assertThat(asciiCodec)
106- .accepts(String.class)
107- .accepts(ascii())
108- .doesNotAccept(varchar())
109- .doesNotAccept(text())
110- .accepts(ascii)
111- .canSerialize(ascii)
112- .cannotSerialize(utf8);
103+ .accepts(String.class)
104+ .accepts(ascii())
105+ .doesNotAccept(varchar())
106+ .doesNotAccept(text())
107+ .accepts(ascii)
108+ .canSerialize(ascii)
109+ .cannotSerialize(utf8);
113110 assertThat(utf8Codec)
114- .accepts(String.class)
115- .doesNotAccept(ascii())
116- .accepts(varchar())
117- .accepts(text())
118- .accepts(ascii)
119- .accepts(utf8)
120- .canSerialize(ascii)
121- .canSerialize(utf8);
111+ .accepts(String.class)
112+ .doesNotAccept(ascii())
113+ .accepts(varchar())
114+ .accepts(text())
115+ .accepts(ascii)
116+ .accepts(utf8)
117+ .canSerialize(ascii)
118+ .canSerialize(utf8);
122119 }
123120
124121 @Test(groups = "unit")
125122 public void test_varchar_vs_text() {
126123 assertThat(TypeCodec.varchar())
127- .accepts(String.class)
128- .accepts(varchar())
129- .accepts(text());
124+ .accepts(String.class)
125+ .accepts(varchar())
126+ .accepts(text());
130127 assertThat(TypeCodec.list(TypeCodec.varchar()))
131- .accepts(list(varchar()))
132- .accepts(list(text()));
128+ .accepts(list(varchar()))
129+ .accepts(list(text()));
133130 assertThat(TypeCodec.set(TypeCodec.varchar()))
134- .accepts(set(varchar()))
135- .accepts(set(text()));
131+ .accepts(set(varchar()))
132+ .accepts(set(text()));
136133 assertThat(TypeCodec.map(TypeCodec.varchar(), TypeCodec.varchar()))
137- .accepts(map(varchar(), varchar()))
138- .accepts(map(varchar(), text()))
139- .accepts(map(text(), varchar()))
140- .accepts(map(text(), text()));
134+ .accepts(map(varchar(), varchar()))
135+ .accepts(map(varchar(), text()))
136+ .accepts(map(text(), varchar()))
137+ .accepts(map(text(), text()));
141138 TupleType t1 = new TupleType(newArrayList(varchar(), varchar()), V3, new CodecRegistry());
142139 TupleType t2 = new TupleType(newArrayList(text(), varchar()), V3, new CodecRegistry());
143140 TupleType t3 = new TupleType(newArrayList(varchar(), text()), V3, new CodecRegistry());
144141 TupleType t4 = new TupleType(newArrayList(text(), text()), V3, new CodecRegistry());
145142 assertThat(TypeCodec.tuple(t1))
146- .accepts(t2)
147- .accepts(t3)
148- .accepts(t4);
143+ .accepts(t2)
144+ .accepts(t3)
145+ .accepts(t4);
149146 UserType u1 = new UserType("ks", "table", newArrayList(new Field("f1", varchar()), new Field("f2", varchar())), V3, new CodecRegistry());
150147 UserType u2 = new UserType("ks", "table", newArrayList(new Field("f1", text()), new Field("f2", varchar())), V3, new CodecRegistry());
151148 UserType u3 = new UserType("ks", "table", newArrayList(new Field("f1", varchar()), new Field("f2", text())), V3, new CodecRegistry());
152149 UserType u4 = new UserType("ks", "table", newArrayList(new Field("f1", text()), new Field("f2", text())), V3, new CodecRegistry());
153150 assertThat(TypeCodec.userType(u1))
154- .accepts(u2)
155- .accepts(u3)
156- .accepts(u4);
151+ .accepts(u2)
152+ .accepts(u3)
153+ .accepts(u4);
157154 }
158155
159156 @Test(groups = "unit")
@@ -170,12 +167,14 @@
170167 //ok
171168 }
172169 TypeCodec<List<A>> expected = TypeCodec.list(aCodec);
173- TypeCodec<List<A>> actual = codecRegistry.codecFor(list(cint()), new TypeToken<List<A>>(){});
170+ TypeCodec<List<A>> actual = codecRegistry.codecFor(list(cint()), new TypeToken<List<A>>() {
171+ });
174172 assertThat(actual.getCqlType()).isEqualTo(expected.getCqlType());
175173 assertThat(actual.getJavaType()).isEqualTo(expected.getJavaType());
176174 // cannot work: List<B> is not assignable to List<A>
177175 try {
178- codecRegistry.codecFor(list(cint()), new TypeToken<List<B>>(){});
176+ codecRegistry.codecFor(list(cint()), new TypeToken<List<B>>() {
177+ });
179178 fail();
180179 } catch (CodecNotFoundException e) {
181180 //ok
@@ -191,13 +190,15 @@
191190 }
192191 assertThat(codecRegistry.codecFor(cint(), B.class)).isNotNull().isSameAs(bCodec);
193192 try {
194- codecRegistry.codecFor(list(cint()), new TypeToken<List<A>>(){});
193+ codecRegistry.codecFor(list(cint()), new TypeToken<List<A>>() {
194+ });
195195 fail();
196196 } catch (CodecNotFoundException e) {
197197 // ok
198198 }
199199 TypeCodec<List<B>> expectedB = TypeCodec.list(bCodec);
200- TypeCodec<List<B>> actualB = codecRegistry.codecFor(list(cint()), new TypeToken<List<B>>(){});
200+ TypeCodec<List<B>> actualB = codecRegistry.codecFor(list(cint()), new TypeToken<List<B>>() {
201+ });
201202 assertThat(actualB.getCqlType()).isEqualTo(expectedB.getCqlType());
202203 assertThat(actualB.getJavaType()).isEqualTo(expectedB.getJavaType());
203204 }
@@ -218,9 +219,9 @@
218219 public void should_deserialize_empty_buffer_as_udt_with_null_values() {
219220 CodecRegistry codecRegistry = new CodecRegistry();
220221 UserType udt = new UserType("ks", "t", Arrays.asList(
221- new UserType.Field("t", DataType.text()),
222- new UserType.Field("i", DataType.cint()),
223- new UserType.Field("l", DataType.list(DataType.text()))
222+ new UserType.Field("t", DataType.text()),
223+ new UserType.Field("i", DataType.cint()),
224+ new UserType.Field("l", DataType.list(DataType.text()))
224225 ), ProtocolVersion.NEWEST_SUPPORTED, codecRegistry);
225226 UDTValue expected = udt.newValue();
226227 expected.setString("t", null);
@@ -245,9 +246,9 @@
245246 TypeCodec<UUID> codec = codecRegistry.codecFor(DataType.timeuuid(), type4UUID);
246247 // Should resolve the TimeUUIDCodec, but not serialize/format a type4 uuid with it.
247248 assertThat(codec).isSameAs(TypeCodec.timeUUID())
248- .accepts(UUID.class)
249- .cannotSerialize(type4UUID)
250- .cannotFormat(type4UUID);
249+ .accepts(UUID.class)
250+ .cannotSerialize(type4UUID)
251+ .cannotFormat(type4UUID);
251252 }
252253
253254
@@ -294,7 +295,7 @@
294295 throw new UnsupportedOperationException();
295296 }
296297 }
297-
298+
298299 class A {
299300
300301 int i = 0;
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTupleIntegrationTest.java +17 −19
@@ -15,18 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.Collections;
20-import java.util.UUID;
21-
18+import com.datastax.driver.core.utils.CassandraVersion;
2219 import com.google.common.collect.Lists;
2320 import org.testng.annotations.Test;
2421
25-import static org.assertj.core.api.Assertions.assertThat;
26-
27-import com.datastax.driver.core.utils.CassandraVersion;
22+import java.util.Collection;
23+import java.util.Collections;
24+import java.util.UUID;
2825
2926 import static com.datastax.driver.core.DataType.cfloat;
27+import static org.assertj.core.api.Assertions.assertThat;
3028
3129 @CassandraVersion(major = 2.1)
3230 public class TypeCodecTupleIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -46,7 +44,7 @@
4644 @Override
4745 protected Collection<String> getTableDefinitions() {
4846 return Lists.newArrayList(
49- "CREATE TABLE IF NOT EXISTS \"users\" (id uuid PRIMARY KEY, name text, location frozen<tuple<float,float>>)"
47+ "CREATE TABLE IF NOT EXISTS \"users\" (id uuid PRIMARY KEY, name text, location frozen<tuple<float,float>>)"
5048 );
5149 }
5250
@@ -96,15 +94,15 @@
9694 public void should_handle_tuples_with_custom_codecs() {
9795 CodecRegistry codecRegistry = new CodecRegistry();
9896 Cluster cluster = Cluster.builder()
99- .addContactPointsWithPorts(Collections.singleton(hostAddress))
100- .withCodecRegistry(codecRegistry)
101- .build();
97+ .addContactPointsWithPorts(Collections.singleton(hostAddress))
98+ .withCodecRegistry(codecRegistry)
99+ .build();
102100
103101 try {
104102 Session session = cluster.connect(keyspace);
105103 setUpTupleTypes(cluster);
106104 codecRegistry
107- .register(new LocationCodec(TypeCodec.tuple(locationType)))
105+ .register(new LocationCodec(TypeCodec.tuple(locationType)))
108106 ;
109107 session.execute(insertQuery, uuid, "John Doe", locationValue);
110108 ResultSet rows = session.execute(selectQuery, uuid);
@@ -132,15 +130,15 @@
132130 public void should_handle_partial_tuples_with_custom_codecs() {
133131 CodecRegistry codecRegistry = new CodecRegistry();
134132 Cluster cluster = Cluster.builder()
135- .addContactPointsWithPorts(Collections.singleton(hostAddress))
136- .withCodecRegistry(codecRegistry)
137- .build();
133+ .addContactPointsWithPorts(Collections.singleton(hostAddress))
134+ .withCodecRegistry(codecRegistry)
135+ .build();
138136
139137 try {
140138 Session session = cluster.connect(keyspace);
141139 setUpTupleTypes(cluster);
142140 codecRegistry
143- .register(new LocationCodec(TypeCodec.tuple(locationType)))
141+ .register(new LocationCodec(TypeCodec.tuple(locationType)))
144142 ;
145143 session.execute(insertQuery, uuid, "John Doe", partialLocationValueInserted);
146144 ResultSet rows = session.execute(selectQuery, uuid);
@@ -191,8 +189,8 @@
191189 private void setUpTupleTypes(Cluster cluster) {
192190 locationType = cluster.getMetadata().newTupleType(cfloat(), cfloat());
193191 locationValue = locationType.newValue()
194- .setFloat(0, 37.387224f)
195- .setFloat(1, -121.9733837f);
192+ .setFloat(0, 37.387224f)
193+ .setFloat(1, -121.9733837f);
196194 // insert a tuple of a different dimension
197195 partialLocationValueInserted = cluster.getMetadata().newTupleType(cfloat()).newValue().setFloat(0, 37.387224f);
198196 // retrieve the partial tuple with null missing values
@@ -239,7 +237,7 @@
239237 if (o == null || getClass() != o.getClass())
240238 return false;
241239
242- Location location = (Location)o;
240+ Location location = (Location) o;
243241
244242 return Float.compare(location.latitude, latitude) == 0 && Float.compare(location.longitude, longitude) == 0;
245243
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecUDTIntegrationTest.java +20 −21
@@ -15,15 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.utils.CassandraVersion;
2019 import com.google.common.collect.Lists;
2120 import com.google.common.collect.Sets;
2221 import org.testng.annotations.Test;
2322
24-import static org.assertj.core.api.Assertions.assertThat;
23+import java.util.*;
2524
26-import com.datastax.driver.core.utils.CassandraVersion;
25+import static org.assertj.core.api.Assertions.assertThat;
2726
2827 @CassandraVersion(major = 2.1)
2928 public class TypeCodecUDTIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -45,9 +44,9 @@
4544 @Override
4645 protected Collection<String> getTableDefinitions() {
4746 return Lists.newArrayList(
48- "CREATE TYPE IF NOT EXISTS \"phone\" (number text, tags set<text>)",
49- "CREATE TYPE IF NOT EXISTS \"address\" (street text, zipcode int, phones list<frozen<phone>>)",
50- "CREATE TABLE IF NOT EXISTS \"users\" (id uuid PRIMARY KEY, name text, address frozen<address>)"
47+ "CREATE TYPE IF NOT EXISTS \"phone\" (number text, tags set<text>)",
48+ "CREATE TYPE IF NOT EXISTS \"address\" (street text, zipcode int, phones list<frozen<phone>>)",
49+ "CREATE TABLE IF NOT EXISTS \"users\" (id uuid PRIMARY KEY, name text, address frozen<address>)"
5150 );
5251 }
5352
@@ -76,9 +75,9 @@
7675 public void should_handle_udts_with_custom_codecs() {
7776 CodecRegistry codecRegistry = new CodecRegistry();
7877 Cluster cluster = Cluster.builder()
79- .addContactPointsWithPorts(Collections.singleton(hostAddress))
80- .withCodecRegistry(codecRegistry)
81- .build();
78+ .addContactPointsWithPorts(Collections.singleton(hostAddress))
79+ .withCodecRegistry(codecRegistry)
80+ .build();
8281
8382 try {
8483 Session session = cluster.connect(keyspace);
@@ -86,8 +85,8 @@
8685 TypeCodec<UDTValue> addressTypeCodec = TypeCodec.userType(addressType);
8786 TypeCodec<UDTValue> phoneTypeCodec = TypeCodec.userType(phoneType);
8887 codecRegistry
89- .register(new AddressCodec(addressTypeCodec, Address.class))
90- .register(new PhoneCodec(phoneTypeCodec, Phone.class))
88+ .register(new AddressCodec(addressTypeCodec, Address.class))
89+ .register(new PhoneCodec(phoneTypeCodec, Phone.class))
9190 ;
9291 session.execute(insertQuery, uuid, "John Doe", address);
9392 ResultSet rows = session.execute(selectQuery, uuid);
@@ -127,15 +126,15 @@
127126 addressType = cluster.getMetadata().getKeyspace(keyspace).getUserType("address");
128127 phoneType = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone");
129128 UDTValue phone1Value = phoneType.newValue()
130- .setString("number", phone1.number)
131- .setSet("tags", phone1.tags);
129+ .setString("number", phone1.number)
130+ .setSet("tags", phone1.tags);
132131 UDTValue phone2Value = phoneType.newValue()
133- .setString("number", phone2.number)
134- .setSet("tags", phone2.tags);
132+ .setString("number", phone2.number)
133+ .setSet("tags", phone2.tags);
135134 addressValue = addressType.newValue()
136- .setString("street", address.street)
137- .setInt(1, address.zipcode)
138- .setList("phones", Lists.newArrayList(phone1Value, phone2Value));
135+ .setString("street", address.street)
136+ .setInt(1, address.zipcode)
137+ .setList("phones", Lists.newArrayList(phone1Value, phone2Value));
139138 }
140139
141140 static class AddressCodec extends MappingCodec<Address, UDTValue> {
@@ -198,7 +197,7 @@
198197 return true;
199198 if (o == null || getClass() != o.getClass())
200199 return false;
201- Address address = (Address)o;
200+ Address address = (Address) o;
202201 return zipcode == address.zipcode && street.equals(address.street) && phones.equals(address.phones);
203202 }
204203
@@ -228,7 +227,7 @@
228227 return true;
229228 if (o == null || getClass() != o.getClass())
230229 return false;
231- Phone phone = (Phone)o;
230+ Phone phone = (Phone) o;
232231 return number.equals(phone.number) && tags.equals(phone.tags);
233232 }
234233
modified driver-core/src/test/java/com/datastax/driver/core/UnresolvedUserTypeTest.java +13 −17
@@ -15,20 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.Collections;
20-import java.util.concurrent.ExecutionException;
21-
18+import com.datastax.driver.core.utils.CassandraVersion;
2219 import com.google.common.collect.Lists;
2320 import org.testng.annotations.Test;
2421
25-import com.datastax.driver.core.utils.CassandraVersion;
22+import java.util.Collection;
23+import java.util.Collections;
24+import java.util.concurrent.ExecutionException;
2625
2726 import static com.datastax.driver.core.Assertions.assertThat;
28-import static com.datastax.driver.core.DataType.cint;
29-import static com.datastax.driver.core.DataType.list;
30-import static com.datastax.driver.core.DataType.map;
31-import static com.datastax.driver.core.DataType.set;
27+import static com.datastax.driver.core.DataType.*;
3228
3329 @CassandraVersion(major = 3.0)
3430 public class UnresolvedUserTypeTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -52,14 +48,14 @@
5248
5349 Topological sort order should be : GH,FE,D,CB,A
5450 */
55- String.format("CREATE TYPE %s.h (f1 int)", keyspace),
56- String.format("CREATE TYPE %s.g (f1 int)", keyspace),
57- String.format("CREATE TYPE %s.\"F\" (f1 frozen<h>)", keyspace),
58- String.format("CREATE TYPE %s.\"E\" (f1 frozen<list<g>>)", keyspace),
59- String.format("CREATE TYPE %s.\"D\" (f1 frozen<tuple<\"F\",g,h>>)", keyspace),
60- String.format("CREATE TYPE %s.\"C\" (f1 frozen<map<\"E\",\"D\">>)", keyspace),
61- String.format("CREATE TYPE %s.\"B\" (f1 frozen<set<\"D\">>)", keyspace),
62- String.format("CREATE TYPE %s.\"A\" (f1 frozen<\"C\">)", keyspace)
51+ String.format("CREATE TYPE %s.h (f1 int)", keyspace),
52+ String.format("CREATE TYPE %s.g (f1 int)", keyspace),
53+ String.format("CREATE TYPE %s.\"F\" (f1 frozen<h>)", keyspace),
54+ String.format("CREATE TYPE %s.\"E\" (f1 frozen<list<g>>)", keyspace),
55+ String.format("CREATE TYPE %s.\"D\" (f1 frozen<tuple<\"F\",g,h>>)", keyspace),
56+ String.format("CREATE TYPE %s.\"C\" (f1 frozen<map<\"E\",\"D\">>)", keyspace),
57+ String.format("CREATE TYPE %s.\"B\" (f1 frozen<set<\"D\">>)", keyspace),
58+ String.format("CREATE TYPE %s.\"A\" (f1 frozen<\"C\">)", keyspace)
6359 );
6460 }
6561
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +28 −23
@@ -15,34 +15,33 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.lang.Exception;
19-import java.math.BigDecimal;
20-import java.math.BigInteger;
21-import java.net.InetAddress;
22-import java.nio.ByteBuffer;
23-import java.util.*;
24-
18+import com.datastax.driver.core.utils.CassandraVersion;
19+import com.google.common.base.Joiner;
2520 import com.google.common.collect.ImmutableMap;
2621 import com.google.common.collect.ImmutableSet;
27-import com.google.common.base.Joiner;
28-
2922 import com.google.common.collect.Lists;
3023 import com.google.common.collect.Sets;
3124 import org.testng.annotations.Test;
32-import static org.testng.Assert.assertEquals;
25+
26+import java.math.BigDecimal;
27+import java.math.BigInteger;
28+import java.net.InetAddress;
29+import java.nio.ByteBuffer;
30+import java.util.*;
3331
3432 import static com.datastax.driver.core.Metadata.quote;
33+import static org.testng.Assert.assertEquals;
3534 import static org.testng.Assert.assertNotEquals;
3635
37-import com.datastax.driver.core.utils.CassandraVersion;
38-
39-@CassandraVersion(major=2.1)
36+@CassandraVersion(major = 2.1)
4037 public class UserTypesTest extends CCMBridge.PerClassSingleNodeCluster {
4138
4239 private final static List<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>(DataType.allPrimitiveTypes(TestUtils.getDesiredProtocolVersion()));
40+
4341 static {
4442 DATA_TYPE_PRIMITIVES.remove(DataType.counter());
4543 }
44+
4645 private final static List<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES =
4746 new ArrayList<DataType.Name>(EnumSet.of(DataType.Name.LIST, DataType.Name.SET, DataType.Name.MAP, DataType.Name.TUPLE));
4847
@@ -92,6 +91,7 @@
9291
9392 /**
9493 * Run simpleWriteReadTest with unprepared requests.
94+ *
9595 * @throws Exception
9696 */
9797 @Test(groups = "short")
@@ -122,6 +122,7 @@
122122
123123 /**
124124 * Test for ensuring udts are defined in a particular keyspace.
125+ *
125126 * @throws Exception
126127 */
127128 @Test(groups = "short")
@@ -166,6 +167,7 @@
166167 /**
167168 * Test for ensuring extra-lengthy udts are handled correctly.
168169 * Original code found in python-driver:integration.standard.test_udts.py:test_udt_sizes
170+ *
169171 * @throws Exception
170172 */
171173 @Test(groups = "short")
@@ -219,6 +221,7 @@
219221 /**
220222 * Test for inserting various types of DATA_TYPE_PRIMITIVES into UDT's.
221223 * Original code found in python-driver:integration.standard.test_udts.py:test_primitive_datatypes
224+ *
222225 * @throws Exception
223226 */
224227 @Test(groups = "short")
@@ -290,7 +293,7 @@
290293 alldatatypes.setTimestamp(index, ((Date) sampleData));
291294 break;
292295 case DATE:
293- alldatatypes.setDate(index, ((LocalDate)sampleData));
296+ alldatatypes.setDate(index, ((LocalDate) sampleData));
294297 break;
295298 case TIME:
296299 alldatatypes.setTime(index, ((Long) sampleData));
@@ -332,6 +335,7 @@
332335 /**
333336 * Test for inserting various types of DATA_TYPE_NON_PRIMITIVE into UDT's
334337 * Original code found in python-driver:integration.standard.test_udts.py:test_nonprimitive_datatypes
338+ *
335339 * @throws Exception
336340 */
337341 @Test(groups = "short")
@@ -351,17 +355,15 @@
351355 for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
352356 for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) {
353357 String typeString;
354- if(DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.MAP) {
358+ if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.MAP) {
355359 typeString = (String.format("%s_%s %s<%s, %s>", Character.toString((char) (startIndex + i)),
356360 Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
357361 DATA_TYPE_PRIMITIVES.get(j).getName(), DATA_TYPE_PRIMITIVES.get(j).getName()));
358- }
359- else if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.TUPLE) {
362+ } else if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.TUPLE) {
360363 typeString = (String.format("%s_%s frozen<%s<%s>>", Character.toString((char) (startIndex + i)),
361- Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
362- DATA_TYPE_PRIMITIVES.get(j).getName()));
363- }
364- else {
364+ Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
365+ DATA_TYPE_PRIMITIVES.get(j).getName()));
366+ } else {
365367 typeString = (String.format("%s_%s %s<%s>", Character.toString((char) (startIndex + i)),
366368 Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
367369 DATA_TYPE_PRIMITIVES.get(j).getName()));
@@ -383,7 +385,7 @@
383385
384386 String index = Character.toString((char) (startIndex + i)) + "_" + Character.toString((char) (startIndex + j));
385387 Object sampleElement = PrimitiveTypeSamples.ALL.get(dataType);
386- switch(name) {
388+ switch (name) {
387389 case LIST:
388390 alldatatypes.setList(index, Lists.newArrayList(sampleElement));
389391 break;
@@ -420,6 +422,7 @@
420422 /**
421423 * Test for ensuring nested UDT's are handled correctly.
422424 * Original code found in python-driver:integration.standard.test_udts.py:test_nested_registered_udts
425+ *
423426 * @throws Exception
424427 */
425428 @Test(groups = "short")
@@ -436,7 +439,7 @@
436439 session.execute("CREATE TYPE depth_0 (age int, name text)");
437440
438441 for (int i = 1; i <= MAX_NESTING_DEPTH; i++) {
439- session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i-1)));
442+ session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1)));
440443 }
441444
442445 session.execute(String.format("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<depth_0>, c frozen<depth_1>, d frozen<depth_2>, e frozen<depth_3>," +
@@ -484,6 +487,7 @@
484487 /**
485488 * Test for inserting null values into UDT's
486489 * Original code found in python-driver:integration.standard.test_udts.py:test_udts_with_nulls
490+ *
487491 * @throws Exception
488492 */
489493 @Test(groups = "short")
@@ -537,6 +541,7 @@
537541
538542 /**
539543 * Test for inserting null values into collections of UDT's
544+ *
540545 * @throws Exception
541546 */
542547 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/VersionNumberTest.java +8 −7
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import org.testng.annotations.Test;
19+
1920 import static org.testng.Assert.assertEquals;
2021
2122 public class VersionNumberTest {
@@ -23,13 +24,13 @@
2324 @Test(groups = "unit")
2425 public void versionNumberTest() {
2526
26- String[] versions = new String[] {
27- "1.2.0",
28- "2.0.0",
29- "2.0.0-beta1",
30- "2.0.0-beta1-SNAPSHOT",
31- "2.0.0-beta1-SNAPSHOT+abc01",
32- "2.0.0.22" // DSE
27+ String[] versions = new String[]{
28+ "1.2.0",
29+ "2.0.0",
30+ "2.0.0-beta1",
31+ "2.0.0-beta1-SNAPSHOT",
32+ "2.0.0-beta1-SNAPSHOT+abc01",
33+ "2.0.0.22" // DSE
3334 };
3435
3536 VersionNumber[] numbers = new VersionNumber[versions.length];
modified driver-core/src/test/java/com/datastax/driver/core/WarningsTest.java +6 −7
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.List;
20-
18+import com.datastax.driver.core.utils.CassandraVersion;
2119 import com.google.common.base.Strings;
2220 import com.google.common.collect.Lists;
2321 import org.testng.annotations.Test;
2422
25-import static org.assertj.core.api.Assertions.assertThat;
23+import java.util.Collection;
24+import java.util.List;
2625
27-import com.datastax.driver.core.utils.CassandraVersion;
26+import static org.assertj.core.api.Assertions.assertThat;
2827
2928 public class WarningsTest extends CCMBridge.PerClassSingleNodeCluster {
3029
@@ -36,7 +35,7 @@
3635 @Override
3736 protected Collection<String> getTableDefinitions() {
3837 return Lists.newArrayList(
39- "CREATE TABLE foo(k int primary key, v text)"
38+ "CREATE TABLE foo(k int primary key, v text)"
4039 );
4140 }
4241
@@ -44,7 +43,7 @@
4443 @Test(groups = "short")
4544 public void should_expose_warnings_on_execution_info() {
4645 ResultSet rs = session.execute(String.format("BEGIN UNLOGGED BATCH INSERT INTO foo (k, v) VALUES (1, '%s') APPLY BATCH",
47- Strings.repeat("1", BATCH_SIZE_WARN_THRESHOLD_IN_BYTES)));
46+ Strings.repeat("1", BATCH_SIZE_WARN_THRESHOLD_IN_BYTES)));
4847
4948 List<String> warnings = rs.getExecutionInfo().getWarnings();
5049 assertThat(warnings).hasSize(1);
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsScassandraTest.java +15 −19
@@ -15,25 +15,21 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18-import java.util.List;
19-import java.util.Map;
20-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.policies.FallthroughRetryPolicy;
2120 import com.google.common.collect.ImmutableList;
2221 import com.google.common.collect.ImmutableMap;
2322 import org.scassandra.Scassandra;
2423 import org.scassandra.http.client.PrimingRequest;
2524 import org.testng.annotations.*;
2625
27-import static org.assertj.core.api.Assertions.assertThat;
28-import static org.assertj.core.api.Assertions.fail;
29-import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
30-import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
31-import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
32-
33-import com.datastax.driver.core.*;
34-import com.datastax.driver.core.policies.FallthroughRetryPolicy;
26+import java.util.List;
27+import java.util.Map;
3528
3629 import static com.datastax.driver.core.ConsistencyLevel.LOCAL_ONE;
30+import static org.assertj.core.api.Assertions.assertThat;
31+import static org.assertj.core.api.Assertions.fail;
32+import static org.scassandra.http.client.PrimingRequest.Result.*;
3733
3834 public class ExceptionsScassandraTest {
3935
@@ -52,14 +48,14 @@
5248 @BeforeMethod(groups = "short")
5349 public void beforeMethod() {
5450 cluster = Cluster.builder()
55- .addContactPoint(CCMBridge.ipOfNode(1))
56- .withRetryPolicy(FallthroughRetryPolicy.INSTANCE)
57- .build();
51+ .addContactPoint(CCMBridge.ipOfNode(1))
52+ .withRetryPolicy(FallthroughRetryPolicy.INSTANCE)
53+ .build();
5854 session = cluster.connect();
5955 host1 = TestUtils.findHost(cluster, 1);
6056 errors = cluster.getMetrics().getErrorMetrics();
6157
62- for(Scassandra node : scassandras.nodes()) {
58+ for (Scassandra node : scassandras.nodes()) {
6359 node.primingClient().clearAllPrimes();
6460 node.activityClient().clearAllRecordedActivity();
6561 }
@@ -116,9 +112,9 @@
116112
117113 protected void simulateError(int hostNumber, PrimingRequest.Result result) {
118114 scassandras.node(hostNumber).primingClient().prime(PrimingRequest.queryBuilder()
119- .withQuery("mock query")
120- .withResult(result)
121- .build());
115+ .withQuery("mock query")
116+ .withResult(result)
117+ .build());
122118 }
123119
124120 private static List<Map<String, ?>> row(String key, String value) {
@@ -135,7 +131,7 @@
135131
136132 @AfterMethod(groups = "short")
137133 public void afterMethod() {
138- for(Scassandra node : scassandras.nodes()) {
134+ for (Scassandra node : scassandras.nodes()) {
139135 node.primingClient().clearAllPrimes();
140136 }
141137 if (cluster != null)
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsTest.java +17 −18
@@ -15,22 +15,21 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.Cluster;
20+import com.datastax.driver.core.TestUtils;
21+import com.datastax.driver.core.WriteType;
22+import org.testng.annotations.Test;
23+
1824 import java.net.InetAddress;
1925 import java.net.InetSocketAddress;
20-import java.util.Locale;
21-
22-import org.testng.annotations.Test;
2326
27+import static com.datastax.driver.core.CCMBridge.ipOfNode;
28+import static com.datastax.driver.core.ConsistencyLevel.LOCAL_QUORUM;
2429 import static org.assertj.core.api.Assertions.assertThat;
2530 import static org.testng.Assert.assertEquals;
2631 import static org.testng.Assert.assertTrue;
2732
28-import com.datastax.driver.core.*;
29-
30-import static com.datastax.driver.core.CCMBridge.ipOfNode;
31-import static com.datastax.driver.core.ConsistencyLevel.LOCAL_QUORUM;
32-import static com.datastax.driver.core.TestUtils.waitForDownWithWait;
33-
3433 /**
3534 * Tests Exception classes with separate clusters per test, when applicable
3635 */
@@ -53,9 +52,9 @@
5352 String table = "TestTable";
5453
5554 String[] cqlCommands = new String[]{
56- String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1),
57- "USE " + keyspace,
58- String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table)
55+ String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1),
56+ "USE " + keyspace,
57+ String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table)
5958 };
6059
6160 // Create the schema once
@@ -185,7 +184,7 @@
185184 public void should_create_proper_invalid_query_exception() {
186185 InvalidQueryException e = new InvalidQueryException("Bad, really bad");
187186 assertThat(e.getMessage()).isEqualTo("Bad, really bad");
188- e = (InvalidQueryException)e.copy();
187+ e = (InvalidQueryException) e.copy();
189188 assertThat(e.getMessage()).isEqualTo("Bad, really bad");
190189 }
191190
@@ -193,7 +192,7 @@
193192 public void should_create_proper_trace_retrieval_exception() {
194193 TraceRetrievalException e = new TraceRetrievalException("Couldn't find any trace of it");
195194 assertThat(e.getMessage()).isEqualTo("Couldn't find any trace of it");
196- e = (TraceRetrievalException)e.copy();
195+ e = (TraceRetrievalException) e.copy();
197196 assertThat(e.getMessage()).isEqualTo("Couldn't find any trace of it");
198197 }
199198
@@ -210,7 +209,7 @@
210209 assertThat(e.getMessage()).isEqualTo("Bad, really bad");
211210 assertThat(e.getAddress()).isEqualTo(address1);
212211 assertThat(e.getHost()).isEqualTo(address1.getAddress());
213- InvalidQueryException e1 = (InvalidQueryException)e.copy();
212+ InvalidQueryException e1 = (InvalidQueryException) e.copy();
214213 assertThat(e1.getMessage()).isEqualTo("Bad, really bad");
215214 }
216215
@@ -232,7 +231,7 @@
232231 assertThat(e.getMessage()).isEqualTo("Missing ) at EOF");
233232 assertThat(e.getAddress()).isEqualTo(address1);
234233 assertThat(e.getHost()).isEqualTo(address1.getAddress());
235- e = (SyntaxError)e.copy();
234+ e = (SyntaxError) e.copy();
236235 assertThat(e.getMessage()).isEqualTo("Missing ) at EOF");
237236 assertThat(e.getAddress()).isEqualTo(address1);
238237 assertThat(e.getHost()).isEqualTo(address1.getAddress());
@@ -244,7 +243,7 @@
244243 assertThat(e.getMessage()).isEqualTo("I'm running headless now");
245244 assertThat(e.getAddress()).isEqualTo(address1);
246245 assertThat(e.getHost()).isEqualTo(address1.getAddress());
247- e = (TruncateException)e.copy();
246+ e = (TruncateException) e.copy();
248247 assertThat(e.getMessage()).isEqualTo("I'm running headless now");
249248 assertThat(e.getAddress()).isEqualTo(address1);
250249 assertThat(e.getHost()).isEqualTo(address1.getAddress());
@@ -256,7 +255,7 @@
256255 assertThat(e.getMessage()).isEqualTo("You talking to me?");
257256 assertThat(e.getAddress()).isEqualTo(address1);
258257 assertThat(e.getHost()).isEqualTo(address1.getAddress());
259- e = (UnauthorizedException)e.copy();
258+ e = (UnauthorizedException) e.copy();
260259 assertThat(e.getMessage()).isEqualTo("You talking to me?");
261260 assertThat(e.getAddress()).isEqualTo(address1);
262261 assertThat(e.getHost()).isEqualTo(address1.getAddress());
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/FunctionExecutionExceptionTest.java +6 −7
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18-import java.util.Collection;
19-
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.utils.CassandraVersion;
2020 import com.google.common.collect.Lists;
2121 import org.testng.annotations.Test;
2222
23-import com.datastax.driver.core.CCMBridge;
24-import com.datastax.driver.core.utils.CassandraVersion;
23+import java.util.Collection;
2524
2625 @CassandraVersion(major = 2.2)
2726 public class FunctionExecutionExceptionTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -29,9 +28,9 @@
2928 @Override
3029 protected Collection<String> getTableDefinitions() {
3130 return Lists.newArrayList(
32- "CREATE TABLE foo (k int primary key, i int, l list<int>)",
33- "INSERT INTO foo (k, i, l) VALUES (1, 1, [1])",
34- "CREATE FUNCTION element_at(l list<int>, i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return (Integer) l.get(i);'"
31+ "CREATE TABLE foo (k int primary key, i int, l list<int>)",
32+ "INSERT INTO foo (k, i, l) VALUES (1, 1, [1])",
33+ "CREATE FUNCTION element_at(l list<int>, i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return (Integer) l.get(i);'"
3534 );
3635 }
3736
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/NoHostAvailableExceptionTest.java +14 −13
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import com.beust.jcommander.internal.Maps;
19+import org.testng.annotations.Test;
20+
1821 import java.io.PrintWriter;
1922 import java.net.InetSocketAddress;
2023 import java.util.Map;
2124
22-import com.beust.jcommander.internal.Maps;
23-import org.testng.annotations.Test;
24-
2525 import static org.assertj.core.api.Assertions.assertThat;
2626
2727 public class NoHostAvailableExceptionTest {
@@ -30,9 +30,9 @@
3030 NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3));
3131 String message = e.getMessage();
3232 assertThat(message).startsWith("All host(s) tried for query failed");
33- assertThat(message).contains( "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)");
34- assertThat(message).contains( "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)");
35- assertThat(message).contains( "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)");
33+ assertThat(message).contains("/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)");
34+ assertThat(message).contains("/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)");
35+ assertThat(message).contains("/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)");
3636 }
3737
3838 @Test(groups = "unit")
@@ -40,9 +40,9 @@
4040 NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(4));
4141 String message = e.getMessage();
4242 assertThat(message).startsWith("All host(s) tried for query failed");
43- assertThat(message).contains( "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)");
44- assertThat(message).contains( "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)");
45- assertThat(message).contains( "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)");
43+ assertThat(message).contains("/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)");
44+ assertThat(message).contains("/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)");
45+ assertThat(message).contains("/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)");
4646 assertThat(message).contains("only showing errors of first 3 hosts, use getErrors() for more details");
4747 }
4848
@@ -51,9 +51,9 @@
5151 NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3));
5252 String message = e.getCustomMessage(3, true, false);
5353 assertThat(message).startsWith("All host(s) tried for query failed (tried:\n");
54- assertThat(message).contains( "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)\n");
55- assertThat(message).contains( "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)\n");
56- assertThat(message).contains( "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)\n");
54+ assertThat(message).contains("/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)\n");
55+ assertThat(message).contains("/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)\n");
56+ assertThat(message).contains("/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)\n");
5757 }
5858
5959 @Test(groups = "unit")
@@ -82,7 +82,8 @@
8282 this.i = i;
8383 }
8484
85- @Override public void printStackTrace(PrintWriter writer) {
85+ @Override
86+ public void printStackTrace(PrintWriter writer) {
8687 writer.printf("mock stack trace %d", i);
8788 }
8889 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +28 −32
@@ -15,9 +15,8 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.List;
19-import java.util.Map;
20-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.DriverException;
2120 import com.google.common.collect.ImmutableList;
2221 import com.google.common.collect.ImmutableMap;
2322 import org.mockito.Mockito;
@@ -26,23 +25,20 @@
2625 import org.testng.annotations.AfterMethod;
2726 import org.testng.annotations.BeforeMethod;
2827
29-import static org.assertj.core.api.Assertions.assertThat;
30-import static org.mockito.Matchers.any;
31-import static org.mockito.Matchers.anyBoolean;
32-import static org.mockito.Matchers.anyInt;
33-import static org.mockito.Mockito.times;
34-
35-import com.datastax.driver.core.*;
36-import com.datastax.driver.core.exceptions.DriverException;
28+import java.util.List;
29+import java.util.Map;
3730
3831 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
32+import static org.assertj.core.api.Assertions.assertThat;
33+import static org.mockito.Matchers.*;
34+import static org.mockito.Mockito.times;
3935
4036 /**
4137 * Base class for retry policy integration tests.
42- *
38+ * <p/>
4339 * We use SCassandra to easily simulate specific errors (unavailable, read timeout...) on nodes,
4440 * and SortingLoadBalancingPolicy to get a predictable order of the query plan (always host1, host2, host3).
45- *
41+ * <p/>
4642 * Note that SCassandra only allows a limited number of test cases, for instance it always returns errors
4743 * with receivedResponses = 0. If that becomes more finely tuneable in the future, we'll be able to add more
4844 * tests in child classes.
@@ -73,17 +69,17 @@
7369 scassandras.init();
7470
7571 cluster = Cluster.builder()
76- .addContactPoint(CCMBridge.ipOfNode(1))
77- .withRetryPolicy(retryPolicy)
78- .withLoadBalancingPolicy(new SortingLoadBalancingPolicy())
79- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
80- .withProtocolVersion(ProtocolVersion.V2)
81- .withPoolingOptions(new PoolingOptions()
82- .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
83- .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
84- .setHeartbeatIntervalSeconds(0))
85- .withNettyOptions(nonQuietClusterCloseOptions)
86- .build();
72+ .addContactPoint(CCMBridge.ipOfNode(1))
73+ .withRetryPolicy(retryPolicy)
74+ .withLoadBalancingPolicy(new SortingLoadBalancingPolicy())
75+ // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
76+ .withProtocolVersion(ProtocolVersion.V2)
77+ .withPoolingOptions(new PoolingOptions()
78+ .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
79+ .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
80+ .setHeartbeatIntervalSeconds(0))
81+ .withNettyOptions(nonQuietClusterCloseOptions)
82+ .build();
8783
8884 session = cluster.connect();
8985
@@ -95,16 +91,16 @@
9591
9692 Mockito.reset(retryPolicy);
9793
98- for(Scassandra node : scassandras.nodes()) {
94+ for (Scassandra node : scassandras.nodes()) {
9995 node.activityClient().clearAllRecordedActivity();
10096 }
10197 }
10298
10399 protected void simulateError(int hostNumber, PrimingRequest.Result result) {
104100 scassandras.node(hostNumber).primingClient().prime(PrimingRequest.queryBuilder()
105- .withQuery("mock query")
106- .withResult(result)
107- .build());
101+ .withQuery("mock query")
102+ .withResult(result)
103+ .build());
108104 }
109105
110106 protected void simulateNormalResponse(int hostNumber) {
@@ -128,23 +124,23 @@
128124
129125 protected void assertOnReadTimeoutWasCalled(int times) {
130126 Mockito.verify(retryPolicy, times(times)).onReadTimeout(
131- any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyBoolean(), anyInt());
127+ any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyBoolean(), anyInt());
132128
133129 }
134130
135131 protected void assertOnWriteTimeoutWasCalled(int times) {
136132 Mockito.verify(retryPolicy, times(times)).onWriteTimeout(
137- any(Statement.class), any(ConsistencyLevel.class), any(WriteType.class), anyInt(), anyInt(), anyInt());
133+ any(Statement.class), any(ConsistencyLevel.class), any(WriteType.class), anyInt(), anyInt(), anyInt());
138134 }
139135
140136 protected void assertOnUnavailableWasCalled(int times) {
141137 Mockito.verify(retryPolicy, times(times)).onUnavailable(
142- any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
138+ any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
143139 }
144140
145141 protected void assertOnRequestErrorWasCalled(int times, Class<? extends DriverException> expected) {
146142 Mockito.verify(retryPolicy, times(times)).onRequestError(
147- any(Statement.class), any(ConsistencyLevel.class), any(expected), anyInt());
143+ any(Statement.class), any(ConsistencyLevel.class), any(expected), anyInt());
148144 }
149145
150146 protected void assertQueried(int hostNumber, int times) {
modified driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java +5 −6
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.Cluster;
1820 import org.testng.annotations.Test;
1921
2022 import static org.assertj.core.api.Assertions.assertThat;
2123
22-import com.datastax.driver.core.CCMBridge;
23-import com.datastax.driver.core.Cluster;
24-
2524 public class CloseableLoadBalancingPolicyTest {
2625 @Test(groups = "short")
2726 public void should_be_invoked_at_shutdown() {
@@ -31,9 +30,9 @@
3130 try {
3231 ccm = CCMBridge.builder("test").withNodes(1).build();
3332 cluster = Cluster.builder()
34- .addContactPoint(CCMBridge.ipOfNode(1))
35- .withLoadBalancingPolicy(policy)
36- .build();
33+ .addContactPoint(CCMBridge.ipOfNode(1))
34+ .withLoadBalancingPolicy(policy)
35+ .build();
3736 cluster.connect();
3837 } finally {
3938 if (cluster != null)
modified driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java +9 −11
@@ -15,19 +15,17 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.*;
1820 import org.scassandra.http.client.PrimingRequest;
1921 import org.testng.annotations.DataProvider;
2022 import org.testng.annotations.Test;
2123
24+import static com.datastax.driver.core.Assertions.assertThat;
2225 import static org.assertj.core.api.Fail.fail;
2326 import static org.scassandra.http.client.PrimingRequest.Result.*;
2427 import static org.scassandra.http.client.PrimingRequest.then;
2528
26-import com.datastax.driver.core.*;
27-import com.datastax.driver.core.exceptions.*;
28-
29-import static com.datastax.driver.core.Assertions.assertThat;
30-
3129 /**
3230 * Integration test with a custom implementation, to test retry and ignore decisions.
3331 */
@@ -76,7 +74,7 @@
7674 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
7775 try {
7876 scassandras
79- .node(1).primingClient().prime(PrimingRequest.queryBuilder()
77+ .node(1).primingClient().prime(PrimingRequest.queryBuilder()
8078 .withQuery("mock query")
8179 .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
8280 .build());
@@ -85,7 +83,7 @@
8583 fail("expected an OperationTimedOutException");
8684 } catch (OperationTimedOutException e) {
8785 assertThat(e.getMessage()).isEqualTo(
88- String.format("[%s] Timed out waiting for server response", host1.getAddress())
86+ String.format("[%s] Timed out waiting for server response", host1.getAddress())
8987 );
9088 }
9189 assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
@@ -103,8 +101,8 @@
103101 @DataProvider
104102 public static Object[][] serverSideErrors() {
105103 return new Object[][]{
106- {server_error, ServerError.class},
107- {overloaded, OverloadedException.class}
104+ {server_error, ServerError.class},
105+ {overloaded, OverloadedException.class}
108106 };
109107 }
110108
@@ -145,8 +143,8 @@
145143 @Override
146144 public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
147145 return (nbRetry == 0)
148- ? RetryDecision.retry(cl)
149- : RetryDecision.rethrow();
146+ ? RetryDecision.retry(cl)
147+ : RetryDecision.rethrow();
150148 }
151149
152150 @Override
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +57 −67
@@ -15,8 +15,8 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.Collection;
19-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.NoHostAvailableException;
2020 import com.google.common.collect.Lists;
2121 import org.apache.log4j.Level;
2222 import org.apache.log4j.Logger;
@@ -27,26 +27,16 @@
2727 import org.testng.annotations.BeforeMethod;
2828 import org.testng.annotations.Test;
2929
30-import static com.google.common.collect.Lists.newArrayList;
31-import static org.mockito.Matchers.any;
32-import static org.mockito.Mockito.spy;
33-import static org.mockito.MockitoAnnotations.initMocks;
34-
35-import com.datastax.driver.core.Cluster;
36-import com.datastax.driver.core.ConsistencyLevel;
37-import com.datastax.driver.core.DataProviders;
38-import com.datastax.driver.core.Host;
39-import com.datastax.driver.core.MemoryAppender;
40-import com.datastax.driver.core.QueryTracker;
41-import com.datastax.driver.core.ScassandraCluster;
42-import com.datastax.driver.core.Session;
43-import com.datastax.driver.core.SocketOptions;
44-import com.datastax.driver.core.exceptions.NoHostAvailableException;
30+import java.util.Collection;
4531
4632 import static com.datastax.driver.core.Assertions.assertThat;
4733 import static com.datastax.driver.core.ScassandraCluster.datacenter;
4834 import static com.datastax.driver.core.TestUtils.findHost;
4935 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
36+import static com.google.common.collect.Lists.newArrayList;
37+import static org.mockito.Matchers.any;
38+import static org.mockito.Mockito.spy;
39+import static org.mockito.MockitoAnnotations.initMocks;
5040
5141 public class DCAwareRoundRobinPolicyTest {
5242
@@ -74,8 +64,8 @@
7464
7565 private Cluster.Builder builder() {
7666 return Cluster.builder()
77- // Close cluster immediately to speed up tests.
78- .withNettyOptions(nonQuietClusterCloseOptions);
67+ // Close cluster immediately to speed up tests.
68+ .withNettyOptions(nonQuietClusterCloseOptions);
7969 }
8070
8171 /**
@@ -89,9 +79,9 @@
8979 // given: a 10 node 2 DC cluster.
9080 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build();
9181 Cluster cluster = builder()
92- .addContactPoint(sCluster.address(1, 1))
93- .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).build())
94- .build();
82+ .addContactPoint(sCluster.address(1, 1))
83+ .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).build())
84+ .build();
9585 try {
9686 sCluster.init();
9787
@@ -101,7 +91,7 @@
10191
10292 // then: each node in local DC should get an equal (10) number of requests.
10393 // then: no node in the remote DC should get a request.
104- for(int i = 1; i <= 5; i++) {
94+ for (int i = 1; i <= 5; i++) {
10595 queryTracker.assertQueried(sCluster, 1, i, 10);
10696 queryTracker.assertQueried(sCluster, 2, i, 0);
10797 }
@@ -116,14 +106,14 @@
116106 *
117107 * @test_category load_balancing:dc_aware
118108 */
119- @Test(groups="short")
109+ @Test(groups = "short")
120110 public void should_not_use_remote_hosts_if_some_nodes_are_up_in_local_dc() {
121111 // given: a 10 node 2 DC cluster with DC policy with 2 remote hosts.
122112 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build();
123113 Cluster cluster = builder()
124- .addContactPoint(sCluster.address(1, 1))
125- .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).withUsedHostsPerRemoteDc(2).build())
126- .build();
114+ .addContactPoint(sCluster.address(1, 1))
115+ .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).withUsedHostsPerRemoteDc(2).build())
116+ .build();
127117
128118 try {
129119 sCluster.init();
@@ -142,7 +132,7 @@
142132 queryTracker.assertQueried(sCluster, 1, 4, 25);
143133
144134 // then: no nodes in the remote DC should have been queried.
145- for(int i = 1; i <= 5; i++) {
135+ for (int i = 1; i <= 5; i++) {
146136 queryTracker.assertQueried(sCluster, 2, i, 0);
147137 }
148138 } finally {
@@ -158,14 +148,14 @@
158148 *
159149 * @test_category load_balancing:dc_aware
160150 */
161- @Test(groups="short")
151+ @Test(groups = "short")
162152 public void should_round_robin_on_remote_hosts_when_no_up_nodes_in_local_dc() {
163153 // given: a 10 node 2 DC cluster with DC policy with 2 remote hosts.
164154 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build();
165155 Cluster cluster = builder()
166- .addContactPoint(sCluster.address(1, 1))
167- .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build())
168- .build();
156+ .addContactPoint(sCluster.address(1, 1))
157+ .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build())
158+ .build();
169159
170160 try {
171161 sCluster.init();
@@ -200,15 +190,15 @@
200190 *
201191 * @test_category load_balancing:dc_aware
202192 */
203- @Test(groups="short", dataProvider="consistencyLevels", dataProviderClass = DataProviders.class)
193+ @Test(groups = "short", dataProvider = "consistencyLevels", dataProviderClass = DataProviders.class)
204194 public void should_only_use_remote_hosts_when_using_non_dc_local_cl(ConsistencyLevel cl) {
205195 // given: a 4 node 2 DC Cluster with a LB policy that specifies to not allow remote dcs for
206196 // a local consistency level.
207197 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
208198 Cluster cluster = builder()
209- .addContactPoint(sCluster.address(1, 1))
210- .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build())
211- .build();
199+ .addContactPoint(sCluster.address(1, 1))
200+ .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build())
201+ .build();
212202
213203 try {
214204 sCluster.init();
@@ -245,17 +235,17 @@
245235 *
246236 * @test_category load_balancing:dc_aware
247237 */
248- @Test(groups="short", dataProvider="consistencyLevels", dataProviderClass = DataProviders.class)
238+ @Test(groups = "short", dataProvider = "consistencyLevels", dataProviderClass = DataProviders.class)
249239 public void should_use_remote_hosts_for_local_cl_when_allowed(ConsistencyLevel cl) {
250240 // given: a 4 node 2 DC Cluster with a LB policy that specifies to allow remote dcs for
251241 // a local consistency level.
252242 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
253243 Cluster cluster = builder()
254- .addContactPoint(sCluster.address(1, 1))
255- .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder()
256- .allowRemoteDCsForLocalConsistencyLevel()
257- .withUsedHostsPerRemoteDc(2).build())
258- .build();
244+ .addContactPoint(sCluster.address(1, 1))
245+ .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder()
246+ .allowRemoteDCsForLocalConsistencyLevel()
247+ .withUsedHostsPerRemoteDc(2).build())
248+ .build();
259249
260250 try {
261251 sCluster.init();
@@ -291,14 +281,14 @@
291281 @Test(groups = "short")
292282 public void should_not_send_requests_to_blacklisted_dc_using_host_filter_policy() {
293283 // given: a 6 node 3 DC cluster with a DCAwareRoundRobinPolicy that is filtering hosts in DC2.
294- ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2,2,2).build();
284+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2, 2).build();
295285 LoadBalancingPolicy loadBalancingPolicy = HostFilterPolicy.fromDCBlackList(
296- DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(),
297- Lists.newArrayList(datacenter(2)));
286+ DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(),
287+ Lists.newArrayList(datacenter(2)));
298288 Cluster cluster = builder()
299- .addContactPoint(sCluster.address(1, 1))
300- .withLoadBalancingPolicy(loadBalancingPolicy)
301- .build();
289+ .addContactPoint(sCluster.address(1, 1))
290+ .withLoadBalancingPolicy(loadBalancingPolicy)
291+ .build();
302292
303293 try {
304294 sCluster.init();
@@ -344,14 +334,14 @@
344334 @Test(groups = "short")
345335 public void should_send_requests_to_whitelisted_dcs_using_host_filter_policy() {
346336 // given: a 6 node 3 DC cluster with a DCAwareRoundRobinPolicy that is whitelisting hosts in DC1 and DC2.
347- ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2,2,2).build();
337+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2, 2).build();
348338 LoadBalancingPolicy loadBalancingPolicy = HostFilterPolicy.fromDCWhiteList(
349- DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(),
350- Lists.newArrayList(datacenter(1), datacenter(2)));
339+ DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(),
340+ Lists.newArrayList(datacenter(1), datacenter(2)));
351341 Cluster cluster = builder()
352- .addContactPoint(sCluster.address(1, 1))
353- .withLoadBalancingPolicy(loadBalancingPolicy)
354- .build();
342+ .addContactPoint(sCluster.address(1, 1))
343+ .withLoadBalancingPolicy(loadBalancingPolicy)
344+ .build();
355345
356346 try {
357347 sCluster.init();
@@ -394,15 +384,15 @@
394384 *
395385 * @test_category load_balancing:dc_aware
396386 */
397- @Test(groups="short")
387+ @Test(groups = "short")
398388 public void should_use_local_dc_from_contact_points_when_not_explicitly_specified() {
399389 // given: a 4 node 2 DC cluster without a local DC specified.
400390 DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().build());
401391 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
402392 Cluster cluster = builder()
403- .addContactPoint(sCluster.address(1, 1))
404- .withLoadBalancingPolicy(policy)
405- .build();
393+ .addContactPoint(sCluster.address(1, 1))
394+ .withLoadBalancingPolicy(policy)
395+ .build();
406396
407397 try {
408398 sCluster.init();
@@ -439,9 +429,9 @@
439429 DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().build());
440430 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
441431 Cluster cluster = builder()
442- .addContactPoints(sCluster.address(1, 1), sCluster.address(2, 1))
443- .withLoadBalancingPolicy(policy)
444- .build();
432+ .addContactPoints(sCluster.address(1, 1), sCluster.address(2, 1))
433+ .withLoadBalancingPolicy(policy)
434+ .build();
445435
446436 try {
447437 sCluster.init();
@@ -477,9 +467,9 @@
477467 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
478468 DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).build());
479469 Cluster cluster = builder()
480- .addContactPoints(sCluster.address(1, 1))
481- .withLoadBalancingPolicy(policy)
482- .build();
470+ .addContactPoints(sCluster.address(1, 1))
471+ .withLoadBalancingPolicy(policy)
472+ .build();
483473
484474 try {
485475 sCluster.init();
@@ -516,9 +506,9 @@
516506 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
517507 DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(3)).build());
518508 Cluster cluster = builder()
519- .addContactPoints(sCluster.address(1, 1), sCluster.address(2, 1))
520- .withLoadBalancingPolicy(policy)
521- .build();
509+ .addContactPoints(sCluster.address(1, 1), sCluster.address(2, 1))
510+ .withLoadBalancingPolicy(policy)
511+ .build();
522512
523513 try {
524514 sCluster.init();
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +23 −24
@@ -17,20 +17,19 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.*;
20-
2120 import org.assertj.core.api.Fail;
2221 import org.scassandra.Scassandra;
2322 import org.scassandra.http.client.PrimingRequest;
2423 import org.testng.annotations.DataProvider;
2524 import org.testng.annotations.Test;
2625
26+import java.util.Collections;
27+
2728 import static org.assertj.core.api.Assertions.assertThat;
2829 import static org.assertj.core.api.Assertions.fail;
2930 import static org.scassandra.http.client.PrimingRequest.Result.*;
3031 import static org.scassandra.http.client.PrimingRequest.then;
3132
32-import java.util.Collections;
33-
3433 public class DefaultRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
3534 public DefaultRetryPolicyIntegrationTest() {
3635 super(DefaultRetryPolicy.INSTANCE);
@@ -115,7 +114,7 @@
115114
116115 Cluster whiteListedCluster = Cluster.builder()
117116 .addContactPoint(CCMBridge.ipOfNode(1))
118- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
117+ // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
119118 .withProtocolVersion(ProtocolVersion.V2)
120119 .withRetryPolicy(retryPolicy)
121120 .withLoadBalancingPolicy(firstHostOnlyPolicy)
@@ -124,7 +123,7 @@
124123 try {
125124 Session whiteListedSession = whiteListedCluster.connect();
126125 // Clear all activity as result of connect.
127- for(Scassandra node : scassandras.nodes()) {
126+ for (Scassandra node : scassandras.nodes()) {
128127 node.activityClient().clearAllRecordedActivity();
129128 }
130129
@@ -133,7 +132,7 @@
133132 try {
134133 query(whiteListedSession);
135134 fail("expected an NoHostAvailableException");
136- } catch(NoHostAvailableException e) {
135+ } catch (NoHostAvailableException e) {
137136 // ok
138137 Throwable error = e.getErrors().get(host1.getSocketAddress());
139138 assertThat(error).isNotNull();
@@ -157,17 +156,17 @@
157156 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
158157 try {
159158 scassandras
160- .node(1).primingClient().prime(PrimingRequest.queryBuilder()
159+ .node(1).primingClient().prime(PrimingRequest.queryBuilder()
161160 .withQuery("mock query")
162161 .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
163162 .build());
164163 scassandras
165- .node(2).primingClient().prime(PrimingRequest.queryBuilder()
164+ .node(2).primingClient().prime(PrimingRequest.queryBuilder()
166165 .withQuery("mock query")
167166 .withThen(then().withFixedDelay(1000L).withRows(row("result", "result2")))
168167 .build());
169168 scassandras
170- .node(3).primingClient().prime(PrimingRequest.queryBuilder()
169+ .node(3).primingClient().prime(PrimingRequest.queryBuilder()
171170 .withQuery("mock query")
172171 .withThen(then().withFixedDelay(1000L).withRows(row("result", "result3")))
173172 .build());
@@ -176,17 +175,17 @@
176175 fail("expected a NoHostAvailableException");
177176 } catch (NoHostAvailableException e) {
178177 assertThat(e.getErrors().keySet()).hasSize(3).containsOnlyOnce(
179- host1.getSocketAddress(),
180- host2.getSocketAddress(),
181- host3.getSocketAddress());
178+ host1.getSocketAddress(),
179+ host2.getSocketAddress(),
180+ host3.getSocketAddress());
182181 assertThat(e.getErrors().values())
183- .hasOnlyElementsOfType(OperationTimedOutException.class)
184- .extractingResultOf("getMessage")
185- .containsOnlyOnce(
186- String.format("[%s] Timed out waiting for server response", host1.getAddress()),
187- String.format("[%s] Timed out waiting for server response", host2.getAddress()),
188- String.format("[%s] Timed out waiting for server response", host3.getAddress())
189- );
182+ .hasOnlyElementsOfType(OperationTimedOutException.class)
183+ .extractingResultOf("getMessage")
184+ .containsOnlyOnce(
185+ String.format("[%s] Timed out waiting for server response", host1.getAddress()),
186+ String.format("[%s] Timed out waiting for server response", host2.getAddress()),
187+ String.format("[%s] Timed out waiting for server response", host3.getAddress())
188+ );
190189 }
191190 assertOnRequestErrorWasCalled(3, OperationTimedOutException.class);
192191 assertThat(errors.getRetries().getCount()).isEqualTo(3);
@@ -203,8 +202,8 @@
203202 @DataProvider
204203 public static Object[][] serverSideErrors() {
205204 return new Object[][]{
206- {server_error, ServerError.class},
207- {overloaded, OverloadedException.class}
205+ {server_error, ServerError.class},
206+ {overloaded, OverloadedException.class}
208207 };
209208 }
210209
@@ -218,9 +217,9 @@
218217 Fail.fail("expected a NoHostAvailableException");
219218 } catch (NoHostAvailableException e) {
220219 assertThat(e.getErrors().keySet()).hasSize(3).containsOnlyOnce(
221- host1.getSocketAddress(),
222- host2.getSocketAddress(),
223- host3.getSocketAddress());
220+ host1.getSocketAddress(),
221+ host2.getSocketAddress(),
222+ host3.getSocketAddress());
224223 assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception);
225224 }
226225 assertOnRequestErrorWasCalled(3, exception);
modified driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingLoadBalancingPolicy.java +4 −4
@@ -15,17 +15,17 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.Collection;
19-import java.util.Iterator;
20-
2118 import com.datastax.driver.core.Cluster;
2219 import com.datastax.driver.core.Host;
2320 import com.datastax.driver.core.HostDistance;
2421 import com.datastax.driver.core.Statement;
2522
23+import java.util.Collection;
24+import java.util.Iterator;
25+
2626 /**
2727 * Base class for tests that want to wrap a policy to add some instrumentation.
28- *
28+ * <p/>
2929 * NB: this is currently only used in tests, but could be provided as a convenience in the production code.
3030 */
3131 public abstract class DelegatingLoadBalancingPolicy implements ChainableLoadBalancingPolicy {
modified driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingSpeculativeExecutionPolicy.java +1 −1
@@ -20,7 +20,7 @@
2020
2121 /**
2222 * Base class for tests that want to wrap a policy to add some instrumentation.
23- *
23+ * <p/>
2424 * NB: this is currently only used in tests, but could be provided as a convenience in the production code.
2525 */
2626 public abstract class DelegatingSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy {
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +7 −12
@@ -15,24 +15,19 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.datastax.driver.core.*;
1819 import com.google.common.base.Objects;
1920 import org.mockito.Mockito;
2021 import org.mockito.verification.VerificationMode;
2122 import org.testng.annotations.Test;
2223
24+import static com.datastax.driver.core.ConsistencyLevel.*;
2325 import static org.assertj.core.api.Assertions.assertThat;
2426 import static org.mockito.Matchers.any;
2527 import static org.mockito.Matchers.anyInt;
2628 import static org.mockito.Mockito.never;
2729 import static org.mockito.Mockito.times;
2830
29-import com.datastax.driver.core.*;
30-
31-import static com.datastax.driver.core.ConsistencyLevel.ALL;
32-import static com.datastax.driver.core.ConsistencyLevel.ONE;
33-import static com.datastax.driver.core.ConsistencyLevel.QUORUM;
34-import static com.datastax.driver.core.ConsistencyLevel.TWO;
35-
3631 /**
3732 * Note: we can't extend {@link AbstractRetryPolicyIntegrationTest} here, because SCassandra doesn't allow custom values for
3833 * receivedResponses in primed responses.
@@ -48,9 +43,9 @@
4843 // 3-node cluster, keyspace with RF = 3
4944 ccm = CCMBridge.builder(this.getClass().getName()).withNodes(3).build();
5045 cluster = Cluster.builder()
51- .addContactPoint(CCMBridge.ipOfNode(1))
52- .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE))
53- .build();
46+ .addContactPoint(CCMBridge.ipOfNode(1))
47+ .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE))
48+ .build();
5449 Session session = cluster.connect();
5550
5651 session.execute("CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}");
@@ -91,7 +86,7 @@
9186 Mockito.reset(retryPolicy);
9287
9388 Statement s = new SimpleStatement("SELECT * FROM test.foo WHERE k = 0")
94- .setConsistencyLevel(requested);
89+ .setConsistencyLevel(requested);
9590
9691 ResultSet rs = session.execute(s);
9792
@@ -104,6 +99,6 @@
10499 // If the level was downgraded the policy should have been invoked
105100 VerificationMode expectedCallsToPolicy = (expected == requested) ? never() : times(1);
106101 Mockito.verify(retryPolicy, expectedCallsToPolicy).onUnavailable(
107- any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
102+ any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
108103 }
109104 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslatorTest.java +5 −5
@@ -55,7 +55,7 @@
5555 InetSocketAddress expectedAddress = new InetSocketAddress("54.32.55.66", 9042);
5656
5757 InitialDirContext mock = mock(InitialDirContext.class);
58- when(mock.getAttributes("5.2.0.192.in-addr.arpa", new String[] { "PTR" }))
58+ when(mock.getAttributes("5.2.0.192.in-addr.arpa", new String[]{"PTR"}))
5959 .thenReturn(new BasicAttributes("PTR", expectedAddress.getHostName()));
6060 EC2MultiRegionAddressTranslator translator = new EC2MultiRegionAddressTranslator(mock);
6161
@@ -79,9 +79,9 @@
7979 public void should_build_reversed_domain_name_for_ip_v4() throws Exception {
8080 InetAddress address = InetAddress.getByName("192.0.2.5");
8181 assertThat(
82- EC2MultiRegionAddressTranslator.reverse(address)
82+ EC2MultiRegionAddressTranslator.reverse(address)
8383 ).isEqualTo(
84- "5.2.0.192.in-addr.arpa"
84+ "5.2.0.192.in-addr.arpa"
8585 );
8686 }
8787
@@ -89,9 +89,9 @@
8989 public void should_build_reversed_domain_name_for_ip_v6() throws Exception {
9090 InetAddress address = InetAddress.getByName("2001:db8::567:89ab");
9191 assertThat(
92- EC2MultiRegionAddressTranslator.reverse(address)
92+ EC2MultiRegionAddressTranslator.reverse(address)
9393 ).isEqualTo(
94- "b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa"
94+ "b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa"
9595 );
9696 }
9797 }
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +6 −7
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.datastax.driver.core.SocketOptions;
19+import com.datastax.driver.core.exceptions.*;
1820 import org.assertj.core.api.Fail;
1921 import org.scassandra.http.client.PrimingRequest;
2022 import org.testng.annotations.DataProvider;
@@ -25,9 +27,6 @@
2527 import static org.scassandra.http.client.PrimingRequest.Result.*;
2628 import static org.scassandra.http.client.PrimingRequest.then;
2729
28-import com.datastax.driver.core.SocketOptions;
29-import com.datastax.driver.core.exceptions.*;
30-
3130 public class FallthroughRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
3231 public FallthroughRetryPolicyIntegrationTest() {
3332 super(FallthroughRetryPolicy.INSTANCE);
@@ -86,7 +85,7 @@
8685 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
8786 try {
8887 scassandras
89- .node(1).primingClient().prime(PrimingRequest.queryBuilder()
88+ .node(1).primingClient().prime(PrimingRequest.queryBuilder()
9089 .withQuery("mock query")
9190 .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
9291 .build());
@@ -95,7 +94,7 @@
9594 Fail.fail("expected an OperationTimedOutException");
9695 } catch (OperationTimedOutException e) {
9796 assertThat(e.getMessage()).isEqualTo(
98- String.format("[%s] Timed out waiting for server response", host1.getAddress())
97+ String.format("[%s] Timed out waiting for server response", host1.getAddress())
9998 );
10099 }
101100 assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
@@ -113,8 +112,8 @@
113112 @DataProvider
114113 public static Object[][] serverSideErrors() {
115114 return new Object[][]{
116- {server_error, ServerError.class},
117- {overloaded, OverloadedException.class}
115+ {server_error, ServerError.class},
116+ {overloaded, OverloadedException.class}
118117 };
119118 }
120119
modified driver-core/src/test/java/com/datastax/driver/core/policies/HostFilterPolicyTest.java +11 −12
@@ -15,9 +15,10 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.net.InetSocketAddress;
19-import java.util.Collection;
20-
18+import com.datastax.driver.core.Cluster;
19+import com.datastax.driver.core.Host;
20+import com.datastax.driver.core.HostDistance;
21+import com.datastax.driver.core.Statement;
2122 import com.google.common.base.Predicate;
2223 import com.google.common.base.Predicates;
2324 import com.google.common.collect.Iterators;
@@ -29,14 +30,12 @@
2930 import org.testng.annotations.BeforeMethod;
3031 import org.testng.annotations.Test;
3132
33+import java.net.InetSocketAddress;
34+import java.util.Collection;
35+
3236 import static org.assertj.core.api.Assertions.assertThat;
3337 import static org.mockito.Mockito.*;
3438
35-import com.datastax.driver.core.Cluster;
36-import com.datastax.driver.core.Host;
37-import com.datastax.driver.core.HostDistance;
38-import com.datastax.driver.core.Statement;
39-
4039 public class HostFilterPolicyTest {
4140 @Mock
4241 Cluster cluster;
@@ -130,12 +129,12 @@
130129 @Test(groups = "unit")
131130 public void should_return_query_plan_of_wrapped_policy() {
132131 when(wrappedPolicy.newQueryPlan(any(String.class), any(Statement.class)))
133- .thenReturn(Iterators.forArray(host1, host2, host3));
132+ .thenReturn(Iterators.forArray(host1, host2, host3));
134133
135134 HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, null);
136135
137136 assertThat(policy.newQueryPlan("keyspace", mock(Statement.class)))
138- .containsExactly(host1, host2, host3);
137+ .containsExactly(host1, host2, host3);
139138 }
140139
141140 @Test(groups = "unit")
@@ -145,7 +144,7 @@
145144 when(host3.getDatacenter()).thenReturn(null);
146145
147146 HostFilterPolicy policy = HostFilterPolicy.fromDCBlackList(wrappedPolicy,
148- Lists.newArrayList("dc2"));
147+ Lists.newArrayList("dc2"));
149148
150149 assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL);
151150 assertThat(policy.distance(host2)).isSameAs(HostDistance.IGNORED);
@@ -159,7 +158,7 @@
159158 when(host3.getDatacenter()).thenReturn(null);
160159
161160 HostFilterPolicy policy = HostFilterPolicy.fromDCWhiteList(wrappedPolicy,
162- Lists.newArrayList("dc1"));
161+ Lists.newArrayList("dc1"));
163162
164163 assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL);
165164 assertThat(policy.distance(host2)).isSameAs(HostDistance.IGNORED);
modified driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java +12 −15
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.*;
1820 import org.scassandra.http.client.PrimingRequest;
1921 import org.testng.annotations.BeforeMethod;
2022 import org.testng.annotations.DataProvider;
@@ -22,14 +24,9 @@
2224
2325 import static org.assertj.core.api.Assertions.assertThat;
2426 import static org.assertj.core.api.Assertions.fail;
25-import static org.scassandra.http.client.PrimingRequest.Result.overloaded;
26-import static org.scassandra.http.client.PrimingRequest.Result.server_error;
27-import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
27+import static org.scassandra.http.client.PrimingRequest.Result.*;
2828 import static org.scassandra.http.client.PrimingRequest.then;
2929
30-import com.datastax.driver.core.*;
31-import com.datastax.driver.core.exceptions.*;
32-
3330 /**
3431 * Integration test with an IdempotenceAwareRetryPolicy.
3532 */
@@ -40,7 +37,7 @@
4037 }
4138
4239 @BeforeMethod(groups = "short")
43- public void setUpDefaultIdempotence(){
40+ public void setUpDefaultIdempotence() {
4441 cluster.getConfiguration().getQueryOptions().setDefaultIdempotence(false);
4542 }
4643
@@ -78,7 +75,7 @@
7875 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
7976 try {
8077 scassandras
81- .node(1).primingClient().prime(PrimingRequest.queryBuilder()
78+ .node(1).primingClient().prime(PrimingRequest.queryBuilder()
8279 .withQuery("mock query")
8380 .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
8481 .build());
@@ -87,7 +84,7 @@
8784 fail("expected an OperationTimedOutException");
8885 } catch (OperationTimedOutException e) {
8986 assertThat(e.getMessage()).isEqualTo(
90- String.format("[%s] Timed out waiting for server response", host1.getAddress())
87+ String.format("[%s] Timed out waiting for server response", host1.getAddress())
9188 );
9289 }
9390 assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
@@ -107,7 +104,7 @@
107104 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
108105 try {
109106 scassandras
110- .node(1).primingClient().prime(PrimingRequest.queryBuilder()
107+ .node(1).primingClient().prime(PrimingRequest.queryBuilder()
111108 .withQuery("mock query")
112109 .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
113110 .build());
@@ -127,8 +124,8 @@
127124 @DataProvider
128125 public static Object[][] serverSideErrors() {
129126 return new Object[][]{
130- {server_error, ServerError.class},
131- {overloaded, OverloadedException.class}
127+ {server_error, ServerError.class},
128+ {overloaded, OverloadedException.class}
132129 };
133130 }
134131
@@ -161,9 +158,9 @@
161158 fail("expected a NoHostAvailableException");
162159 } catch (NoHostAvailableException e) {
163160 assertThat(e.getErrors().keySet()).hasSize(3).containsOnly(
164- host1.getSocketAddress(),
165- host2.getSocketAddress(),
166- host3.getSocketAddress());
161+ host1.getSocketAddress(),
162+ host2.getSocketAddress(),
163+ host3.getSocketAddress());
167164 assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception);
168165 }
169166 assertOnRequestErrorWasCalled(3, exception);
modified driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java +26 −26
@@ -15,23 +15,21 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.concurrent.CountDownLatch;
19-
20-import static java.util.concurrent.TimeUnit.SECONDS;
21-
18+import com.datastax.driver.core.*;
2219 import com.datastax.driver.core.exceptions.NoHostAvailableException;
20+import com.datastax.driver.core.exceptions.ReadTimeoutException;
21+import com.datastax.driver.core.exceptions.UnavailableException;
2322 import org.testng.annotations.Test;
2423
24+import java.util.concurrent.CountDownLatch;
25+
26+import static java.util.concurrent.TimeUnit.SECONDS;
2527 import static org.assertj.core.api.Assertions.assertThat;
2628 import static org.assertj.core.api.Assertions.fail;
2729 import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
2830 import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
2931 import static org.scassandra.http.client.PrimingRequest.queryBuilder;
3032
31-import com.datastax.driver.core.*;
32-import com.datastax.driver.core.exceptions.ReadTimeoutException;
33-import com.datastax.driver.core.exceptions.UnavailableException;
34-
3533 public class LatencyAwarePolicyTest extends ScassandraTestBase {
3634
3735 /**
@@ -55,10 +53,12 @@
5553 }
5654
5755 @Override
58- public void onRegister(Cluster cluster) {}
56+ public void onRegister(Cluster cluster) {
57+ }
5958
6059 @Override
61- public void onUnregister(Cluster cluster) {}
60+ public void onUnregister(Cluster cluster) {
61+ }
6262 }
6363
6464 @Test(groups = "short")
@@ -66,13 +66,13 @@
6666 // given
6767 String query = "SELECT foo FROM bar";
6868 primingClient.prime(
69- queryBuilder()
70- .withQuery(query)
71- .build()
69+ queryBuilder()
70+ .withQuery(query)
71+ .build()
7272 );
7373 LatencyAwarePolicy latencyAwarePolicy = LatencyAwarePolicy.builder(new RoundRobinPolicy())
74- .withMininumMeasurements(1)
75- .build();
74+ .withMininumMeasurements(1)
75+ .build();
7676 Cluster.Builder builder = super.createClusterBuilder();
7777 builder.withLoadBalancingPolicy(latencyAwarePolicy);
7878 Cluster cluster = builder.build();
@@ -104,14 +104,14 @@
104104 // given
105105 String query = "SELECT foo FROM bar";
106106 primingClient.prime(
107- queryBuilder()
108- .withQuery(query)
109- .withResult(unavailable)
110- .build()
107+ queryBuilder()
108+ .withQuery(query)
109+ .withResult(unavailable)
110+ .build()
111111 );
112112 LatencyAwarePolicy latencyAwarePolicy = LatencyAwarePolicy.builder(new RoundRobinPolicy())
113- .withMininumMeasurements(1)
114- .build();
113+ .withMininumMeasurements(1)
114+ .build();
115115 Cluster.Builder builder = super.createClusterBuilder();
116116 builder.withLoadBalancingPolicy(latencyAwarePolicy);
117117 Cluster cluster = builder.build();
@@ -144,14 +144,14 @@
144144 }
145145 }
146146
147- @Test(groups= "short")
147+ @Test(groups = "short")
148148 public void should_consider_latency_when_read_timeout() throws Exception {
149149 String query = "SELECT foo FROM bar";
150150 primingClient.prime(
151- queryBuilder()
152- .withQuery(query)
153- .withResult(read_request_timeout)
154- .build()
151+ queryBuilder()
152+ .withQuery(query)
153+ .withResult(read_request_timeout)
154+ .build()
155155 );
156156
157157 LatencyAwarePolicy latencyAwarePolicy = LatencyAwarePolicy.builder(new RoundRobinPolicy())
modified driver-core/src/test/java/com/datastax/driver/core/policies/LimitingLoadBalancingPolicy.java +12 −13
@@ -15,27 +15,26 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.*;
19-import java.util.concurrent.ConcurrentHashMap;
20-import java.util.concurrent.locks.Lock;
21-import java.util.concurrent.locks.ReentrantLock;
22-
23-import com.google.common.collect.Sets;
24-
2518 import com.datastax.driver.core.Cluster;
2619 import com.datastax.driver.core.Host;
2720 import com.datastax.driver.core.HostDistance;
2821 import com.datastax.driver.core.Statement;
22+import com.google.common.collect.Sets;
23+
24+import java.util.*;
25+import java.util.concurrent.ConcurrentHashMap;
26+import java.util.concurrent.locks.Lock;
27+import java.util.concurrent.locks.ReentrantLock;
2928
3029 /**
3130 * Sample load balancing policy that limits the number of nodes the driver connects to.
32- *
31+ * <p/>
3332 * If more nodes are available, they are marked as IGNORED. When one of the "chosen" nodes
3433 * goes down, the policy picks one of the ignored nodes to replace it.
35- * <p>
34+ * <p/>
3635 * This kind of policy can be used to alleviate the load on a cluster that has a lot of
3736 * clients.
38- * <p>
37+ * <p/>
3938 * For simplicity, this policy does not distinguish LOCAL and REMOTE nodes.
4039 */
4140 public class LimitingLoadBalancingPolicy extends DelegatingLoadBalancingPolicy {
@@ -48,8 +47,8 @@
4847 private volatile Cluster cluster;
4948
5049 /**
51- * @param delegate the underlying policy that will be fed with the chosen nodes
52- * @param maxHosts the maximum number of chosen nodes
50+ * @param delegate the underlying policy that will be fed with the chosen nodes
51+ * @param maxHosts the maximum number of chosen nodes
5352 * @param threshold how many chosen nodes we accept to lose before we start picking new ones
5453 */
5554 public LimitingLoadBalancingPolicy(LoadBalancingPolicy delegate, int maxHosts, int threshold) {
@@ -63,7 +62,7 @@
6362 this.cluster = cluster;
6463
6564 Iterator<Host> hostIt = hosts.iterator();
66- while(hostIt.hasNext() && chosenHosts.size() <= maxHosts - threshold) {
65+ while (hostIt.hasNext() && chosenHosts.size() <= maxHosts - threshold) {
6766 chosenHosts.add(hostIt.next());
6867 }
6968
modified driver-core/src/test/java/com/datastax/driver/core/policies/LoggingRetryPolicyIntegrationTest.java +13 −15
@@ -15,20 +15,16 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import org.apache.log4j.Level;
19-import org.apache.log4j.Logger;
20-import org.slf4j.helpers.MessageFormatter;
21-import org.testng.annotations.*;
22-
23-import static org.apache.log4j.Level.INFO;
24-import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
25-import static org.scassandra.http.client.PrimingRequest.Result.server_error;
26-import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
27-import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
28-
2918 import com.datastax.driver.core.*;
3019 import com.datastax.driver.core.exceptions.DriverException;
3120 import com.datastax.driver.core.exceptions.ServerError;
21+import org.apache.log4j.Level;
22+import org.apache.log4j.Logger;
23+import org.slf4j.helpers.MessageFormatter;
24+import org.testng.annotations.AfterMethod;
25+import org.testng.annotations.BeforeClass;
26+import org.testng.annotations.BeforeMethod;
27+import org.testng.annotations.Test;
3228
3329 import static com.datastax.driver.core.Assertions.assertThat;
3430 import static com.datastax.driver.core.ConsistencyLevel.LOCAL_ONE;
@@ -36,6 +32,8 @@
3632 import static com.datastax.driver.core.policies.LoggingRetryPolicy.*;
3733 import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.ignore;
3834 import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.tryNextHost;
35+import static org.apache.log4j.Level.INFO;
36+import static org.scassandra.http.client.PrimingRequest.Result.*;
3937
4038 /**
4139 * Integration tests with LoggingRetryPolicy.
@@ -51,24 +49,24 @@
5149 private Level originalLevel;
5250 private ConsistencyLevel defaultCL;
5351
54- @BeforeClass(groups = { "short", "unit" })
52+ @BeforeClass(groups = {"short", "unit"})
5553 public void setUpRetryPolicy() {
5654 setRetryPolicy(new LoggingRetryPolicy(new CustomRetryPolicy()));
5755 }
5856
59- @BeforeMethod(groups = { "short", "unit" })
57+ @BeforeMethod(groups = {"short", "unit"})
6058 public void storeDefaultCL() {
6159 defaultCL = cluster.getConfiguration().getQueryOptions().getConsistencyLevel();
6260 }
6361
64- @BeforeMethod(groups = { "short", "unit" })
62+ @BeforeMethod(groups = {"short", "unit"})
6563 public void startCapturingLogs() {
6664 originalLevel = logger.getLevel();
6765 logger.setLevel(INFO);
6866 logger.addAppender(appender = new MemoryAppender());
6967 }
7068
71- @AfterMethod(groups = { "short", "unit" })
69+ @AfterMethod(groups = {"short", "unit"})
7270 public void stopCapturingLogs() {
7371 logger.setLevel(originalLevel);
7472 logger.removeAppender(appender);
modified driver-core/src/test/java/com/datastax/driver/core/policies/RetryDecisionTest.java +15 −19
@@ -15,16 +15,12 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import org.testng.annotations.Test;
19-
20-import static org.assertj.core.api.Assertions.assertThat;
21-
2218 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
19+import org.testng.annotations.Test;
2320
2421 import static com.datastax.driver.core.ConsistencyLevel.ONE;
25-import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type.IGNORE;
26-import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type.RETHROW;
27-import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type.RETRY;
22+import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type.*;
23+import static org.assertj.core.api.Assertions.assertThat;
2824
2925 public class RetryDecisionTest {
3026
@@ -32,34 +28,34 @@
3228 public void should_expose_decision_properties() throws Throwable {
3329 RetryDecision retryAtOne = RetryDecision.retry(ONE);
3430 assertThat(retryAtOne.getType())
35- .isEqualTo(RETRY);
31+ .isEqualTo(RETRY);
3632 assertThat(retryAtOne.getRetryConsistencyLevel())
37- .isEqualTo(ONE);
33+ .isEqualTo(ONE);
3834 assertThat(retryAtOne.isRetryCurrent())
39- .isTrue();
35+ .isTrue();
4036 assertThat(retryAtOne.toString())
41- .isEqualTo("Retry at ONE on same host.");
37+ .isEqualTo("Retry at ONE on same host.");
4238
4339 RetryDecision tryNextAtOne = RetryDecision.tryNextHost(ONE);
4440 assertThat(tryNextAtOne.getType())
45- .isEqualTo(RETRY);
41+ .isEqualTo(RETRY);
4642 assertThat(tryNextAtOne.getRetryConsistencyLevel())
47- .isEqualTo(ONE);
43+ .isEqualTo(ONE);
4844 assertThat(tryNextAtOne.isRetryCurrent())
49- .isFalse();
45+ .isFalse();
5046 assertThat(tryNextAtOne.toString())
51- .isEqualTo("Retry at ONE on next host.");
47+ .isEqualTo("Retry at ONE on next host.");
5248
5349 RetryDecision rethrow = RetryDecision.rethrow();
5450 assertThat(rethrow.getType())
55- .isEqualTo(RETHROW);
51+ .isEqualTo(RETHROW);
5652 assertThat(rethrow.toString())
57- .isEqualTo("Rethrow");
53+ .isEqualTo("Rethrow");
5854
5955 RetryDecision ignore = RetryDecision.ignore();
6056 assertThat(ignore.getType())
61- .isEqualTo(IGNORE);
57+ .isEqualTo(IGNORE);
6258 assertThat(ignore.toString())
63- .isEqualTo("Ignore");
59+ .isEqualTo("Ignore");
6460 }
6561 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/RoundRobinPolicyTest.java +21 −28
@@ -15,20 +15,13 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.datastax.driver.core.*;
1819 import org.apache.log4j.Level;
1920 import org.apache.log4j.Logger;
2021 import org.testng.annotations.AfterMethod;
2122 import org.testng.annotations.BeforeMethod;
2223 import org.testng.annotations.Test;
2324
24-import com.datastax.driver.core.Cluster;
25-import com.datastax.driver.core.ConsistencyLevel;
26-import com.datastax.driver.core.DataProviders;
27-import com.datastax.driver.core.MemoryAppender;
28-import com.datastax.driver.core.QueryTracker;
29-import com.datastax.driver.core.ScassandraCluster;
30-import com.datastax.driver.core.Session;
31-
3225 import static com.datastax.driver.core.Assertions.assertThat;
3326 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
3427
@@ -58,16 +51,16 @@
5851 *
5952 * @test_category load_balancing:round_robin
6053 */
61- @Test(groups="short")
54+ @Test(groups = "short")
6255 public void should_round_robin_within_single_datacenter() {
6356 // given: a 5 node cluster using RoundRobinPolicy.
6457 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build();
6558
6659 Cluster cluster = Cluster.builder()
67- .addContactPoint(sCluster.address(1))
68- .withLoadBalancingPolicy(new RoundRobinPolicy())
69- .withNettyOptions(nonQuietClusterCloseOptions)
70- .build();
60+ .addContactPoint(sCluster.address(1))
61+ .withLoadBalancingPolicy(new RoundRobinPolicy())
62+ .withNettyOptions(nonQuietClusterCloseOptions)
63+ .build();
7164
7265 try {
7366 sCluster.init();
@@ -77,7 +70,7 @@
7770 queryTracker.query(session, 50);
7871
7972 // then: all nodes should be queried equally.
80- for(int i = 1; i <= 5; i++) {
73+ for (int i = 1; i <= 5; i++) {
8174 queryTracker.assertQueried(sCluster, 1, i, 10);
8275 }
8376 } finally {
@@ -93,16 +86,16 @@
9386 *
9487 * @test_category load_balancing:round_robin
9588 */
96- @Test(groups="short")
89+ @Test(groups = "short")
9790 public void should_round_robin_irrespective_of_topology() {
9891 // given: a 10 node, 5 DC cluster using RoundRobinPolicy.
99- ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2,2,2,2,2).build();
92+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2, 2, 2, 2).build();
10093
10194 Cluster cluster = Cluster.builder()
102- .addContactPoint(sCluster.address(1))
103- .withLoadBalancingPolicy(new RoundRobinPolicy())
104- .withNettyOptions(nonQuietClusterCloseOptions)
105- .build();
95+ .addContactPoint(sCluster.address(1))
96+ .withLoadBalancingPolicy(new RoundRobinPolicy())
97+ .withNettyOptions(nonQuietClusterCloseOptions)
98+ .build();
10699
107100 try {
108101 sCluster.init();
@@ -112,7 +105,7 @@
112105 queryTracker.query(session, 50);
113106
114107 // then: all nodes should be queried equally.
115- for(int dc = 1; dc <= 5; dc++) {
108+ for (int dc = 1; dc <= 5; dc++) {
116109 for (int i = 1; i <= 2; i++) {
117110 queryTracker.assertQueried(sCluster, dc, i, 5);
118111 }
@@ -131,16 +124,16 @@
131124 *
132125 * @test_category load_balancing:round_robin
133126 */
134- @Test(groups="short", dataProvider="consistencyLevels", dataProviderClass=DataProviders.class)
127+ @Test(groups = "short", dataProvider = "consistencyLevels", dataProviderClass = DataProviders.class)
135128 public void should_warn_if_using_dc_local_consistency_level(ConsistencyLevel cl) {
136129 // given: a 2 node, 2 DC cluster using RoundRobinPolicy.
137- ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(1,1).build();
130+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(1, 1).build();
138131
139132 Cluster cluster = Cluster.builder()
140- .addContactPoint(sCluster.address(1))
141- .withLoadBalancingPolicy(new RoundRobinPolicy())
142- .withNettyOptions(nonQuietClusterCloseOptions)
143- .build();
133+ .addContactPoint(sCluster.address(1))
134+ .withLoadBalancingPolicy(new RoundRobinPolicy())
135+ .withNettyOptions(nonQuietClusterCloseOptions)
136+ .build();
144137
145138 String expectedLogMessage = "Detected request at Consistency Level " + cl + " but the non-DC aware RoundRobinPolicy is in use.";
146139
@@ -156,7 +149,7 @@
156149 queryTracker.assertQueried(sCluster, 2, 1, 25);
157150
158151 // Should get a warning if using a local DC cl.
159- if(cl.isDCLocal()) {
152+ if (cl.isDCLocal()) {
160153 assertThat(logs.get()).containsOnlyOnce(expectedLogMessage);
161154 } else {
162155 assertThat(logs.get()).doesNotContain(expectedLogMessage);
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +61 −65
@@ -15,22 +15,18 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.nio.ByteBuffer;
19-import java.util.List;
20-
18+import com.datastax.driver.core.*;
2119 import com.google.common.collect.ImmutableMap;
2220 import com.google.common.collect.Lists;
2321 import org.testng.annotations.BeforeMethod;
2422 import org.testng.annotations.DataProvider;
2523 import org.testng.annotations.Test;
2624
27-import com.datastax.driver.core.*;
25+import java.nio.ByteBuffer;
26+import java.util.List;
2827
2928 import static com.datastax.driver.core.Assertions.assertThat;
30-import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
31-import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
32-import static com.datastax.driver.core.TestUtils.getDesiredProtocolVersion;
33-import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
29+import static com.datastax.driver.core.TestUtils.*;
3430
3531 public class TokenAwarePolicyTest {
3632
@@ -41,12 +37,12 @@
4137 queryTracker = new QueryTracker();
4238 }
4339
44- @DataProvider(name="shuffleProvider")
45- public Object[][] shuffleProvider () {
46- return new Object[][] {
47- { true },
48- { false },
49- { null }
40+ @DataProvider(name = "shuffleProvider")
41+ public Object[][] shuffleProvider() {
42+ return new Object[][]{
43+ {true},
44+ {false},
45+ {null}
5046 };
5147 }
5248
@@ -57,16 +53,16 @@
5753 *
5854 * @test_category load_balancing:token_aware
5955 */
60- @Test(groups="short", dataProvider="shuffleProvider")
56+ @Test(groups = "short", dataProvider = "shuffleProvider")
6157 public void should_shuffle_replicas_based_on_configuration(Boolean shuffleReplicas) {
6258 // given: an 8 node cluster using TokenAwarePolicy and some shuffle replica configuration with a keyspace with replication factor of 3.
6359 ScassandraCluster sCluster = ScassandraCluster.builder()
64- .withNodes(8)
65- .withSimpleKeyspace("keyspace", 3)
66- .build();
60+ .withNodes(8)
61+ .withSimpleKeyspace("keyspace", 3)
62+ .build();
6763
6864 LoadBalancingPolicy loadBalancingPolicy;
69- if(shuffleReplicas == null) {
65+ if (shuffleReplicas == null) {
7066 loadBalancingPolicy = new TokenAwarePolicy(new RoundRobinPolicy());
7167 shuffleReplicas = true;
7268 } else {
@@ -74,9 +70,9 @@
7470 }
7571
7672 Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
77- .withNettyOptions(nonQuietClusterCloseOptions)
78- .withLoadBalancingPolicy(loadBalancingPolicy)
79- .build();
73+ .withNettyOptions(nonQuietClusterCloseOptions)
74+ .withLoadBalancingPolicy(loadBalancingPolicy)
75+ .build();
8076
8177 try {
8278 sCluster.init();
@@ -91,9 +87,9 @@
9187 // then: The replicas resolved from the cluster metadata must match node 6 and its replicas.
9288 List<Host> replicas = Lists.newArrayList(cluster.getMetadata().getReplicas("keyspace", routingKey));
9389 assertThat(replicas).containsExactly(
94- sCluster.host(cluster, 1, 6),
95- sCluster.host(cluster, 1, 7),
96- sCluster.host(cluster, 1, 8));
90+ sCluster.host(cluster, 1, 6),
91+ sCluster.host(cluster, 1, 7),
92+ sCluster.host(cluster, 1, 8));
9793
9894 // then: generating a query plan on a statement using that routing key should properly prioritize node 6 and its replicas.
9995 // Actual query does not matter, only the keyspace and routing key will be used
@@ -102,16 +98,16 @@
10298 statement.setKeyspace("keyspace");
10399
104100 boolean shuffledAtLeastOnce = false;
105- for(int i = 0; i < 1024; i++) {
101+ for (int i = 0; i < 1024; i++) {
106102 List<Host> queryPlan = Lists.newArrayList(loadBalancingPolicy.newQueryPlan(null, statement));
107103 assertThat(queryPlan).containsOnlyElementsOf(cluster.getMetadata().getAllHosts());
108104
109105 List<Host> firstThree = queryPlan.subList(0, 3);
110106 // then: if shuffle replicas was used or using default, the first three hosts returned should be 6,7,8 in any order.
111107 // if shuffle replicas was not used, the first three hosts returned should be 6,7,8 in that order.
112- if(shuffleReplicas) {
108+ if (shuffleReplicas) {
113109 assertThat(firstThree).containsOnlyElementsOf(replicas);
114- if(!firstThree.equals(replicas)) {
110+ if (!firstThree.equals(replicas)) {
115111 shuffledAtLeastOnce = true;
116112 }
117113 } else {
@@ -134,17 +130,17 @@
134130 *
135131 * @test_category load_balancing:token_aware
136132 */
137- @Test(groups="short")
133+ @Test(groups = "short")
138134 public void should_choose_proper_host_based_on_routing_key() {
139135 // given: A 3 node cluster using TokenAwarePolicy with a replication factor of 1.
140136 ScassandraCluster sCluster = ScassandraCluster.builder()
141- .withNodes(3)
142- .withSimpleKeyspace("keyspace", 1)
143- .build();
137+ .withNodes(3)
138+ .withSimpleKeyspace("keyspace", 1)
139+ .build();
144140 Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
145- .withNettyOptions(nonQuietClusterCloseOptions)
146- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
147- .build();
141+ .withNettyOptions(nonQuietClusterCloseOptions)
142+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
143+ .build();
148144
149145 // when: A query is made with a routing key
150146 try {
@@ -155,8 +151,8 @@
155151 // Encodes into murmur hash '4557949199137838892' which should belong be owned by node 3.
156152 ByteBuffer routingKey = TypeCodec.varchar().serialize("should_choose_proper_host_based_on_routing_key", ProtocolVersion.NEWEST_SUPPORTED);
157153 SimpleStatement statement = new SimpleStatement("select * from table where k=5")
158- .setRoutingKey(routingKey)
159- .setKeyspace("keyspace");
154+ .setRoutingKey(routingKey)
155+ .setKeyspace("keyspace");
160156
161157 queryTracker.query(session, 10, statement);
162158
@@ -177,20 +173,20 @@
177173 *
178174 * @test_category load_balancing:token_aware
179175 */
180- @Test(groups="short")
176+ @Test(groups = "short")
181177 public void should_choose_host_in_local_dc_when_using_network_topology_strategy_and_dc_aware() {
182178 // given: A 6 node, 2 DC cluster with RF 1:1, using TokenAwarePolicy wrapping DCAwareRoundRobinPolicy with remote hosts.
183179 ScassandraCluster sCluster = ScassandraCluster.builder()
184- .withNodes(3, 3)
185- .withNetworkTopologyKeyspace("keyspace", ImmutableMap.of(1, 1, 2, 1))
186- .build();
187- Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2,1))
188- .withNettyOptions(nonQuietClusterCloseOptions)
189- .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder()
190- .withLocalDc(ScassandraCluster.datacenter(2))
191- .withUsedHostsPerRemoteDc(3)
192- .build()))
193- .build();
180+ .withNodes(3, 3)
181+ .withNetworkTopologyKeyspace("keyspace", ImmutableMap.of(1, 1, 2, 1))
182+ .build();
183+ Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2, 1))
184+ .withNettyOptions(nonQuietClusterCloseOptions)
185+ .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder()
186+ .withLocalDc(ScassandraCluster.datacenter(2))
187+ .withUsedHostsPerRemoteDc(3)
188+ .build()))
189+ .build();
194190
195191 // when: A query is made with a routing key
196192 try {
@@ -201,8 +197,8 @@
201197 // Encodes into murmur hash '-8124212968526248339' which should belong to 1:1 in DC1 and 2:1 in DC2.
202198 ByteBuffer routingKey = TypeCodec.varchar().serialize("should_choose_host_in_local_dc_when_using_network_topology_strategy_and_dc_aware", ProtocolVersion.NEWEST_SUPPORTED);
203199 SimpleStatement statement = new SimpleStatement("select * from table where k=5")
204- .setRoutingKey(routingKey)
205- .setKeyspace("keyspace");
200+ .setRoutingKey(routingKey)
201+ .setKeyspace("keyspace");
206202
207203 queryTracker.query(session, 10, statement);
208204
@@ -222,18 +218,18 @@
222218 *
223219 * @test_category load_balancing:token_aware
224220 */
225- @Test(groups="short")
221+ @Test(groups = "short")
226222 public void should_use_other_nodes_when_replicas_having_token_are_down() {
227223 // given: A 4 node cluster using TokenAwarePolicy with a replication factor of 2.
228224 ScassandraCluster sCluster = ScassandraCluster.builder()
229- .withNodes(4)
230- .withSimpleKeyspace("keyspace", 2)
231- .build();
225+ .withNodes(4)
226+ .withSimpleKeyspace("keyspace", 2)
227+ .build();
232228 Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2))
233- .withNettyOptions(nonQuietClusterCloseOptions)
234- // Don't shuffle replicas just to keep test deterministic.
235- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
236- .build();
229+ .withNettyOptions(nonQuietClusterCloseOptions)
230+ // Don't shuffle replicas just to keep test deterministic.
231+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
232+ .build();
237233
238234 try {
239235 sCluster.init();
@@ -244,8 +240,8 @@
244240 // Encodes into murmur hash '6444339665561646341' which should belong to node 4.
245241 ByteBuffer routingKey = TypeCodec.varchar().serialize("should_use_other_nodes_when_replicas_having_token_are_down", ProtocolVersion.NEWEST_SUPPORTED);
246242 SimpleStatement statement = new SimpleStatement("select * from table where k=5")
247- .setRoutingKey(routingKey)
248- .setKeyspace("keyspace");
243+ .setRoutingKey(routingKey)
244+ .setKeyspace("keyspace");
249245
250246 queryTracker.query(session, 10, statement);
251247
@@ -318,9 +314,9 @@
318314 CCMBridge ccm = CCMBridge.builder("TokenAwarePolicyTest").withNodes(3).notStarted().build();
319315
320316 Cluster cluster = Cluster.builder()
321- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
322- .addContactPoint(CCMBridge.ipOfNode(1))
323- .build();
317+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
318+ .addContactPoint(CCMBridge.ipOfNode(1))
319+ .build();
324320
325321 try {
326322 ccm.start();
@@ -336,11 +332,11 @@
336332 BoundStatement insertBs = insertPs.bind(1, 2, 3);
337333
338334 PreparedStatement selectPs = session.prepare("SELECT * FROM " + table + " WHERE k1=? and k2=?");
339- BoundStatement selectBs = selectPs.bind(1,2);
335+ BoundStatement selectBs = selectPs.bind(1, 2);
340336
341337 // when: executing a prepared statement with a composite partition key.
342338 // then: should query the correct node (1) in for both insert and select queries.
343- for(int i = 0; i < 10; i++) {
339+ for (int i = 0; i < 10; i++) {
344340 ResultSet rs = session.execute(insertBs);
345341 assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
346342
modified driver-core/src/test/java/com/datastax/driver/core/policies/WhiteListPolicyTest.java +20 −25
@@ -15,20 +15,15 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.net.InetAddress;
19-import java.net.InetSocketAddress;
20-import java.util.List;
21-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.NoHostAvailableException;
2220 import com.google.common.collect.Lists;
2321 import org.testng.annotations.BeforeMethod;
2422 import org.testng.annotations.Test;
2523
26-import com.datastax.driver.core.Cluster;
27-import com.datastax.driver.core.ConsistencyLevel;
28-import com.datastax.driver.core.QueryTracker;
29-import com.datastax.driver.core.ScassandraCluster;
30-import com.datastax.driver.core.Session;
31-import com.datastax.driver.core.exceptions.NoHostAvailableException;
24+import java.net.InetAddress;
25+import java.net.InetSocketAddress;
26+import java.util.List;
3227
3328 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
3429
@@ -46,25 +41,25 @@
4641 * <p/>
4742 * Ensures that:
4843 * <ol>
49- * <li>Only addresses provided in the whitelist are every used for querying.</li>
50- * <li>If no nodes present in the whitelist are available, queries fail with a {@link NoHostAvailableException}</li>
44+ * <li>Only addresses provided in the whitelist are every used for querying.</li>
45+ * <li>If no nodes present in the whitelist are available, queries fail with a {@link NoHostAvailableException}</li>
5146 * </ol>
5247 *
5348 * @test_category load_balancing:white_list
5449 */
55- @Test(groups="short")
50+ @Test(groups = "short")
5651 public void should_only_query_hosts_in_white_list() throws Exception {
5752 // given: a 5 node cluster with a WhiteListPolicy targeting nodes 3 and 5.
5853 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build();
5954 List<InetSocketAddress> whiteList = Lists.newArrayList(
60- new InetSocketAddress(InetAddress.getByName(sCluster.address(3)), 9042),
61- new InetSocketAddress(InetAddress.getByName(sCluster.address(5)), 9042));
55+ new InetSocketAddress(InetAddress.getByName(sCluster.address(3)), 9042),
56+ new InetSocketAddress(InetAddress.getByName(sCluster.address(5)), 9042));
6257
6358 Cluster cluster = Cluster.builder()
64- .addContactPoint(sCluster.address(5))
65- .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
66- .withNettyOptions(nonQuietClusterCloseOptions)
67- .build();
59+ .addContactPoint(sCluster.address(5))
60+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
61+ .withNettyOptions(nonQuietClusterCloseOptions)
62+ .build();
6863
6964 try {
7065 sCluster.init();
@@ -106,7 +101,7 @@
106101 *
107102 * @test_category load_balancing:white_list
108103 */
109- @Test(groups="short", expectedExceptions = {IllegalArgumentException.class})
104+ @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
110105 public void should_require_contact_point_in_white_list() throws Exception {
111106 // given: a 5 node cluster with a WhiteListPolicy targeting node2.
112107 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build();
@@ -114,12 +109,12 @@
114109 // when: using a Cluster instance with none of the contact points in the declared
115110 // WhiteListPolicy.
116111 List<InetSocketAddress> whiteList = Lists.newArrayList(
117- new InetSocketAddress(InetAddress.getByName(sCluster.address(2)), 9042));
112+ new InetSocketAddress(InetAddress.getByName(sCluster.address(2)), 9042));
118113 Cluster cluster = Cluster.builder()
119- .addContactPoint(sCluster.address(3))
120- .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
121- .withNettyOptions(nonQuietClusterCloseOptions)
122- .build();
114+ .addContactPoint(sCluster.address(3))
115+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
116+ .withNettyOptions(nonQuietClusterCloseOptions)
117+ .build();
123118
124119 try {
125120 sCluster.init();
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java +12 −16
@@ -15,24 +15,20 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.Arrays;
19-import java.util.Collection;
20-
21-import org.testng.annotations.Test;
22-
2318 import com.datastax.driver.core.CCMBridge;
2419 import com.datastax.driver.core.PreparedStatement;
2520 import com.datastax.driver.core.ResultSet;
2621 import com.datastax.driver.core.Row;
2722 import com.datastax.driver.core.utils.CassandraVersion;
23+import org.testng.annotations.Test;
24+
25+import java.util.Arrays;
26+import java.util.Collection;
2827
2928 import static com.datastax.driver.core.Assertions.assertThat;
30-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.contains;
32-import static com.datastax.driver.core.querybuilder.QueryBuilder.containsKey;
33-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
34-
35-@CassandraVersion(major=2.1)
29+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
30+
31+@CassandraVersion(major = 2.1)
3632 public class QueryBuilder21ExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
3733
3834 @Override
@@ -53,7 +49,7 @@
5349 );
5450 }
5551
56- @Test(groups="short")
52+ @Test(groups = "short")
5753 public void should_handle_contains_on_set_with_index() {
5854 PreparedStatement byCategory = session.prepare(select("id", "description", "categories")
5955 .from("products")
@@ -62,12 +58,12 @@
6258 ResultSet results = session.execute(byCategory.bind().setString("category", "hdtv"));
6359
6460 assertThat(results.getAvailableWithoutFetching()).isEqualTo(2);
65- for(Row row : results) {
61+ for (Row row : results) {
6662 assertThat(row.getSet("categories", String.class)).contains("hdtv");
6763 }
6864 }
6965
70- @Test(groups="short")
66+ @Test(groups = "short")
7167 public void should_handle_contains_on_list_with_index() {
7268 PreparedStatement byBuyer = session.prepare(select("id", "description", "buyers")
7369 .from("products")
@@ -81,7 +77,7 @@
8177 assertThat(row.getList("buyers", Integer.class)).contains(4);
8278 }
8379
84- @Test(groups="short")
80+ @Test(groups = "short")
8581 public void should_handle_contains_on_map_with_index() {
8682 PreparedStatement byFeatures = session.prepare(select("id", "description", "features_values")
8783 .from("products")
@@ -96,7 +92,7 @@
9692 }
9793
9894
99- @Test(groups="short")
95+ @Test(groups = "short")
10096 public void should_handle_contains_key_on_map_with_index() {
10197 PreparedStatement byFeatures = session.prepare(select("id", "description", "features_keys")
10298 .from("products")
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +8 −12
@@ -15,19 +15,15 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.*;
2019 import org.testng.annotations.Test;
2120
22-import static org.assertj.core.api.Assertions.assertThat;
23-import static org.assertj.core.data.MapEntry.entry;
24-import static org.testng.Assert.assertEquals;
25-import static org.testng.Assert.assertFalse;
26-import static org.testng.Assert.assertTrue;
27-
28-import com.datastax.driver.core.*;
21+import java.util.*;
2922
3023 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
24+import static org.assertj.core.api.Assertions.assertThat;
25+import static org.assertj.core.data.MapEntry.entry;
26+import static org.testng.Assert.*;
3127
3228 public class QueryBuilderExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
3329
@@ -36,9 +32,9 @@
3632 @Override
3733 protected Collection<String> getTableDefinitions() {
3834 return Arrays.asList(
39- String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE1),
40- "CREATE TABLE dateTest (t timestamp PRIMARY KEY)",
41- "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)");
35+ String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE1),
36+ "CREATE TABLE dateTest (t timestamp PRIMARY KEY)",
37+ "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)");
4238 }
4339
4440 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +21 −19
@@ -15,19 +15,17 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.Arrays;
19-import java.util.Collection;
20-import java.util.TreeSet;
21-
22-import org.testng.annotations.Test;
23-
24-import static org.testng.Assert.*;
25-
2618 import com.datastax.driver.core.*;
2719 import com.datastax.driver.core.exceptions.SyntaxError;
2820 import com.datastax.driver.core.utils.CassandraVersion;
21+import org.testng.annotations.Test;
22+
23+import java.util.Arrays;
24+import java.util.Collection;
25+import java.util.TreeSet;
2926
3027 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
28+import static org.testng.Assert.*;
3129
3230 public class QueryBuilderITest extends CCMBridge.PerClassSingleNodeCluster {
3331
@@ -37,15 +35,15 @@
3735 @Override
3836 protected Collection<String> getTableDefinitions() {
3937 return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
40- String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
38+ String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
4139 }
4240
4341 @Override
4442 protected Cluster.Builder configure(Cluster.Builder builder) {
4543 return builder.withQueryOptions(new QueryOptions()
46- .setRefreshNodeIntervalMillis(0)
47- .setRefreshNodeListIntervalMillis(0)
48- .setRefreshSchemaIntervalMillis(0)
44+ .setRefreshNodeIntervalMillis(0)
45+ .setRefreshNodeListIntervalMillis(0)
46+ .setRefreshSchemaIntervalMillis(0)
4947 );
5048 }
5149
@@ -147,7 +145,11 @@
147145 assertEquals(insert.toString(), query);
148146
149147 query = "INSERT INTO foo (a,b) VALUES ({'2''} space','3','4'},3.4) USING TTL 24 AND TIMESTAMP 42;";
150- insert = insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<String>(){{ add("2'} space"); add("3"); add("4"); }}, 3.4 }).using(ttl(24)).and(timestamp(42));
148+ insert = insertInto("foo").values(new String[]{"a", "b"}, new Object[]{new TreeSet<String>() {{
149+ add("2'} space");
150+ add("3");
151+ add("4");
152+ }}, 3.4}).using(ttl(24)).and(timestamp(42));
151153 assertEquals(insert.toString(), query);
152154 }
153155
@@ -215,16 +217,16 @@
215217 }
216218
217219 @Test(groups = "short")
218- @CassandraVersion(major=2.0, minor=7, description="DELETE..IF EXISTS only supported in 2.0.7+ (CASSANDRA-5708)")
220+ @CassandraVersion(major = 2.0, minor = 7, description = "DELETE..IF EXISTS only supported in 2.0.7+ (CASSANDRA-5708)")
219221 public void conditionalDeletesTest() throws Exception {
220- session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)",keyspace));
222+ session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
221223
222224 Statement delete;
223225 Row row;
224226 delete = delete().from(keyspace, TABLE_INT).where(eq("k", 2)).ifExists();
225227 row = session.execute(delete).one();
226228 assertFalse(row.getBool("[applied]"));
227-
229+
228230 delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).ifExists();
229231 row = session.execute(delete).one();
230232 assertTrue(row.getBool("[applied]"));
@@ -234,16 +236,16 @@
234236 delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 2));
235237 row = session.execute(delete).one();
236238 assertFalse(row.getBool("[applied]"));
237-
239+
238240 delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 1));
239241 row = session.execute(delete).one();
240242 assertTrue(row.getBool("[applied]"));
241243 }
242244
243245 @Test(groups = "short")
244- @CassandraVersion(major=2.0, minor=13, description="Allow IF EXISTS for UPDATE statements (CASSANDRA-8610)")
246+ @CassandraVersion(major = 2.0, minor = 13, description = "Allow IF EXISTS for UPDATE statements (CASSANDRA-8610)")
245247 public void conditionalUpdatesTest() throws Exception {
246- session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)",keyspace));
248+ session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
247249
248250 Statement update;
249251 Row row;
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +9 −11
@@ -15,19 +15,17 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.*;
19+import org.testng.annotations.Test;
20+
1821 import java.nio.ByteBuffer;
1922 import java.util.Arrays;
2023 import java.util.Collection;
2124
22-import org.testng.annotations.Test;
23-
25+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2426 import static org.testng.Assert.assertEquals;
2527 import static org.testng.Assert.assertNotNull;
2628
27-import com.datastax.driver.core.*;
28-
29-import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
30-
3129 public class QueryBuilderRoutingKeyTest extends CCMBridge.PerClassSingleNodeCluster {
3230
3331 private static final String TABLE_TEXT = "test_text";
@@ -36,15 +34,15 @@
3634 @Override
3735 protected Collection<String> getTableDefinitions() {
3836 return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
39- String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
37+ String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
4038 }
4139
4240 @Override
4341 protected Cluster.Builder configure(Cluster.Builder builder) {
4442 return builder.withQueryOptions(new QueryOptions()
45- .setRefreshNodeIntervalMillis(0)
46- .setRefreshNodeListIntervalMillis(0)
47- .setRefreshSchemaIntervalMillis(0)
43+ .setRefreshNodeIntervalMillis(0)
44+ .setRefreshNodeListIntervalMillis(0)
45+ .setRefreshSchemaIntervalMillis(0)
4846 );
4947 }
5048
@@ -115,7 +113,7 @@
115113 batch_query += String.format("UPDATE %s.test_int USING TTL 400;", keyspace);
116114 batch_query += "APPLY BATCH;";
117115 batch = batch()
118- .add(insertInto(table).values(new String[]{ "k", "a" }, new Object[]{ 42, 1 }))
116+ .add(insertInto(table).values(new String[]{"k", "a"}, new Object[]{42, 1}))
119117 .add(update(table).using(ttl(400)));
120118 assertEquals(batch.getRoutingKey(protocolVersion, codecRegistry), bb);
121119 assertEquals(batch.toString(), batch_query);
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +108 −112
@@ -15,29 +15,25 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.math.BigDecimal;
19-import java.math.BigInteger;
20-import java.net.InetAddress;
21-import java.util.*;
22-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.CodecNotFoundException;
20+import com.datastax.driver.core.exceptions.InvalidQueryException;
21+import com.datastax.driver.core.utils.Bytes;
22+import com.datastax.driver.core.utils.CassandraVersion;
2323 import com.google.common.collect.ImmutableList;
2424 import com.google.common.collect.ImmutableMap;
2525 import com.google.common.collect.Lists;
2626 import com.google.common.collect.Sets;
2727 import org.testng.annotations.Test;
2828
29-import static org.assertj.core.api.Assertions.assertThat;
30-import static org.testng.Assert.assertEquals;
31-import static org.testng.Assert.assertTrue;
32-import static org.testng.Assert.fail;
33-
34-import com.datastax.driver.core.*;
35-import com.datastax.driver.core.exceptions.CodecNotFoundException;
36-import com.datastax.driver.core.exceptions.InvalidQueryException;
37-import com.datastax.driver.core.utils.Bytes;
38-import com.datastax.driver.core.utils.CassandraVersion;
29+import java.math.BigDecimal;
30+import java.math.BigInteger;
31+import java.net.InetAddress;
32+import java.util.*;
3933
4034 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
35+import static org.assertj.core.api.Assertions.assertThat;
36+import static org.testng.Assert.*;
4137
4238 public class QueryBuilderTest {
4339
@@ -57,10 +53,10 @@
5753
5854 query = "SELECT a,b,\"C\" FROM foo WHERE a IN ('127.0.0.1','127.0.0.3') AND \"C\"='foo' ORDER BY a ASC,b DESC LIMIT 42;";
5955 select = select("a", "b", quote("C")).from("foo")
60- .where(in("a", InetAddress.getByName("127.0.0.1"), InetAddress.getByName("127.0.0.3")))
61- .and(eq(quote("C"), "foo"))
62- .orderBy(asc("a"), desc("b"))
63- .limit(42);
56+ .where(in("a", InetAddress.getByName("127.0.0.1"), InetAddress.getByName("127.0.0.3")))
57+ .and(eq(quote("C"), "foo"))
58+ .orderBy(asc("a"), desc("b"))
59+ .limit(42);
6460 assertEquals(select.toString(), query);
6561
6662 query = "SELECT writetime(a),ttl(a) FROM foo ALLOW FILTERING;";
@@ -178,7 +174,7 @@
178174 }
179175
180176 @Test(groups = "unit")
181- @SuppressWarnings({ "serial", "deprecation" })
177+ @SuppressWarnings({"serial", "deprecation"})
182178 public void insertTest() throws Exception {
183179
184180 String query;
@@ -186,67 +182,67 @@
186182
187183 query = "INSERT INTO foo (a,b,\"C\",d) VALUES (123,'127.0.0.1','foo''bar',{'x':3,'y':2}) USING TIMESTAMP 42 AND TTL 24;";
188184 insert = insertInto("foo")
189- .value("a", 123)
190- .value("b", InetAddress.getByName("127.0.0.1"))
191- .value(quote("C"), "foo'bar")
192- .value("d", new TreeMap<String, Integer>() {{
193- put("x", 3);
194- put("y", 2);
195- }})
196- .using(timestamp(42)).and(ttl(24));
185+ .value("a", 123)
186+ .value("b", InetAddress.getByName("127.0.0.1"))
187+ .value(quote("C"), "foo'bar")
188+ .value("d", new TreeMap<String, Integer>() {{
189+ put("x", 3);
190+ put("y", 2);
191+ }})
192+ .using(timestamp(42)).and(ttl(24));
197193 assertEquals(insert.toString(), query);
198194
199195 query = "INSERT INTO foo (a,b) VALUES (2,null);";
200196 insert = insertInto("foo")
201- .value("a", 2)
202- .value("b", null);
197+ .value("a", 2)
198+ .value("b", null);
203199 assertEquals(insert.toString(), query);
204200
205201 query = "INSERT INTO foo (a,b) VALUES ({2,3,4},3.4) USING TTL 24 AND TIMESTAMP 42;";
206- insert = insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
202+ insert = insertInto("foo").values(new String[]{"a", "b"}, new Object[]{new TreeSet<Integer>() {{
207203 add(2);
208204 add(3);
209205 add(4);
210- }}, 3.4 }).using(ttl(24)).and(timestamp(42));
206+ }}, 3.4}).using(ttl(24)).and(timestamp(42));
211207 assertEquals(insert.toString(), query);
212208
213209 query = "INSERT INTO foo.bar (a,b) VALUES ({2,3,4},3.4) USING TTL ? AND TIMESTAMP ?;";
214210 insert = insertInto("foo", "bar")
215- .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
216- add(2);
217- add(3);
218- add(4);
219- }}, 3.4 })
220- .using(ttl(bindMarker()))
221- .and(timestamp(bindMarker()));
211+ .values(new String[]{"a", "b"}, new Object[]{new TreeSet<Integer>() {{
212+ add(2);
213+ add(3);
214+ add(4);
215+ }}, 3.4})
216+ .using(ttl(bindMarker()))
217+ .and(timestamp(bindMarker()));
222218 assertEquals(insert.toString(), query);
223219
224220 // commutative result of TIMESTAMP
225221 query = "INSERT INTO foo.bar (a,b,c) VALUES ({2,3,4},3.4,123) USING TIMESTAMP 42;";
226222 insert = insertInto("foo", "bar")
227- .using(timestamp(42))
228- .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
229- add(2);
230- add(3);
231- add(4);
232- }}, 3.4 })
233- .value("c", 123);
223+ .using(timestamp(42))
224+ .values(new String[]{"a", "b"}, new Object[]{new TreeSet<Integer>() {{
225+ add(2);
226+ add(3);
227+ add(4);
228+ }}, 3.4})
229+ .value("c", 123);
234230 assertEquals(insert.toString(), query);
235231
236232 // commutative result of value() and values()
237233 query = "INSERT INTO foo (c,a,b) VALUES (123,{2,3,4},3.4) USING TIMESTAMP 42;";
238234 insert = insertInto("foo")
239- .using(timestamp(42))
240- .value("c", 123)
241- .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
242- add(2);
243- add(3);
244- add(4);
245- }}, 3.4 });
235+ .using(timestamp(42))
236+ .value("c", 123)
237+ .values(new String[]{"a", "b"}, new Object[]{new TreeSet<Integer>() {{
238+ add(2);
239+ add(3);
240+ add(4);
241+ }}, 3.4});
246242 assertEquals(insert.toString(), query);
247243
248244 try {
249- insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ 1, 2, 3 });
245+ insertInto("foo").values(new String[]{"a", "b"}, new Object[]{1, 2, 3});
250246 fail();
251247 } catch (IllegalArgumentException e) {
252248 assertEquals(e.getMessage(), "Got 2 names but 3 values");
@@ -298,11 +294,11 @@
298294 add(3);
299295 add(4);
300296 }}))
301- .and(put("c", "k", "v"))
302- .and(putAll("d", new TreeMap<String, Integer>() {{
303- put("x", 3);
304- put("y", 2);
305- }}));
297+ .and(put("c", "k", "v"))
298+ .and(putAll("d", new TreeMap<String, Integer>() {{
299+ put("x", 3);
300+ put("y", 2);
301+ }}));
306302 assertEquals(update.toString(), query);
307303
308304 query = "UPDATE foo USING TTL 400;";
@@ -341,7 +337,7 @@
341337 update = update("foo").with(set("x", 3)).where(eq("k", 2)).ifExists();
342338 assertThat(update.toString()).isEqualTo("UPDATE foo SET x=3 WHERE k=2 IF EXISTS;");
343339 }
344-
340+
345341 @Test(groups = "unit")
346342 public void deleteTest() throws Exception {
347343
@@ -418,14 +414,14 @@
418414 query += "DELETE a[3],b['foo'],c FROM foo WHERE k=1;";
419415 query += "APPLY BATCH;";
420416 batch = batch()
421- .add(insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
422- add(2);
423- add(3);
424- add(4);
425- }}, 3.4 }))
426- .add(update("foo").with(setIdx("a", 2, "foo")).and(prependAll("b", Arrays.asList(3, 2, 1))).and(remove("c", "a")).where(eq("k", 2)))
427- .add(delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1)))
428- .using(timestamp(42));
417+ .add(insertInto("foo").values(new String[]{"a", "b"}, new Object[]{new TreeSet<Integer>() {{
418+ add(2);
419+ add(3);
420+ add(4);
421+ }}, 3.4}))
422+ .add(update("foo").with(setIdx("a", 2, "foo")).and(prependAll("b", Arrays.asList(3, 2, 1))).and(remove("c", "a")).where(eq("k", 2)))
423+ .add(delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1)))
424+ .using(timestamp(42));
429425 assertEquals(batch.toString(), query);
430426
431427 // Test passing batch(statement)
@@ -450,10 +446,10 @@
450446 query += "UPDATE foo SET c=c+3;";
451447 query += "APPLY BATCH;";
452448 batch = batch()
453- .add(update("foo").with(incr("a", 1)))
454- .add(update("foo").with(incr("b", 2)))
455- .add(update("foo").with(incr("c", 3)))
456- .using(timestamp(42));
449+ .add(update("foo").with(incr("a", 1)))
450+ .add(update("foo").with(incr("b", 2)))
451+ .add(update("foo").with(incr("c", 3)))
452+ .using(timestamp(42));
457453 assertEquals(batch.toString(), query);
458454
459455 // Test single increments
@@ -463,10 +459,10 @@
463459 query += "UPDATE foo SET c=c+1;";
464460 query += "APPLY BATCH;";
465461 batch = batch()
466- .add(update("foo").with(incr("a")))
467- .add(update("foo").with(incr("b")))
468- .add(update("foo").with(incr("c")))
469- .using(timestamp(42));
462+ .add(update("foo").with(incr("a")))
463+ .add(update("foo").with(incr("b")))
464+ .add(update("foo").with(incr("c")))
465+ .using(timestamp(42));
470466 assertEquals(batch.toString(), query);
471467
472468 // Test value decrements
@@ -476,10 +472,10 @@
476472 query += "UPDATE foo SET c=c-3;";
477473 query += "APPLY BATCH;";
478474 batch = batch()
479- .add(update("foo").with(decr("a", 1)))
480- .add(update("foo").with(decr("b", 2)))
481- .add(update("foo").with(decr("c", 3)))
482- .using(timestamp(42));
475+ .add(update("foo").with(decr("a", 1)))
476+ .add(update("foo").with(decr("b", 2)))
477+ .add(update("foo").with(decr("c", 3)))
478+ .using(timestamp(42));
483479 assertEquals(batch.toString(), query);
484480
485481 // Test single decrements
@@ -489,10 +485,10 @@
489485 query += "UPDATE foo SET c=c-1;";
490486 query += "APPLY BATCH;";
491487 batch = batch()
492- .add(update("foo").with(decr("a")))
493- .add(update("foo").with(decr("b")))
494- .add(update("foo").with(decr("c")))
495- .using(timestamp(42));
488+ .add(update("foo").with(decr("a")))
489+ .add(update("foo").with(decr("b")))
490+ .add(update("foo").with(decr("c")))
491+ .using(timestamp(42));
496492 assertEquals(batch.toString(), query);
497493
498494 // Test negative decrements and negative increments
@@ -502,20 +498,20 @@
502498 query += "UPDATE foo SET c=c-3;";
503499 query += "APPLY BATCH;";
504500 batch = batch()
505- .add(update("foo").with(decr("a", -1)))
506- .add(update("foo").with(incr("b", -2)))
507- .add(update("foo").with(decr("c", 3)))
508- .using(timestamp(42));
501+ .add(update("foo").with(decr("a", -1)))
502+ .add(update("foo").with(incr("b", -2)))
503+ .add(update("foo").with(decr("c", 3)))
504+ .using(timestamp(42));
509505 assertEquals(batch.toString(), query);
510506 }
511507
512- @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
508+ @Test(groups = "unit", expectedExceptions = {IllegalArgumentException.class})
513509 public void batchMixedCounterTest() throws Exception {
514510 batch()
515- .add(update("foo").with(incr("a", 1)))
516- .add(update("foo").with(set("b", 2)))
517- .add(update("foo").with(incr("c", 3)))
518- .using(timestamp(42));
511+ .add(update("foo").with(incr("a", 1)))
512+ .add(update("foo").with(set("b", 2)))
513+ .add(update("foo").with(incr("c", 3)))
514+ .using(timestamp(42));
519515 }
520516
521517 @Test(groups = "unit")
@@ -525,8 +521,8 @@
525521
526522 query = "INSERT INTO test (k,c) VALUES (0,?);";
527523 insert = insertInto("test")
528- .value("k", 0)
529- .value("c", bindMarker());
524+ .value("k", 0)
525+ .value("c", bindMarker());
530526 assertEquals(insert.toString(), query);
531527 }
532528
@@ -625,11 +621,11 @@
625621 assertEquals(insert.toString(), query);
626622
627623 query = "INSERT INTO foo (a,b) VALUES ({'2''} space','3','4'},3.4) USING TTL 24 AND TIMESTAMP 42;";
628- insert = insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<String>() {{
624+ insert = insertInto("foo").values(new String[]{"a", "b"}, new Object[]{new TreeSet<String>() {{
629625 add("2'} space");
630626 add("3");
631627 add("4");
632- }}, 3.4 }).using(ttl(24)).and(timestamp(42));
628+ }}, 3.4}).using(ttl(24)).and(timestamp(42));
633629 assertEquals(insert.toString(), query);
634630 }
635631
@@ -684,7 +680,7 @@
684680
685681 query = "DELETE a,b FROM foo WHERE a IN ('b','c''); --comment');";
686682 delete = delete("a", "b").from("foo")
687- .where(in("a", "b", "c'); --comment"));
683+ .where(in("a", "b", "c'); --comment"));
688684 assertEquals(delete.toString(), query);
689685
690686 query = "DELETE FROM foo WHERE \"k=1 OR k\">42;";
@@ -713,7 +709,7 @@
713709 public void rejectUnknownValueTest() throws Exception {
714710 try {
715711 RegularStatement s = update("foo").with(set("a", new byte[13])).where(eq("k", 2))
716- .setForceNoValues(true);
712+ .setForceNoValues(true);
717713 s.getQueryString();
718714 fail("should have failed to inline a byte[]");
719715 } catch (CodecNotFoundException e) {
@@ -730,22 +726,22 @@
730726 @Test(groups = "unit")
731727 public void quotingTest() {
732728 assertEquals(select().from("Metrics", "epochs").toString(),
733- "SELECT * FROM Metrics.epochs;");
729+ "SELECT * FROM Metrics.epochs;");
734730 assertEquals(select().from("Metrics", quote("epochs")).toString(),
735- "SELECT * FROM Metrics.\"epochs\";");
731+ "SELECT * FROM Metrics.\"epochs\";");
736732 assertEquals(select().from(quote("Metrics"), "epochs").toString(),
737- "SELECT * FROM \"Metrics\".epochs;");
733+ "SELECT * FROM \"Metrics\".epochs;");
738734 assertEquals(select().from(quote("Metrics"), quote("epochs")).toString(),
739- "SELECT * FROM \"Metrics\".\"epochs\";");
735+ "SELECT * FROM \"Metrics\".\"epochs\";");
740736
741737 assertEquals(insertInto("Metrics", "epochs").toString(),
742- "INSERT INTO Metrics.epochs () VALUES ();");
738+ "INSERT INTO Metrics.epochs () VALUES ();");
743739 assertEquals(insertInto("Metrics", quote("epochs")).toString(),
744- "INSERT INTO Metrics.\"epochs\" () VALUES ();");
740+ "INSERT INTO Metrics.\"epochs\" () VALUES ();");
745741 assertEquals(insertInto(quote("Metrics"), "epochs").toString(),
746- "INSERT INTO \"Metrics\".epochs () VALUES ();");
742+ "INSERT INTO \"Metrics\".epochs () VALUES ();");
747743 assertEquals(insertInto(quote("Metrics"), quote("epochs")).toString(),
748- "INSERT INTO \"Metrics\".\"epochs\" () VALUES ();");
744+ "INSERT INTO \"Metrics\".\"epochs\" () VALUES ();");
749745 }
750746
751747 @Test(groups = "unit")
@@ -759,7 +755,7 @@
759755
760756 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)>=('a',2) AND (c1,c2)<('b',0);";
761757 select = select().all().from("foo").where(eq("k", 4)).and(gte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)))
762- .and(lt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("b", 0)));
758+ .and(lt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("b", 0)));
763759 assertEquals(select.toString(), query);
764760
765761 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)<=('a',2);";
@@ -779,8 +775,8 @@
779775
780776 // If the excessive count results from successive DSL calls, we don't check it on the fly so this statement works:
781777 BuiltStatement statement = select().all().from("foo")
782- .where(eq("bar", "a"))
783- .and(in("baz", values.toArray()));
778+ .where(eq("bar", "a"))
779+ .and(in("baz", values.toArray()));
784780
785781 // But we still want to check it client-side, to fail fast instead of sending a bad query to Cassandra.
786782 // getValues() is called on any RegularStatement before we send it (see SessionManager.makeRequestMessage).
@@ -866,12 +862,12 @@
866862 assertThat(select.getValues(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE)).isNull();
867863 }
868864
869- @Test(groups = "unit", expectedExceptions = { IllegalStateException.class })
865+ @Test(groups = "unit", expectedExceptions = {IllegalStateException.class})
870866 public void should_throw_ISE_if_getObject_called_on_statement_without_values() {
871867 select().from("test").where(eq("foo", 42)).getObject(0); // integers are appended to the CQL string
872868 }
873869
874- @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class })
870+ @Test(groups = "unit", expectedExceptions = {IndexOutOfBoundsException.class})
875871 public void should_throw_IOOBE_if_getObject_called_with_wrong_index() {
876872 select().from("test").where(eq("foo", new Object())).getObject(1);
877873 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java +11 −16
@@ -15,33 +15,28 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.TupleType;
20+import com.datastax.driver.core.TupleValue;
21+import com.datastax.driver.core.utils.CassandraVersion;
22+import com.google.common.collect.ImmutableList;
23+import org.testng.annotations.Test;
24+
1825 import java.util.Collection;
1926 import java.util.Collections;
2027 import java.util.List;
2128
22-import com.google.common.collect.ImmutableList;
23-import org.testng.annotations.Test;
24-
29+import static com.datastax.driver.core.DataType.cint;
30+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2531 import static org.assertj.core.api.Assertions.assertThat;
2632 import static org.testng.Assert.assertEquals;
2733
28-import com.datastax.driver.core.CCMBridge;
29-import com.datastax.driver.core.TupleType;
30-import com.datastax.driver.core.TupleValue;
31-import com.datastax.driver.core.utils.CassandraVersion;
32-
33-import static com.datastax.driver.core.DataType.cint;
34-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
35-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
36-import static com.datastax.driver.core.querybuilder.QueryBuilder.set;
37-import static com.datastax.driver.core.querybuilder.QueryBuilder.update;
38-
39-@CassandraVersion(major=2.1, minor=3)
34+@CassandraVersion(major = 2.1, minor = 3)
4035 public class QueryBuilderTupleExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
4136
4237 @Override
4338 protected Collection<String> getTableDefinitions() {
44- return Collections.emptyList();
39+ return Collections.emptyList();
4540 }
4641
4742 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java +10 −12
@@ -15,30 +15,28 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.utils.CassandraVersion;
20+import com.google.common.collect.ImmutableList;
21+import com.google.common.collect.Maps;
22+import org.testng.annotations.Test;
23+
1824 import java.net.InetAddress;
1925 import java.util.Arrays;
2026 import java.util.Collection;
2127 import java.util.List;
2228 import java.util.Map;
2329
24-import com.google.common.collect.ImmutableList;
25-import com.google.common.collect.Maps;
26-import org.testng.annotations.Test;
27-
30+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2831 import static org.assertj.core.api.Assertions.assertThat;
2932 import static org.testng.Assert.assertEquals;
3033
31-import com.datastax.driver.core.*;
32-import com.datastax.driver.core.utils.CassandraVersion;
33-
34-import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
35-
36-@CassandraVersion(major=2.1, minor=3)
34+@CassandraVersion(major = 2.1, minor = 3)
3735 public class QueryBuilderUDTExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
3836
3937 @Override
4038 protected Collection<String> getTableDefinitions() {
41- return Arrays.asList("CREATE TYPE udt (i int, a inet)",
39+ return Arrays.asList("CREATE TYPE udt (i int, a inet)",
4240 "CREATE TABLE udtTest(k int PRIMARY KEY, t frozen<udt>, l list<frozen<udt>>, m map<int, frozen<udt>>)");
4341 }
4442
@@ -83,7 +81,7 @@
8381 map.put(2, udtValue2);
8482 Statement updateMap = update("udtTest").with(putAll("m", map)).where(eq("k", 1));
8583 assertThat(updateMap.toString())
86- .isEqualTo("UPDATE udtTest SET m=m+{0:{i:2,a:'127.0.0.1'},2:{i:3,a:'127.0.0.1'}} WHERE k=1;");
84+ .isEqualTo("UPDATE udtTest SET m=m+{0:{i:2,a:'127.0.0.1'},2:{i:3,a:'127.0.0.1'}} WHERE k=1;");
8785
8886 session.execute(updateMap);
8987
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/AlterTest.java +50 −52
@@ -15,13 +15,11 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import org.testng.annotations.Test;
19-
20-import static org.assertj.core.api.Assertions.assertThat;
21-
2218 import com.datastax.driver.core.DataType;
19+import org.testng.annotations.Test;
2320
2421 import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*;
22+import static org.assertj.core.api.Assertions.assertThat;
2523
2624 public class AlterTest {
2725
@@ -94,96 +92,96 @@
9492 // Note that this does not necessarily represent a valid configuration, the goal is just to test all options
9593 // (some of which might be specific to C* 2.0 or 2.1)
9694 SchemaStatement statement = alterTable("test").withOptions()
97- .bloomFilterFPChance(0.01)
98- .caching(Caching.ROWS_ONLY)
99- .comment("This is a comment")
100- .compactionOptions(leveledStrategy().ssTableSizeInMB(160))
101- .compressionOptions(lz4())
102- .dcLocalReadRepairChance(0.21)
103- .defaultTimeToLive(100)
104- .gcGraceSeconds(9999)
105- .indexInterval(256)
106- .minIndexInterval(64)
107- .maxIndexInterval(512)
108- .memtableFlushPeriodInMillis(12)
109- .populateIOCacheOnFlush(true)
110- .replicateOnWrite(true)
111- .readRepairChance(0.42)
112- .speculativeRetry(always());
95+ .bloomFilterFPChance(0.01)
96+ .caching(Caching.ROWS_ONLY)
97+ .comment("This is a comment")
98+ .compactionOptions(leveledStrategy().ssTableSizeInMB(160))
99+ .compressionOptions(lz4())
100+ .dcLocalReadRepairChance(0.21)
101+ .defaultTimeToLive(100)
102+ .gcGraceSeconds(9999)
103+ .indexInterval(256)
104+ .minIndexInterval(64)
105+ .maxIndexInterval(512)
106+ .memtableFlushPeriodInMillis(12)
107+ .populateIOCacheOnFlush(true)
108+ .replicateOnWrite(true)
109+ .readRepairChance(0.42)
110+ .speculativeRetry(always());
113111
114112 SchemaStatement statementWith21Caching = alterTable("test").withOptions()
115- .caching(KeyCaching.NONE, rows(100));
113+ .caching(KeyCaching.NONE, rows(100));
116114
117115 //Then
118116 assertThat(statement.getQueryString()).isEqualTo("\n\tALTER TABLE test\n\t" +
119- "WITH caching = 'rows_only' " +
120- "AND bloom_filter_fp_chance = 0.01 " +
121- "AND comment = 'This is a comment' " +
122- "AND compression = {'sstable_compression' : 'LZ4Compressor'} " +
123- "AND compaction = {'class' : 'LeveledCompactionStrategy', 'sstable_size_in_mb' : 160} " +
124- "AND dclocal_read_repair_chance = 0.21 " +
125- "AND default_time_to_live = 100 " +
126- "AND gc_grace_seconds = 9999 " +
127- "AND index_interval = 256 " +
128- "AND min_index_interval = 64 " +
129- "AND max_index_interval = 512 " +
130- "AND memtable_flush_period_in_ms = 12 " +
131- "AND populate_io_cache_on_flush = true " +
132- "AND read_repair_chance = 0.42 " +
133- "AND replicate_on_write = true " +
134- "AND speculative_retry = 'ALWAYS'");
117+ "WITH caching = 'rows_only' " +
118+ "AND bloom_filter_fp_chance = 0.01 " +
119+ "AND comment = 'This is a comment' " +
120+ "AND compression = {'sstable_compression' : 'LZ4Compressor'} " +
121+ "AND compaction = {'class' : 'LeveledCompactionStrategy', 'sstable_size_in_mb' : 160} " +
122+ "AND dclocal_read_repair_chance = 0.21 " +
123+ "AND default_time_to_live = 100 " +
124+ "AND gc_grace_seconds = 9999 " +
125+ "AND index_interval = 256 " +
126+ "AND min_index_interval = 64 " +
127+ "AND max_index_interval = 512 " +
128+ "AND memtable_flush_period_in_ms = 12 " +
129+ "AND populate_io_cache_on_flush = true " +
130+ "AND read_repair_chance = 0.42 " +
131+ "AND replicate_on_write = true " +
132+ "AND speculative_retry = 'ALWAYS'");
135133
136134 assertThat(statementWith21Caching.getQueryString()).isEqualTo("\n\tALTER TABLE test\n\t" +
137- "WITH caching = {'keys' : 'none', 'rows_per_partition' : 100}");
135+ "WITH caching = {'keys' : 'none', 'rows_per_partition' : 100}");
138136 }
139137
140138 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
141- expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword")
139+ expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword")
142140 public void should_fail_if_keyspace_name_is_a_reserved_keyword() throws Exception {
143141 alterTable("add", "test")
144- .addColumn("test").type(DataType.ascii());
142+ .addColumn("test").type(DataType.ascii());
145143 }
146144
147145 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
148- expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword")
146+ expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword")
149147 public void should_fail_if_table_name_is_a_reserved_keyword() throws Exception {
150148 alterTable("add")
151- .addColumn("test").type(DataType.ascii());
149+ .addColumn("test").type(DataType.ascii());
152150 }
153151
154152 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
155- expectedExceptionsMessageRegExp = "The new column name 'add' is not allowed because it is a reserved keyword")
153+ expectedExceptionsMessageRegExp = "The new column name 'add' is not allowed because it is a reserved keyword")
156154 public void should_fail_if_added_column_is_a_reserved_keyword() throws Exception {
157155 alterTable("test")
158- .addColumn("add").type(DataType.ascii()).getQueryString();
156+ .addColumn("add").type(DataType.ascii()).getQueryString();
159157 }
160158
161159 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
162- expectedExceptionsMessageRegExp = "The altered column name 'add' is not allowed because it is a reserved keyword")
160+ expectedExceptionsMessageRegExp = "The altered column name 'add' is not allowed because it is a reserved keyword")
163161 public void should_fail_if_altered_column_is_a_reserved_keyword() throws Exception {
164162 alterTable("test")
165- .alterColumn("add").type(DataType.ascii()).getQueryString();
163+ .alterColumn("add").type(DataType.ascii()).getQueryString();
166164 }
167165
168166 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
169- expectedExceptionsMessageRegExp = "The renamed column name 'add' is not allowed because it is a reserved keyword")
167+ expectedExceptionsMessageRegExp = "The renamed column name 'add' is not allowed because it is a reserved keyword")
170168 public void should_fail_if_renamed_column_is_a_reserved_keyword() throws Exception {
171169 alterTable("test")
172- .renameColumn("add");
170+ .renameColumn("add");
173171 }
174172
175173 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
176- expectedExceptionsMessageRegExp = "The new column name 'add' is not allowed because it is a reserved keyword")
174+ expectedExceptionsMessageRegExp = "The new column name 'add' is not allowed because it is a reserved keyword")
177175 public void should_fail_if_new_renamed_column_is_a_reserved_keyword() throws Exception {
178176 alterTable("test")
179- .renameColumn("col").to("add");
177+ .renameColumn("col").to("add");
180178 }
181179
182180 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
183- expectedExceptionsMessageRegExp = "The dropped column name 'add' is not allowed because it is a reserved keyword")
181+ expectedExceptionsMessageRegExp = "The dropped column name 'add' is not allowed because it is a reserved keyword")
184182 public void should_fail_if_drop_column_is_a_reserved_keyword() throws Exception {
185183 alterTable("test")
186- .dropColumn("add").getQueryString();
184+ .dropColumn("add").getQueryString();
187185 }
188186
189187 @Test(groups = "unit")
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompactionOptionsTest.java +74 −77
@@ -17,12 +17,9 @@
1717
1818 import org.testng.annotations.Test;
1919
20-import static org.assertj.core.api.Assertions.assertThat;
21-
22-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.dateTieredStrategy;
23-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.leveledStrategy;
24-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.sizedTieredStategy;
20+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*;
2521 import static com.datastax.driver.core.schemabuilder.TableOptions.CompactionOptions.DateTieredCompactionStrategyOptions.TimeStampResolution;
22+import static org.assertj.core.api.Assertions.assertThat;
2623
2724 public class CompactionOptionsTest {
2825
@@ -30,128 +27,128 @@
3027 public void should_create_sized_tiered_compaction_options() throws Exception {
3128 //When
3229 final String built = sizedTieredStategy()
33- .bucketLow(0.5)
34- .bucketHigh(1.2)
35- .coldReadsRatioToOmit(0.89)
36- .enabled(true)
37- .minThreshold(2)
38- .maxThreshold(4)
39- .minSSTableSizeInBytes(5000000L)
40- .tombstoneCompactionIntervalInDay(3)
41- .tombstoneThreshold(0.7)
42- .uncheckedTombstoneCompaction(true)
43- .build();
30+ .bucketLow(0.5)
31+ .bucketHigh(1.2)
32+ .coldReadsRatioToOmit(0.89)
33+ .enabled(true)
34+ .minThreshold(2)
35+ .maxThreshold(4)
36+ .minSSTableSizeInBytes(5000000L)
37+ .tombstoneCompactionIntervalInDay(3)
38+ .tombstoneThreshold(0.7)
39+ .uncheckedTombstoneCompaction(true)
40+ .build();
4441
4542 //Then
4643 assertThat(built).isEqualTo("{'class' : 'SizeTieredCompactionStrategy', " +
47- "'enabled' : true, " +
48- "'tombstone_compaction_interval' : 3, " +
49- "'tombstone_threshold' : 0.7, " +
50- "'unchecked_tombstone_compaction' : true, " +
51- "'bucket_high' : 1.2, " +
52- "'bucket_low' : 0.5, " +
53- "'cold_reads_to_omit' : 0.89, " +
54- "'min_threshold' : 2, " +
55- "'max_threshold' : 4, " +
56- "'min_sstable_size' : 5000000}");
44+ "'enabled' : true, " +
45+ "'tombstone_compaction_interval' : 3, " +
46+ "'tombstone_threshold' : 0.7, " +
47+ "'unchecked_tombstone_compaction' : true, " +
48+ "'bucket_high' : 1.2, " +
49+ "'bucket_low' : 0.5, " +
50+ "'cold_reads_to_omit' : 0.89, " +
51+ "'min_threshold' : 2, " +
52+ "'max_threshold' : 4, " +
53+ "'min_sstable_size' : 5000000}");
5754 }
5855
5956 @Test(groups = "unit")
6057 public void should_create_leveled_compaction_option() throws Exception {
6158 //When
6259 final String built = leveledStrategy()
63- .enabled(true)
64- .ssTableSizeInMB(160)
65- .tombstoneCompactionIntervalInDay(3)
66- .tombstoneThreshold(0.7)
67- .uncheckedTombstoneCompaction(true)
68- .build();
60+ .enabled(true)
61+ .ssTableSizeInMB(160)
62+ .tombstoneCompactionIntervalInDay(3)
63+ .tombstoneThreshold(0.7)
64+ .uncheckedTombstoneCompaction(true)
65+ .build();
6966
7067 //Then
7168 assertThat(built).isEqualTo("{'class' : 'LeveledCompactionStrategy', " +
72- "'enabled' : true, " +
73- "'tombstone_compaction_interval' : 3, " +
74- "'tombstone_threshold' : 0.7, " +
75- "'unchecked_tombstone_compaction' : true, " +
76- "'sstable_size_in_mb' : 160}");
69+ "'enabled' : true, " +
70+ "'tombstone_compaction_interval' : 3, " +
71+ "'tombstone_threshold' : 0.7, " +
72+ "'unchecked_tombstone_compaction' : true, " +
73+ "'sstable_size_in_mb' : 160}");
7774 }
7875
7976 @Test(groups = "unit")
8077 public void should_create_date_tiered_compaction_option() throws Exception {
8178 //When
8279 String built = dateTieredStrategy()
83- .baseTimeSeconds(7200)
84- .enabled(true)
85- .maxSSTableAgeDays(400)
86- .minThreshold(2)
87- .maxThreshold(4)
88- .timestampResolution(TimeStampResolution.MICROSECONDS)
89- .tombstoneCompactionIntervalInDay(3)
90- .tombstoneThreshold(0.7)
91- .uncheckedTombstoneCompaction(true)
92- .build();
80+ .baseTimeSeconds(7200)
81+ .enabled(true)
82+ .maxSSTableAgeDays(400)
83+ .minThreshold(2)
84+ .maxThreshold(4)
85+ .timestampResolution(TimeStampResolution.MICROSECONDS)
86+ .tombstoneCompactionIntervalInDay(3)
87+ .tombstoneThreshold(0.7)
88+ .uncheckedTombstoneCompaction(true)
89+ .build();
9390
9491 //Then
9592 assertThat(built).isEqualTo("{'class' : 'DateTieredCompactionStrategy', " +
96- "'enabled' : true, " +
97- "'tombstone_compaction_interval' : 3, " +
98- "'tombstone_threshold' : 0.7, " +
99- "'unchecked_tombstone_compaction' : true, " +
100- "'base_time_seconds' : 7200, " +
101- "'max_sstable_age_days' : 400, " +
102- "'min_threshold' : 2, " +
103- "'max_threshold' : 4, " +
104- "'timestamp_resolution' : 'MICROSECONDS'}");
93+ "'enabled' : true, " +
94+ "'tombstone_compaction_interval' : 3, " +
95+ "'tombstone_threshold' : 0.7, " +
96+ "'unchecked_tombstone_compaction' : true, " +
97+ "'base_time_seconds' : 7200, " +
98+ "'max_sstable_age_days' : 400, " +
99+ "'min_threshold' : 2, " +
100+ "'max_threshold' : 4, " +
101+ "'timestamp_resolution' : 'MICROSECONDS'}");
105102 }
106103
107104 @Test(groups = "unit")
108105 public void should_handle_freeform_options() {
109106 //When
110107 String built = dateTieredStrategy()
111- .freeformOption("foo", "bar")
112- .freeformOption("baz", 1)
113- .build();
108+ .freeformOption("foo", "bar")
109+ .freeformOption("baz", 1)
110+ .build();
114111
115112 //Then
116113 assertThat(built).isEqualTo("{'class' : 'DateTieredCompactionStrategy', " +
117- "'foo' : 'bar', " +
118- "'baz' : 1}");
114+ "'foo' : 'bar', " +
115+ "'baz' : 1}");
119116
120117 }
121118
122119 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
123120 public void should_throw_exception_if_cold_read_ratio_out_of_range() throws Exception {
124121 sizedTieredStategy()
125- .bucketLow(0.5)
126- .bucketHigh(1.2)
127- .coldReadsRatioToOmit(1.89)
128- .build();
122+ .bucketLow(0.5)
123+ .bucketHigh(1.2)
124+ .coldReadsRatioToOmit(1.89)
125+ .build();
129126 }
130127
131128 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
132129 public void should_throw_exception_if_cold_read_ratio_negative() throws Exception {
133130 sizedTieredStategy()
134- .bucketLow(0.5)
135- .bucketHigh(1.2)
136- .coldReadsRatioToOmit(-1.0)
137- .build();
131+ .bucketLow(0.5)
132+ .bucketHigh(1.2)
133+ .coldReadsRatioToOmit(-1.0)
134+ .build();
138135 }
139136
140137 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
141138 public void should_throw_exception_if_tombstone_threshold_out_of_range() throws Exception {
142139 sizedTieredStategy()
143- .bucketLow(0.5)
144- .bucketHigh(1.2)
145- .tombstoneThreshold(1.89)
146- .build();
140+ .bucketLow(0.5)
141+ .bucketHigh(1.2)
142+ .tombstoneThreshold(1.89)
143+ .build();
147144 }
148145
149146 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
150147 public void should_throw_exception_if_tombstone_threshold_negative() throws Exception {
151148 sizedTieredStategy()
152- .bucketLow(0.5)
153- .bucketHigh(1.2)
154- .coldReadsRatioToOmit(-1.0)
155- .build();
149+ .bucketLow(0.5)
150+ .bucketHigh(1.2)
151+ .coldReadsRatioToOmit(-1.0)
152+ .build();
156153 }
157154 }
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompressionOptionsTest.java +1 −5
@@ -17,13 +17,9 @@
1717
1818 import org.testng.annotations.Test;
1919
20+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*;
2021 import static org.assertj.core.api.Assertions.assertThat;
2122
22-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.deflate;
23-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.lz4;
24-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.noCompression;
25-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.snappy;
26-
2723 public class CompressionOptionsTest {
2824
2925 @Test(groups = "unit")
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateIndexTest.java +1 −2
@@ -17,9 +17,8 @@
1717
1818 import org.testng.annotations.Test;
1919
20-import static org.assertj.core.api.Assertions.assertThat;
21-
2220 import static com.datastax.driver.core.schemabuilder.SchemaBuilder.createIndex;
21+import static org.assertj.core.api.Assertions.assertThat;
2322
2423 public class CreateIndexTest {
2524
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTest.java +283 −285
@@ -15,13 +15,11 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import org.testng.annotations.Test;
19-
20-import static org.assertj.core.api.Assertions.assertThat;
21-
2218 import com.datastax.driver.core.DataType;
19+import org.testng.annotations.Test;
2320
2421 import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*;
22+import static org.assertj.core.api.Assertions.assertThat;
2523
2624 /**
2725 * Note: some addColumn variants are covered in {@link CreateTypeTest}.
@@ -32,26 +30,26 @@
3230 public void should_create_simple_table() throws Exception {
3331 //When
3432 SchemaStatement statement = createTable("test")
35- .addPartitionKey("id", DataType.bigint())
36- .addColumn("name", DataType.text());
33+ .addPartitionKey("id", DataType.bigint())
34+ .addColumn("name", DataType.text());
3735
3836 //Then
3937 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
40- "id bigint,\n\t\t" +
41- "name text,\n\t\t" +
42- "PRIMARY KEY(id))");
38+ "id bigint,\n\t\t" +
39+ "name text,\n\t\t" +
40+ "PRIMARY KEY(id))");
4341 }
4442
4543 @Test(groups = "unit")
4644 public void should_create_table_with_udt_partition_key() throws Exception {
4745 //When
4846 SchemaStatement statement = createTable("test")
49- .addUDTPartitionKey("u", frozen("user"));
47+ .addUDTPartitionKey("u", frozen("user"));
5048
5149 //Then
5250 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
53- "u frozen<user>,\n\t\t" +
54- "PRIMARY KEY(u))"
51+ "u frozen<user>,\n\t\t" +
52+ "PRIMARY KEY(u))"
5553 );
5654 }
5755
@@ -64,547 +62,547 @@
6462 public void should_create_simple_table_if_not_exists() throws Exception {
6563 //When
6664 SchemaStatement statement = createTable("test")
67- .ifNotExists()
68- .addPartitionKey("id", DataType.bigint())
69- .addColumn("name", DataType.text());
65+ .ifNotExists()
66+ .addPartitionKey("id", DataType.bigint())
67+ .addColumn("name", DataType.text());
7068 //Then
7169 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE IF NOT EXISTS test(\n\t\t" +
72- "id bigint,\n\t\t" +
73- "name text,\n\t\t" +
74- "PRIMARY KEY(id))");
70+ "id bigint,\n\t\t" +
71+ "name text,\n\t\t" +
72+ "PRIMARY KEY(id))");
7573 }
7674
7775 @Test(groups = "unit")
7876 public void should_create_simple_table_with_keyspace() throws Exception {
7977 //When
8078 SchemaStatement statement = createTable("ks", "test")
81- .addPartitionKey("id", DataType.bigint())
82- .addColumn("name", DataType.text());
79+ .addPartitionKey("id", DataType.bigint())
80+ .addColumn("name", DataType.text());
8381 //Then
8482 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE ks.test(\n\t\t" +
85- "id bigint,\n\t\t" +
86- "name text,\n\t\t" +
87- "PRIMARY KEY(id))");
83+ "id bigint,\n\t\t" +
84+ "name text,\n\t\t" +
85+ "PRIMARY KEY(id))");
8886 }
8987
9088 @Test(groups = "unit")
9189 public void should_create_simple_table_with_list() throws Exception {
9290 //When
9391 SchemaStatement statement = createTable("test")
94- .addPartitionKey("id", DataType.bigint())
95- .addColumn("friends", DataType.list(DataType.text()));
92+ .addPartitionKey("id", DataType.bigint())
93+ .addColumn("friends", DataType.list(DataType.text()));
9694
9795 //Then
9896 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
99- "id bigint,\n\t\t" +
100- "friends list<text>,\n\t\t" +
101- "PRIMARY KEY(id))");
97+ "id bigint,\n\t\t" +
98+ "friends list<text>,\n\t\t" +
99+ "PRIMARY KEY(id))");
102100 }
103101
104102 @Test(groups = "unit")
105103 public void should_create_simple_table_with_set() throws Exception {
106104 //When
107105 SchemaStatement statement = createTable("test")
108- .addPartitionKey("id", DataType.bigint())
109- .addColumn("friends", DataType.set(DataType.text()));
106+ .addPartitionKey("id", DataType.bigint())
107+ .addColumn("friends", DataType.set(DataType.text()));
110108
111109 //Then
112110 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
113- "id bigint,\n\t\t" +
114- "friends set<text>,\n\t\t" +
115- "PRIMARY KEY(id))");
111+ "id bigint,\n\t\t" +
112+ "friends set<text>,\n\t\t" +
113+ "PRIMARY KEY(id))");
116114 }
117115
118116 @Test(groups = "unit")
119117 public void should_create_simple_table_with_map() throws Exception {
120118 //When
121119 SchemaStatement statement = createTable("test")
122- .addPartitionKey("id", DataType.bigint())
123- .addColumn("friends", DataType.map(DataType.cint(), DataType.text()));
120+ .addPartitionKey("id", DataType.bigint())
121+ .addColumn("friends", DataType.map(DataType.cint(), DataType.text()));
124122
125123 //Then
126124 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
127- "id bigint,\n\t\t" +
128- "friends map<int, text>,\n\t\t" +
129- "PRIMARY KEY(id))");
125+ "id bigint,\n\t\t" +
126+ "friends map<int, text>,\n\t\t" +
127+ "PRIMARY KEY(id))");
130128 }
131129
132130 @Test(groups = "unit")
133131 public void should_create_table_with_clustering_keys() throws Exception {
134132 //When
135133 SchemaStatement statement = createTable("test")
136- .addPartitionKey("id", DataType.bigint())
137- .addClusteringColumn("col1", DataType.uuid())
138- .addClusteringColumn("col2", DataType.uuid())
139- .addColumn("name", DataType.text());
134+ .addPartitionKey("id", DataType.bigint())
135+ .addClusteringColumn("col1", DataType.uuid())
136+ .addClusteringColumn("col2", DataType.uuid())
137+ .addColumn("name", DataType.text());
140138
141139 //Then
142140 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
143- "id bigint,\n\t\t" +
144- "col1 uuid,\n\t\t" +
145- "col2 uuid,\n\t\t" +
146- "name text,\n\t\t" +
147- "PRIMARY KEY(id, col1, col2))");
141+ "id bigint,\n\t\t" +
142+ "col1 uuid,\n\t\t" +
143+ "col2 uuid,\n\t\t" +
144+ "name text,\n\t\t" +
145+ "PRIMARY KEY(id, col1, col2))");
148146 }
149147
150148 @Test(groups = "unit")
151149 public void should_create_table_with_udt_clustering_keys() throws Exception {
152150 //When
153151 SchemaStatement statement = createTable("test")
154- .addPartitionKey("id", DataType.bigint())
155- .addClusteringColumn("col1", DataType.uuid())
156- .addUDTClusteringColumn("col2", frozen("address"))
157- .addColumn("name", DataType.text());
152+ .addPartitionKey("id", DataType.bigint())
153+ .addClusteringColumn("col1", DataType.uuid())
154+ .addUDTClusteringColumn("col2", frozen("address"))
155+ .addColumn("name", DataType.text());
158156
159157 //Then
160158 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
161- "id bigint,\n\t\t" +
162- "col1 uuid,\n\t\t" +
163- "col2 frozen<address>,\n\t\t" +
164- "name text,\n\t\t" +
165- "PRIMARY KEY(id, col1, col2))");
159+ "id bigint,\n\t\t" +
160+ "col1 uuid,\n\t\t" +
161+ "col2 frozen<address>,\n\t\t" +
162+ "name text,\n\t\t" +
163+ "PRIMARY KEY(id, col1, col2))");
166164 }
167165
168166 @Test(groups = "unit")
169167 public void should_create_table_with_composite_partition_key() throws Exception {
170168 //When
171169 SchemaStatement statement = createTable("test")
172- .addPartitionKey("id1", DataType.bigint())
173- .addPartitionKey("id2", DataType.text())
174- .addColumn("name", DataType.text());
170+ .addPartitionKey("id1", DataType.bigint())
171+ .addPartitionKey("id2", DataType.text())
172+ .addColumn("name", DataType.text());
175173
176174 //Then
177175 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
178- "id1 bigint,\n\t\t" +
179- "id2 text,\n\t\t" +
180- "name text,\n\t\t" +
181- "PRIMARY KEY((id1, id2)))");
176+ "id1 bigint,\n\t\t" +
177+ "id2 text,\n\t\t" +
178+ "name text,\n\t\t" +
179+ "PRIMARY KEY((id1, id2)))");
182180 }
183181
184182 @Test(groups = "unit")
185183 public void should_create_table_with_composite_partition_key_and_clustering_keys() throws Exception {
186184 //When
187185 SchemaStatement statement = createTable("test")
188- .addPartitionKey("id1", DataType.bigint())
189- .addPartitionKey("id2", DataType.text())
190- .addClusteringColumn("col1", DataType.uuid())
191- .addClusteringColumn("col2", DataType.uuid())
192- .addColumn("name", DataType.text());
186+ .addPartitionKey("id1", DataType.bigint())
187+ .addPartitionKey("id2", DataType.text())
188+ .addClusteringColumn("col1", DataType.uuid())
189+ .addClusteringColumn("col2", DataType.uuid())
190+ .addColumn("name", DataType.text());
193191
194192 //Then
195193 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
196- "id1 bigint,\n\t\t" +
197- "id2 text,\n\t\t" +
198- "col1 uuid,\n\t\t" +
199- "col2 uuid,\n\t\t" +
200- "name text,\n\t\t" +
201- "PRIMARY KEY((id1, id2), col1, col2))");
194+ "id1 bigint,\n\t\t" +
195+ "id2 text,\n\t\t" +
196+ "col1 uuid,\n\t\t" +
197+ "col2 uuid,\n\t\t" +
198+ "name text,\n\t\t" +
199+ "PRIMARY KEY((id1, id2), col1, col2))");
202200 }
203201
204202 @Test(groups = "unit")
205203 public void should_create_table_with_static_column() throws Exception {
206204 //When
207205 SchemaStatement statement = createTable("test")
208- .addPartitionKey("id", DataType.bigint())
209- .addClusteringColumn("col", DataType.uuid())
210- .addStaticColumn("bucket", DataType.cint())
211- .addColumn("name", DataType.text());
206+ .addPartitionKey("id", DataType.bigint())
207+ .addClusteringColumn("col", DataType.uuid())
208+ .addStaticColumn("bucket", DataType.cint())
209+ .addColumn("name", DataType.text());
212210
213211 //Then
214212 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
215- "id bigint,\n\t\t" +
216- "col uuid,\n\t\t" +
217- "bucket int static,\n\t\t" +
218- "name text,\n\t\t" +
219- "PRIMARY KEY(id, col))");
213+ "id bigint,\n\t\t" +
214+ "col uuid,\n\t\t" +
215+ "bucket int static,\n\t\t" +
216+ "name text,\n\t\t" +
217+ "PRIMARY KEY(id, col))");
220218 }
221219
222220 @Test(groups = "unit")
223221 public void should_create_table_with_udt_static_column() throws Exception {
224222 //When
225223 SchemaStatement statement = createTable("test")
226- .addPartitionKey("id", DataType.bigint())
227- .addClusteringColumn("col", DataType.uuid())
228- .addUDTStaticColumn("bucket", frozen("address"))
229- .addColumn("name", DataType.text());
224+ .addPartitionKey("id", DataType.bigint())
225+ .addClusteringColumn("col", DataType.uuid())
226+ .addUDTStaticColumn("bucket", frozen("address"))
227+ .addColumn("name", DataType.text());
230228
231229 //Then
232230 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
233- "id bigint,\n\t\t" +
234- "col uuid,\n\t\t" +
235- "bucket frozen<address> static,\n\t\t" +
236- "name text,\n\t\t" +
237- "PRIMARY KEY(id, col))");
231+ "id bigint,\n\t\t" +
232+ "col uuid,\n\t\t" +
233+ "bucket frozen<address> static,\n\t\t" +
234+ "name text,\n\t\t" +
235+ "PRIMARY KEY(id, col))");
238236 }
239237
240238 @Test(groups = "unit")
241239 public void should_create_table_with_clustering_order() throws Exception {
242240 //When
243241 SchemaStatement statement = createTable("test")
244- .addPartitionKey("id", DataType.bigint())
245- .addClusteringColumn("col1", DataType.uuid())
246- .addClusteringColumn("col2", DataType.uuid())
247- .addColumn("name", DataType.text())
248- .withOptions()
249- .clusteringOrder("col1", Direction.ASC)
250- .clusteringOrder("col2", Direction.DESC);
242+ .addPartitionKey("id", DataType.bigint())
243+ .addClusteringColumn("col1", DataType.uuid())
244+ .addClusteringColumn("col2", DataType.uuid())
245+ .addColumn("name", DataType.text())
246+ .withOptions()
247+ .clusteringOrder("col1", Direction.ASC)
248+ .clusteringOrder("col2", Direction.DESC);
251249
252250 //Then
253251 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
254- "id bigint,\n\t\t" +
255- "col1 uuid,\n\t\t" +
256- "col2 uuid,\n\t\t" +
257- "name text,\n\t\t" +
258- "PRIMARY KEY(id, col1, col2))\n\t" +
259- "WITH CLUSTERING ORDER BY(col1 ASC, col2 DESC)");
252+ "id bigint,\n\t\t" +
253+ "col1 uuid,\n\t\t" +
254+ "col2 uuid,\n\t\t" +
255+ "name text,\n\t\t" +
256+ "PRIMARY KEY(id, col1, col2))\n\t" +
257+ "WITH CLUSTERING ORDER BY(col1 ASC, col2 DESC)");
260258 }
261259
262260 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
263261 public void should_fail_when_blank_clustering_order_column_provided() throws Exception {
264262 createTable("test")
265- .addPartitionKey("id", DataType.bigint())
266- .addClusteringColumn("col1", DataType.uuid())
267- .addClusteringColumn("col2", DataType.uuid())
268- .addColumn("name", DataType.text())
269- .withOptions().clusteringOrder("", Direction.DESC);
263+ .addPartitionKey("id", DataType.bigint())
264+ .addClusteringColumn("col1", DataType.uuid())
265+ .addClusteringColumn("col2", DataType.uuid())
266+ .addColumn("name", DataType.text())
267+ .withOptions().clusteringOrder("", Direction.DESC);
270268 }
271269
272270 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
273271 public void should_fail_when_clustering_order_column_does_not_match_declared_clustering_keys() throws Exception {
274272 createTable("test")
275- .addPartitionKey("id", DataType.bigint())
276- .addClusteringColumn("col1", DataType.uuid())
277- .addClusteringColumn("col2", DataType.uuid())
278- .addColumn("name", DataType.text())
279- .withOptions().clusteringOrder("col3", Direction.ASC);
273+ .addPartitionKey("id", DataType.bigint())
274+ .addClusteringColumn("col1", DataType.uuid())
275+ .addClusteringColumn("col2", DataType.uuid())
276+ .addColumn("name", DataType.text())
277+ .withOptions().clusteringOrder("col3", Direction.ASC);
280278 }
281279
282280 @Test(groups = "unit")
283281 public void should_create_table_with_compact_storage() throws Exception {
284282 //When
285283 SchemaStatement statement = createTable("test")
286- .addPartitionKey("id", DataType.bigint())
287- .addClusteringColumn("col1", DataType.uuid())
288- .addClusteringColumn("col2", DataType.uuid())
289- .addColumn("name", DataType.text())
290- .withOptions()
291- .compactStorage();
284+ .addPartitionKey("id", DataType.bigint())
285+ .addClusteringColumn("col1", DataType.uuid())
286+ .addClusteringColumn("col2", DataType.uuid())
287+ .addColumn("name", DataType.text())
288+ .withOptions()
289+ .compactStorage();
292290
293291 //Then
294292 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
295- "id bigint,\n\t\t" +
296- "col1 uuid,\n\t\t" +
297- "col2 uuid,\n\t\t" +
298- "name text,\n\t\t" +
299- "PRIMARY KEY(id, col1, col2))\n\t" +
300- "WITH COMPACT STORAGE");
293+ "id bigint,\n\t\t" +
294+ "col1 uuid,\n\t\t" +
295+ "col2 uuid,\n\t\t" +
296+ "name text,\n\t\t" +
297+ "PRIMARY KEY(id, col1, col2))\n\t" +
298+ "WITH COMPACT STORAGE");
301299 }
302300
303301 @Test(groups = "unit")
304302 public void should_create_table_with_all_options() throws Exception {
305303 //When
306304 SchemaStatement statement = createTable("test")
307- .addPartitionKey("id", DataType.bigint())
308- .addClusteringColumn("col1", DataType.uuid())
309- .addClusteringColumn("col2", DataType.uuid())
310- .addColumn("name", DataType.text())
311- .withOptions()
312- .clusteringOrder("col1", Direction.ASC)
313- .clusteringOrder("col2", Direction.DESC)
314- .compactStorage()
315- .bloomFilterFPChance(0.01)
316- .caching(Caching.ROWS_ONLY)
317- .comment("This is a comment")
318- .compactionOptions(leveledStrategy().ssTableSizeInMB(160))
319- .compressionOptions(lz4())
320- .dcLocalReadRepairChance(0.21)
321- .defaultTimeToLive(100)
322- .gcGraceSeconds(9999)
323- .minIndexInterval(64)
324- .maxIndexInterval(512)
325- .memtableFlushPeriodInMillis(12)
326- .populateIOCacheOnFlush(true)
327- .readRepairChance(0.05)
328- .replicateOnWrite(true)
329- .speculativeRetry(always());
305+ .addPartitionKey("id", DataType.bigint())
306+ .addClusteringColumn("col1", DataType.uuid())
307+ .addClusteringColumn("col2", DataType.uuid())
308+ .addColumn("name", DataType.text())
309+ .withOptions()
310+ .clusteringOrder("col1", Direction.ASC)
311+ .clusteringOrder("col2", Direction.DESC)
312+ .compactStorage()
313+ .bloomFilterFPChance(0.01)
314+ .caching(Caching.ROWS_ONLY)
315+ .comment("This is a comment")
316+ .compactionOptions(leveledStrategy().ssTableSizeInMB(160))
317+ .compressionOptions(lz4())
318+ .dcLocalReadRepairChance(0.21)
319+ .defaultTimeToLive(100)
320+ .gcGraceSeconds(9999)
321+ .minIndexInterval(64)
322+ .maxIndexInterval(512)
323+ .memtableFlushPeriodInMillis(12)
324+ .populateIOCacheOnFlush(true)
325+ .readRepairChance(0.05)
326+ .replicateOnWrite(true)
327+ .speculativeRetry(always());
330328
331329 //Then
332330 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
333- "id bigint,\n\t\t" +
334- "col1 uuid,\n\t\t" +
335- "col2 uuid,\n\t\t" +
336- "name text,\n\t\tPRIMARY KEY(id, col1, col2))\n\t" +
337- "WITH caching = 'rows_only' " +
338- "AND bloom_filter_fp_chance = 0.01 " +
339- "AND comment = 'This is a comment' " +
340- "AND compression = {'sstable_compression' : 'LZ4Compressor'} " +
341- "AND compaction = {'class' : 'LeveledCompactionStrategy', 'sstable_size_in_mb' : 160} " +
342- "AND dclocal_read_repair_chance = 0.21 " +
343- "AND default_time_to_live = 100 " +
344- "AND gc_grace_seconds = 9999 " +
345- "AND min_index_interval = 64 " +
346- "AND max_index_interval = 512 " +
347- "AND memtable_flush_period_in_ms = 12 " +
348- "AND populate_io_cache_on_flush = true " +
349- "AND read_repair_chance = 0.05 " +
350- "AND replicate_on_write = true " +
351- "AND speculative_retry = 'ALWAYS' AND CLUSTERING ORDER BY(col1 ASC, col2 DESC) AND COMPACT STORAGE");
331+ "id bigint,\n\t\t" +
332+ "col1 uuid,\n\t\t" +
333+ "col2 uuid,\n\t\t" +
334+ "name text,\n\t\tPRIMARY KEY(id, col1, col2))\n\t" +
335+ "WITH caching = 'rows_only' " +
336+ "AND bloom_filter_fp_chance = 0.01 " +
337+ "AND comment = 'This is a comment' " +
338+ "AND compression = {'sstable_compression' : 'LZ4Compressor'} " +
339+ "AND compaction = {'class' : 'LeveledCompactionStrategy', 'sstable_size_in_mb' : 160} " +
340+ "AND dclocal_read_repair_chance = 0.21 " +
341+ "AND default_time_to_live = 100 " +
342+ "AND gc_grace_seconds = 9999 " +
343+ "AND min_index_interval = 64 " +
344+ "AND max_index_interval = 512 " +
345+ "AND memtable_flush_period_in_ms = 12 " +
346+ "AND populate_io_cache_on_flush = true " +
347+ "AND read_repair_chance = 0.05 " +
348+ "AND replicate_on_write = true " +
349+ "AND speculative_retry = 'ALWAYS' AND CLUSTERING ORDER BY(col1 ASC, col2 DESC) AND COMPACT STORAGE");
352350 }
353351
354352 @Test(groups = "unit")
355353 public void should_build_table_with_new_caching_options() throws Exception {
356354 //When
357355 SchemaStatement statement = createTable("test")
358- .addPartitionKey("id", DataType.bigint())
359- .addColumn("name", DataType.text())
360- .withOptions()
361- .caching(KeyCaching.ALL, rows(100));
356+ .addPartitionKey("id", DataType.bigint())
357+ .addColumn("name", DataType.text())
358+ .withOptions()
359+ .caching(KeyCaching.ALL, rows(100));
362360
363361 //Then
364362 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
365- "id bigint,\n\t\t" +
366- "name text,\n\t\tPRIMARY KEY(id))\n\t" +
367- "WITH caching = {'keys' : 'all', 'rows_per_partition' : 100}");
363+ "id bigint,\n\t\t" +
364+ "name text,\n\t\tPRIMARY KEY(id))\n\t" +
365+ "WITH caching = {'keys' : 'all', 'rows_per_partition' : 100}");
368366
369367 //When
370368 statement = createTable("test")
371- .addPartitionKey("id", DataType.bigint())
372- .addColumn("name", DataType.text())
373- .withOptions()
374- .caching(KeyCaching.ALL, allRows());
369+ .addPartitionKey("id", DataType.bigint())
370+ .addColumn("name", DataType.text())
371+ .withOptions()
372+ .caching(KeyCaching.ALL, allRows());
375373
376374 //Then
377375 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
378- "id bigint,\n\t\t" +
379- "name text,\n\t\tPRIMARY KEY(id))\n\t" +
380- "WITH caching = {'keys' : 'all', 'rows_per_partition' : 'all'}");
376+ "id bigint,\n\t\t" +
377+ "name text,\n\t\tPRIMARY KEY(id))\n\t" +
378+ "WITH caching = {'keys' : 'all', 'rows_per_partition' : 'all'}");
381379 }
382380
383381 @Test(groups = "unit")
384382 public void should_build_table_with_custom_option() throws Exception {
385383 //When
386384 SchemaStatement statement = createTable("test")
387- .addPartitionKey("id", DataType.bigint())
388- .addColumn("name", DataType.text())
389- .withOptions()
390- .freeformOption("key1", "value1")
391- .freeformOption("key2", 1.0);
385+ .addPartitionKey("id", DataType.bigint())
386+ .addColumn("name", DataType.text())
387+ .withOptions()
388+ .freeformOption("key1", "value1")
389+ .freeformOption("key2", 1.0);
392390
393391 //Then
394392 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
395- "id bigint,\n\t\t" +
396- "name text,\n\t\tPRIMARY KEY(id))\n\t" +
397- "WITH key1 = 'value1' " +
398- "AND key2 = 1.0");
393+ "id bigint,\n\t\t" +
394+ "name text,\n\t\tPRIMARY KEY(id))\n\t" +
395+ "WITH key1 = 'value1' " +
396+ "AND key2 = 1.0");
399397 }
400398
401399 @Test(groups = "unit", expectedExceptions = IllegalStateException.class)
402400 public void should_fail_when_both_caching_versions() throws Exception {
403401 createTable("test")
404- .addPartitionKey("id", DataType.bigint())
405- .addColumn("name", DataType.text())
406- .withOptions()
407- .caching(Caching.KEYS_ONLY)
408- .caching(KeyCaching.ALL, allRows()).getQueryString();
402+ .addPartitionKey("id", DataType.bigint())
403+ .addColumn("name", DataType.text())
404+ .withOptions()
405+ .caching(Caching.KEYS_ONLY)
406+ .caching(KeyCaching.ALL, allRows()).getQueryString();
409407 }
410408
411409 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
412410 public void should_fail_when_negative_rows_per_partition() throws Exception {
413411 createTable("test")
414- .addPartitionKey("id", DataType.bigint())
415- .addColumn("name", DataType.text())
416- .withOptions()
417- .caching(KeyCaching.ALL, rows(-3));
412+ .addPartitionKey("id", DataType.bigint())
413+ .addColumn("name", DataType.text())
414+ .withOptions()
415+ .caching(KeyCaching.ALL, rows(-3));
418416 }
419417
420418 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
421419 public void should_fail_when_read_repair_chance_out_of_bound() throws Exception {
422420 createTable("test")
423- .addPartitionKey("id", DataType.bigint())
424- .addColumn("name", DataType.text())
425- .withOptions()
426- .readRepairChance(1.3);
421+ .addPartitionKey("id", DataType.bigint())
422+ .addColumn("name", DataType.text())
423+ .withOptions()
424+ .readRepairChance(1.3);
427425 }
428426
429427 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
430428 public void should_fail_when_read_repair_chance_negative() throws Exception {
431429 createTable("test")
432- .addPartitionKey("id", DataType.bigint())
433- .addColumn("name", DataType.text())
434- .withOptions()
435- .readRepairChance(-1.3);
430+ .addPartitionKey("id", DataType.bigint())
431+ .addColumn("name", DataType.text())
432+ .withOptions()
433+ .readRepairChance(-1.3);
436434 }
437435
438436 @Test(groups = "unit")
439437 public void should_create_table_with_speculative_retry_none() throws Exception {
440438 //When
441439 SchemaStatement statement = createTable("test")
442- .addPartitionKey("id", DataType.bigint())
443- .addColumn("name", DataType.text())
444- .withOptions()
445- .speculativeRetry(noSpeculativeRetry());
440+ .addPartitionKey("id", DataType.bigint())
441+ .addColumn("name", DataType.text())
442+ .withOptions()
443+ .speculativeRetry(noSpeculativeRetry());
446444
447445 //Then
448446 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
449- "id bigint,\n\t\t" +
450- "name text,\n\t\t" +
451- "PRIMARY KEY(id))\n\t" +
452- "WITH speculative_retry = 'NONE'");
447+ "id bigint,\n\t\t" +
448+ "name text,\n\t\t" +
449+ "PRIMARY KEY(id))\n\t" +
450+ "WITH speculative_retry = 'NONE'");
453451 }
454452
455453 @Test(groups = "unit")
456454 public void should_create_table_with_speculative_retry_in_percentile() throws Exception {
457455 //When
458456 SchemaStatement statement = createTable("test")
459- .addPartitionKey("id", DataType.bigint())
460- .addColumn("name", DataType.text())
461- .withOptions()
462- .speculativeRetry(percentile(95));
457+ .addPartitionKey("id", DataType.bigint())
458+ .addColumn("name", DataType.text())
459+ .withOptions()
460+ .speculativeRetry(percentile(95));
463461
464462 //Then
465463 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
466- "id bigint,\n\t\t" +
467- "name text,\n\t\t" +
468- "PRIMARY KEY(id))\n\t" +
469- "WITH speculative_retry = '95percentile'");
464+ "id bigint,\n\t\t" +
465+ "name text,\n\t\t" +
466+ "PRIMARY KEY(id))\n\t" +
467+ "WITH speculative_retry = '95percentile'");
470468 }
471469
472470 @Test(groups = "unit")
473471 public void should_create_table_with_speculative_retry_in_milli_secs() throws Exception {
474472 //When
475473 SchemaStatement statement = createTable("test")
476- .addPartitionKey("id", DataType.bigint())
477- .addColumn("name", DataType.text())
478- .withOptions()
479- .speculativeRetry(millisecs(12));
474+ .addPartitionKey("id", DataType.bigint())
475+ .addColumn("name", DataType.text())
476+ .withOptions()
477+ .speculativeRetry(millisecs(12));
480478
481479 //Then
482480 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
483- "id bigint,\n\t\t" +
484- "name text,\n\t\t" +
485- "PRIMARY KEY(id))\n\t" +
486- "WITH speculative_retry = '12ms'");
481+ "id bigint,\n\t\t" +
482+ "name text,\n\t\t" +
483+ "PRIMARY KEY(id))\n\t" +
484+ "WITH speculative_retry = '12ms'");
487485 }
488486
489487 @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
490- expectedExceptionsMessageRegExp = "The '\\[pk\\]' columns can not be declared as partition keys and clustering keys at the same time")
488+ expectedExceptionsMessageRegExp = "The '\\[pk\\]' columns can not be declared as partition keys and clustering keys at the same time")
491489 public void should_fail_if_same_partition_and_clustering_column() throws Exception {
492490 createTable("test")
493- .addPartitionKey("pk", DataType.bigint())
494- .addClusteringColumn("pk", DataType.bigint()).getQueryString();
491+ .addPartitionKey("pk", DataType.bigint())
492+ .addClusteringColumn("pk", DataType.bigint()).getQueryString();
495493 }
496494
497495 @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
498- expectedExceptionsMessageRegExp = "The '\\[pk\\]' columns can not be declared as partition keys and simple columns at the same time")
496+ expectedExceptionsMessageRegExp = "The '\\[pk\\]' columns can not be declared as partition keys and simple columns at the same time")
499497 public void should_fail_if_same_partition_and_simple_column() throws Exception {
500498 createTable("test")
501- .addPartitionKey("pk", DataType.bigint())
502- .addColumn("pk", DataType.text()).getQueryString();
499+ .addPartitionKey("pk", DataType.bigint())
500+ .addColumn("pk", DataType.text()).getQueryString();
503501 }
504502
505503 @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
506- expectedExceptionsMessageRegExp = "The '\\[cluster\\]' columns can not be declared as clustering keys and simple columns at the same time")
504+ expectedExceptionsMessageRegExp = "The '\\[cluster\\]' columns can not be declared as clustering keys and simple columns at the same time")
507505 public void should_fail_if_same_clustering_and_simple_column() throws Exception {
508506 createTable("test")
509- .addPartitionKey("pk", DataType.bigint())
510- .addClusteringColumn("cluster", DataType.bigint())
511- .addColumn("cluster", DataType.text()).getQueryString();
507+ .addPartitionKey("pk", DataType.bigint())
508+ .addClusteringColumn("cluster", DataType.bigint())
509+ .addColumn("cluster", DataType.text()).getQueryString();
512510 }
513511
514512 @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
515- expectedExceptionsMessageRegExp = "The '\\[pk\\]' columns can not be declared as partition keys and static columns at the same time")
513+ expectedExceptionsMessageRegExp = "The '\\[pk\\]' columns can not be declared as partition keys and static columns at the same time")
516514 public void should_fail_if_same_partition_and_static_column() throws Exception {
517515 createTable("test")
518- .addPartitionKey("pk", DataType.bigint())
519- .addStaticColumn("pk", DataType.text()).getQueryString();
516+ .addPartitionKey("pk", DataType.bigint())
517+ .addStaticColumn("pk", DataType.text()).getQueryString();
520518 }
521519
522520 @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
523- expectedExceptionsMessageRegExp = "The '\\[cluster\\]' columns can not be declared as clustering keys and static columns at the same time")
521+ expectedExceptionsMessageRegExp = "The '\\[cluster\\]' columns can not be declared as clustering keys and static columns at the same time")
524522 public void should_fail_if_same_clustering_and_static_column() throws Exception {
525523 createTable("test")
526- .addPartitionKey("pk", DataType.bigint())
527- .addClusteringColumn("cluster", DataType.bigint())
528- .addStaticColumn("cluster", DataType.text()).getQueryString();
524+ .addPartitionKey("pk", DataType.bigint())
525+ .addClusteringColumn("cluster", DataType.bigint())
526+ .addStaticColumn("cluster", DataType.text()).getQueryString();
529527 }
530528
531529 @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
532- expectedExceptionsMessageRegExp = "The '\\[col\\]' columns can not be declared as simple columns and static columns at the same time")
530+ expectedExceptionsMessageRegExp = "The '\\[col\\]' columns can not be declared as simple columns and static columns at the same time")
533531 public void should_fail_if_same_simple_and_static_column() throws Exception {
534532 createTable("test")
535- .addPartitionKey("pk", DataType.bigint())
536- .addClusteringColumn("cluster", DataType.uuid())
537- .addColumn("col", DataType.bigint())
538- .addStaticColumn("col", DataType.text()).getQueryString();
533+ .addPartitionKey("pk", DataType.bigint())
534+ .addClusteringColumn("cluster", DataType.uuid())
535+ .addColumn("col", DataType.bigint())
536+ .addStaticColumn("col", DataType.text()).getQueryString();
539537 }
540538
541539 @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
542- expectedExceptionsMessageRegExp = "The table 'test' cannot declare static columns '\\[stat\\]' without clustering columns")
540+ expectedExceptionsMessageRegExp = "The table 'test' cannot declare static columns '\\[stat\\]' without clustering columns")
543541 public void should_fail_if_static_column_in_non_clustered_table() throws Exception {
544542 createTable("test")
545- .addPartitionKey("pk", DataType.bigint())
546- .addStaticColumn("stat", DataType.text()).getQueryString();
543+ .addPartitionKey("pk", DataType.bigint())
544+ .addStaticColumn("stat", DataType.text()).getQueryString();
547545 }
548546
549547 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
550- expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword")
548+ expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword")
551549 public void should_fail_if_keyspace_name_is_a_reserved_keyword() throws Exception {
552550 createTable("add", "test")
553- .addPartitionKey("pk", DataType.bigint())
554- .addColumn("col", DataType.text()).getQueryString();
551+ .addPartitionKey("pk", DataType.bigint())
552+ .addColumn("col", DataType.text()).getQueryString();
555553 }
556554
557555 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
558- expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword")
556+ expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword")
559557 public void should_fail_if_table_name_is_a_reserved_keyword() throws Exception {
560558 createTable("add")
561- .addPartitionKey("pk", DataType.bigint())
562- .addColumn("col", DataType.text()).getQueryString();
559+ .addPartitionKey("pk", DataType.bigint())
560+ .addColumn("col", DataType.text()).getQueryString();
563561 }
564562
565563 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
566- expectedExceptionsMessageRegExp = "The partition key name 'add' is not allowed because it is a reserved keyword")
564+ expectedExceptionsMessageRegExp = "The partition key name 'add' is not allowed because it is a reserved keyword")
567565 public void should_fail_if_partition_key_is_a_reserved_keyword() throws Exception {
568566 createTable("test")
569- .addPartitionKey("add", DataType.bigint())
570- .addColumn("col", DataType.text()).getQueryString();
567+ .addPartitionKey("add", DataType.bigint())
568+ .addColumn("col", DataType.text()).getQueryString();
571569 }
572570
573571 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
574- expectedExceptionsMessageRegExp = "The clustering column name 'add' is not allowed because it is a reserved keyword")
572+ expectedExceptionsMessageRegExp = "The clustering column name 'add' is not allowed because it is a reserved keyword")
575573 public void should_fail_if_clustering_key_is_a_reserved_keyword() throws Exception {
576574 createTable("test")
577- .addPartitionKey("pk", DataType.bigint())
578- .addClusteringColumn("add", DataType.uuid())
579- .addColumn("col", DataType.text()).getQueryString();
575+ .addPartitionKey("pk", DataType.bigint())
576+ .addClusteringColumn("add", DataType.uuid())
577+ .addColumn("col", DataType.text()).getQueryString();
580578 }
581579
582580 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
583- expectedExceptionsMessageRegExp = "The column name 'add' is not allowed because it is a reserved keyword")
581+ expectedExceptionsMessageRegExp = "The column name 'add' is not allowed because it is a reserved keyword")
584582 public void should_fail_if_simple_column_is_a_reserved_keyword() throws Exception {
585583 createTable("test")
586- .addPartitionKey("pk", DataType.bigint())
587- .addClusteringColumn("cluster", DataType.uuid())
588- .addColumn("add", DataType.text()).getQueryString();
584+ .addPartitionKey("pk", DataType.bigint())
585+ .addClusteringColumn("cluster", DataType.uuid())
586+ .addColumn("add", DataType.text()).getQueryString();
589587 }
590588
591589 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
592- expectedExceptionsMessageRegExp = "The static column name 'add' is not allowed because it is a reserved keyword")
590+ expectedExceptionsMessageRegExp = "The static column name 'add' is not allowed because it is a reserved keyword")
593591 public void should_fail_if_static_column_is_a_reserved_keyword() throws Exception {
594592 createTable("test")
595- .addPartitionKey("pk", DataType.bigint())
596- .addClusteringColumn("cluster", DataType.uuid())
597- .addStaticColumn("add", DataType.text())
598- .addColumn("col", DataType.text()).getQueryString();
593+ .addPartitionKey("pk", DataType.bigint())
594+ .addClusteringColumn("cluster", DataType.uuid())
595+ .addStaticColumn("add", DataType.text())
596+ .addColumn("col", DataType.text()).getQueryString();
599597 }
600598
601599 @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
602- expectedExceptionsMessageRegExp = "Cannot create table 'test' with compact storage and static columns '\\[stat\\]'")
600+ expectedExceptionsMessageRegExp = "Cannot create table 'test' with compact storage and static columns '\\[stat\\]'")
603601 public void should_fail_creating_table_with_static_columns_and_compact_storage() throws Exception {
604602 createTable("test")
605- .addPartitionKey("pk", DataType.bigint())
606- .addClusteringColumn("cluster", DataType.uuid())
607- .addStaticColumn("stat", DataType.text())
608- .withOptions().compactStorage().getQueryString();
603+ .addPartitionKey("pk", DataType.bigint())
604+ .addClusteringColumn("cluster", DataType.uuid())
605+ .addStaticColumn("stat", DataType.text())
606+ .withOptions().compactStorage().getQueryString();
609607 }
610608 }
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTypeTest.java +39 −43
@@ -15,133 +15,129 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18+import com.datastax.driver.core.DataType;
1819 import org.testng.annotations.Test;
1920
21+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*;
2022 import static org.assertj.core.api.Assertions.assertThat;
2123
22-import com.datastax.driver.core.DataType;
23-
24-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.createType;
25-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.frozen;
26-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.udtLiteral;
27-
2824 public class CreateTypeTest {
2925
3026 @Test(groups = "unit")
3127 public void should_create_UDT() throws Exception {
3228 //When
3329 SchemaStatement statement = createType("ks", "myType")
34- .addColumn("col1", DataType.text())
35- .addColumn("col2", DataType.bigint());
30+ .addColumn("col1", DataType.text())
31+ .addColumn("col2", DataType.bigint());
3632
3733 //Then
3834 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
39- "col1 text,\n\t\t" +
40- "col2 bigint)");
35+ "col1 text,\n\t\t" +
36+ "col2 bigint)");
4137 }
4238
4339 @Test(groups = "unit")
4440 public void should_create_UDT_if_not_exists() throws Exception {
4541 //When
4642 SchemaStatement statement = createType("myType")
47- .ifNotExists()
48- .addColumn("col1", DataType.text())
49- .addColumn("col2", DataType.bigint());
43+ .ifNotExists()
44+ .addColumn("col1", DataType.text())
45+ .addColumn("col2", DataType.bigint());
5046
5147 //Then
5248 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE IF NOT EXISTS myType(\n\t\t" +
53- "col1 text,\n\t\t" +
54- "col2 bigint)");
49+ "col1 text,\n\t\t" +
50+ "col2 bigint)");
5551 }
5652
5753 @Test(groups = "unit")
5854 public void should_create_simple_UDT_column() throws Exception {
5955 //When
6056 SchemaStatement statement = createType("ks", "myType")
61- .addColumn("col1", DataType.text())
62- .addUDTColumn("my_udt", frozen("address"));
57+ .addColumn("col1", DataType.text())
58+ .addUDTColumn("my_udt", frozen("address"));
6359
6460 //Then
6561 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
66- "col1 text,\n\t\t" +
67- "my_udt frozen<address>)");
62+ "col1 text,\n\t\t" +
63+ "my_udt frozen<address>)");
6864 }
6965
7066 @Test(groups = "unit")
7167 public void should_create_list_UDT_column() throws Exception {
7268 //When
7369 SchemaStatement statement = createType("ks", "myType")
74- .addColumn("col1", DataType.text())
75- .addUDTListColumn("my_udt", frozen("address"));
70+ .addColumn("col1", DataType.text())
71+ .addUDTListColumn("my_udt", frozen("address"));
7672
7773 //Then
7874 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
79- "col1 text,\n\t\t" +
80- "my_udt list<frozen<address>>)");
75+ "col1 text,\n\t\t" +
76+ "my_udt list<frozen<address>>)");
8177 }
8278
8379 @Test(groups = "unit")
8480 public void should_create_set_UDT_column() throws Exception {
8581 //When
8682 SchemaStatement statement = createType("ks", "myType")
87- .addColumn("col1", DataType.text())
88- .addUDTSetColumn("my_udt", frozen("address"));
83+ .addColumn("col1", DataType.text())
84+ .addUDTSetColumn("my_udt", frozen("address"));
8985
9086 //Then
9187 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
92- "col1 text,\n\t\t" +
93- "my_udt set<frozen<address>>)");
88+ "col1 text,\n\t\t" +
89+ "my_udt set<frozen<address>>)");
9490 }
9591
9692 @Test(groups = "unit")
9793 public void should_create_key_UDT_map_column() throws Exception {
9894 //When
9995 SchemaStatement statement = createType("ks", "myType")
100- .addColumn("col1", DataType.text())
101- .addUDTMapColumn("my_udt", frozen("address"), DataType.text());
96+ .addColumn("col1", DataType.text())
97+ .addUDTMapColumn("my_udt", frozen("address"), DataType.text());
10298
10399 //Then
104100 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
105- "col1 text,\n\t\t" +
106- "my_udt map<frozen<address>, text>)");
101+ "col1 text,\n\t\t" +
102+ "my_udt map<frozen<address>, text>)");
107103 }
108104
109105 @Test(groups = "unit")
110106 public void should_create_value_UDT_map_column() throws Exception {
111107 //When
112108 SchemaStatement statement = createType("ks", "myType")
113- .addColumn("col1", DataType.text())
114- .addUDTMapColumn("my_udt", DataType.cint(), frozen("address"));
109+ .addColumn("col1", DataType.text())
110+ .addUDTMapColumn("my_udt", DataType.cint(), frozen("address"));
115111
116112 //Then
117113 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
118- "col1 text,\n\t\t" +
119- "my_udt map<int, frozen<address>>)");
114+ "col1 text,\n\t\t" +
115+ "my_udt map<int, frozen<address>>)");
120116 }
121117
122118 @Test(groups = "unit")
123119 public void should_create_key_value_UDT_map_column() throws Exception {
124120 //When
125121 SchemaStatement statement = createType("ks", "myType")
126- .addColumn("col1", DataType.text())
127- .addUDTMapColumn("my_udt", frozen("coords"), frozen("address"));
122+ .addColumn("col1", DataType.text())
123+ .addUDTMapColumn("my_udt", frozen("coords"), frozen("address"));
128124
129125 //Then
130126 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
131- "col1 text,\n\t\t" +
132- "my_udt map<frozen<coords>, frozen<address>>)");
127+ "col1 text,\n\t\t" +
128+ "my_udt map<frozen<coords>, frozen<address>>)");
133129 }
134130
135131 @Test(groups = "unit")
136132 public void should_create_column_with_manual_type() throws Exception {
137133 //When
138134 SchemaStatement statement = createType("ks", "myType")
139- .addColumn("col1", DataType.text())
140- .addUDTColumn("my_udt", udtLiteral("frozen<address>"));
135+ .addColumn("col1", DataType.text())
136+ .addUDTColumn("my_udt", udtLiteral("frozen<address>"));
141137
142138 //Then
143139 assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
144- "col1 text,\n\t\t" +
145- "my_udt frozen<address>)");
140+ "col1 text,\n\t\t" +
141+ "my_udt frozen<address>)");
146142 }
147143 }
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/DropTest.java +3 −6
@@ -17,12 +17,9 @@
1717
1818 import org.testng.annotations.Test;
1919
20+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*;
2021 import static org.assertj.core.api.Assertions.assertThat;
2122
22-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.dropIndex;
23-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.dropTable;
24-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.dropType;
25-
2623 public class DropTest {
2724
2825 @Test(groups = "unit")
@@ -107,13 +104,13 @@
107104 }
108105
109106 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
110- expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword")
107+ expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword")
111108 public void should_fail_if_keyspace_name_is_a_reserved_keyword() throws Exception {
112109 dropTable("add", "test").getQueryString();
113110 }
114111
115112 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
116- expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword")
113+ expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword")
117114 public void should_fail_if_table_name_is_a_reserved_keyword() throws Exception {
118115 dropTable("add").getQueryString();
119116 }
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/SchemaBuilderIT.java +124 −126
@@ -15,25 +15,23 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.DataType;
20+import com.datastax.driver.core.ResultSet;
21+import com.datastax.driver.core.Row;
22+import com.datastax.driver.core.schemabuilder.TableOptions.CompactionOptions.DateTieredCompactionStrategyOptions.TimeStampResolution;
23+import com.datastax.driver.core.utils.CassandraVersion;
24+import org.testng.annotations.Test;
25+
1826 import java.util.ArrayList;
1927 import java.util.Collection;
2028 import java.util.Iterator;
2129
22-import org.testng.annotations.Test;
23-
30+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*;
2431 import static org.assertj.core.api.Assertions.assertThat;
2532 import static org.assertj.core.api.Assertions.fail;
2633
27-import com.datastax.driver.core.*;
28-import com.datastax.driver.core.schemabuilder.TableOptions.CompactionOptions.DateTieredCompactionStrategyOptions.TimeStampResolution;
29-import com.datastax.driver.core.utils.CassandraVersion;
30-
31-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.dateTieredStrategy;
32-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.percentile;
33-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.rows;
34-import static com.datastax.driver.core.schemabuilder.SchemaBuilder.snappy;
35-
36-public class SchemaBuilderIT extends CCMBridge.PerClassSingleNodeCluster{
34+public class SchemaBuilderIT extends CCMBridge.PerClassSingleNodeCluster {
3735
3836 @Override
3937 protected Collection<String> getTableDefinitions() {
@@ -41,73 +39,73 @@
4139 }
4240
4341 @Test(groups = "short")
44- @CassandraVersion(major=2.1, minor=2)
42+ @CassandraVersion(major = 2.1, minor = 2)
4543 public void should_modify_table_metadata() {
4644 // Create a table
4745 session.execute(SchemaBuilder.createTable("ks", "TableMetadata")
48- .addPartitionKey("a", DataType.cint())
49- .addPartitionKey("b", DataType.cint())
50- .addClusteringColumn("c", DataType.cint())
51- .addClusteringColumn("d", DataType.cint())
52- .withOptions()
53- .compactStorage()
46+ .addPartitionKey("a", DataType.cint())
47+ .addPartitionKey("b", DataType.cint())
48+ .addClusteringColumn("c", DataType.cint())
49+ .addClusteringColumn("d", DataType.cint())
50+ .withOptions()
51+ .compactStorage()
5452 );
5553
5654 // Modify the table metadata
5755 session.execute(SchemaBuilder.alterTable("TableMetadata")
58- .withOptions()
59- .defaultTimeToLive(1337)
60- .bloomFilterFPChance(0.42)
61- .caching(SchemaBuilder.KeyCaching.ALL, rows(1))
62- .gcGraceSeconds(1234567890)
63- .minIndexInterval(6)
64- .indexInterval(7)
65- .maxIndexInterval(8)
66- .comment("Useful comment")
67- .readRepairChance(0.123456)
68- .speculativeRetry(percentile(50))
69- .dcLocalReadRepairChance(0.84)
70- .memtableFlushPeriodInMillis(1234567890)
71- .compactionOptions(dateTieredStrategy()
72- .baseTimeSeconds(1)
73- .minThreshold(2)
74- .maxThreshold(3)
75- .maxSSTableAgeDays(4)
76- .timestampResolution(TimeStampResolution.MILLISECONDS))
77- .compressionOptions(snappy()));
56+ .withOptions()
57+ .defaultTimeToLive(1337)
58+ .bloomFilterFPChance(0.42)
59+ .caching(SchemaBuilder.KeyCaching.ALL, rows(1))
60+ .gcGraceSeconds(1234567890)
61+ .minIndexInterval(6)
62+ .indexInterval(7)
63+ .maxIndexInterval(8)
64+ .comment("Useful comment")
65+ .readRepairChance(0.123456)
66+ .speculativeRetry(percentile(50))
67+ .dcLocalReadRepairChance(0.84)
68+ .memtableFlushPeriodInMillis(1234567890)
69+ .compactionOptions(dateTieredStrategy()
70+ .baseTimeSeconds(1)
71+ .minThreshold(2)
72+ .maxThreshold(3)
73+ .maxSSTableAgeDays(4)
74+ .timestampResolution(TimeStampResolution.MILLISECONDS))
75+ .compressionOptions(snappy()));
7876
7977 // Retrieve the metadata from Cassandra
8078 ResultSet rows = session.execute("SELECT "
81- + "bloom_filter_fp_chance, "
82- + "caching, "
83- + "cf_id, "
84- + "column_aliases, "
85- + "comment, "
86- + "compaction_strategy_class, "
87- + "compaction_strategy_options, "
88- + "comparator, "
89- + "compression_parameters, "
90- + "default_time_to_live, "
91- + "default_validator, "
92- + "dropped_columns, "
93- + "gc_grace_seconds, "
94- + "index_interval, "
95- + "is_dense, "
96- + "key_aliases, "
97- + "key_validator, "
98- + "local_read_repair_chance, "
99- + "max_compaction_threshold, "
100- + "max_index_interval, "
101- + "memtable_flush_period_in_ms, "
102- + "min_compaction_threshold, "
103- + "min_index_interval, "
104- + "read_repair_chance, "
105- + "speculative_retry, "
106- + "subcomparator, "
107- + "type, "
108- + "value_alias "
109- + "FROM system.schema_columnfamilies "
110- + "WHERE keyspace_name='ks' AND columnfamily_name='tablemetadata'");
79+ + "bloom_filter_fp_chance, "
80+ + "caching, "
81+ + "cf_id, "
82+ + "column_aliases, "
83+ + "comment, "
84+ + "compaction_strategy_class, "
85+ + "compaction_strategy_options, "
86+ + "comparator, "
87+ + "compression_parameters, "
88+ + "default_time_to_live, "
89+ + "default_validator, "
90+ + "dropped_columns, "
91+ + "gc_grace_seconds, "
92+ + "index_interval, "
93+ + "is_dense, "
94+ + "key_aliases, "
95+ + "key_validator, "
96+ + "local_read_repair_chance, "
97+ + "max_compaction_threshold, "
98+ + "max_index_interval, "
99+ + "memtable_flush_period_in_ms, "
100+ + "min_compaction_threshold, "
101+ + "min_index_interval, "
102+ + "read_repair_chance, "
103+ + "speculative_retry, "
104+ + "subcomparator, "
105+ + "type, "
106+ + "value_alias "
107+ + "FROM system.schema_columnfamilies "
108+ + "WHERE keyspace_name='ks' AND columnfamily_name='tablemetadata'");
111109 for (Row row : rows) {
112110 // There should be only one row
113111 // Verify that every property we modified is correctly set
@@ -117,11 +115,11 @@
117115 assertThat(row.getString("column_aliases")).isEqualTo("[\"c\",\"d\"]");
118116 assertThat(row.getString("comment")).isEqualTo("Useful comment");
119117 assertThat(row.getString("compaction_strategy_class"))
120- .isEqualTo("org.apache.cassandra.db.compaction.DateTieredCompactionStrategy");
118+ .isEqualTo("org.apache.cassandra.db.compaction.DateTieredCompactionStrategy");
121119 assertThat(row.getString("compaction_strategy_options")).isEqualTo(
122- "{\"base_time_seconds\":\"1\",\"timestamp_resolution\":\"MILLISECONDS\",\"max_sstable_age_days\":\"4\",\"min_threshold\":\"2\",\"max_threshold\":\"3\"}");
120+ "{\"base_time_seconds\":\"1\",\"timestamp_resolution\":\"MILLISECONDS\",\"max_sstable_age_days\":\"4\",\"min_threshold\":\"2\",\"max_threshold\":\"3\"}");
123121 assertThat(row.getString("compression_parameters"))
124- .isEqualTo("{\"sstable_compression\":\"org.apache.cassandra.io.compress.SnappyCompressor\"}");
122+ .isEqualTo("{\"sstable_compression\":\"org.apache.cassandra.io.compress.SnappyCompressor\"}");
125123 assertThat(row.getInt("default_time_to_live")).isEqualTo(1337);
126124 assertThat(row.getInt("gc_grace_seconds")).isEqualTo(1234567890);
127125 assertThat(row.getInt("min_index_interval")).isEqualTo(6);
@@ -137,34 +135,34 @@
137135 }
138136
139137 @Test(groups = "short")
140- @CassandraVersion(major=2.1)
138+ @CassandraVersion(major = 2.1)
141139 public void should_create_a_table_and_a_udt() {
142140 // Create a UDT and a table
143141 session.execute(SchemaBuilder.createType("MyUDT")
144- .ifNotExists()
145- .addColumn("x", DataType.cint())
142+ .ifNotExists()
143+ .addColumn("x", DataType.cint())
146144 );
147145 UDTType myUDT = UDTType.frozen("MyUDT");
148146 session.execute(SchemaBuilder.createTable("ks", "CreateTable")
149- .ifNotExists()
150- .addPartitionKey("a", DataType.cint())
151- .addUDTPartitionKey("b", myUDT)
152- .addClusteringColumn("c", DataType.ascii())
153- .addUDTClusteringColumn("d", myUDT)
154- .addUDTColumn("e", myUDT)
155- .addStaticColumn("f", DataType.bigint())
156- .addUDTStaticColumn("g", myUDT)
157- .addUDTListColumn("h", myUDT)
158- .addUDTMapColumn("i", DataType.cboolean(), myUDT)
159- .addUDTMapColumn("j", myUDT, DataType.cboolean())
160- .addUDTSetColumn("k", myUDT)
147+ .ifNotExists()
148+ .addPartitionKey("a", DataType.cint())
149+ .addUDTPartitionKey("b", myUDT)
150+ .addClusteringColumn("c", DataType.ascii())
151+ .addUDTClusteringColumn("d", myUDT)
152+ .addUDTColumn("e", myUDT)
153+ .addStaticColumn("f", DataType.bigint())
154+ .addUDTStaticColumn("g", myUDT)
155+ .addUDTListColumn("h", myUDT)
156+ .addUDTMapColumn("i", DataType.cboolean(), myUDT)
157+ .addUDTMapColumn("j", myUDT, DataType.cboolean())
158+ .addUDTSetColumn("k", myUDT)
161159 );
162160
163161 // Check columns a to k
164162 ResultSet rows = session.execute(
165- "SELECT column_name, type, validator "
166- + "FROM system.schema_columns "
167- + "WHERE keyspace_name='ks' AND columnfamily_name='createtable'");
163+ "SELECT column_name, type, validator "
164+ + "FROM system.schema_columns "
165+ + "WHERE keyspace_name='ks' AND columnfamily_name='createtable'");
168166 Iterator<Row> iterator = rows.iterator();
169167 verifyNextColumnDefinition(iterator, "a", "partition_key", "org.apache.cassandra.db.marshal.Int32Type");
170168 verifyNextColumnDefinition(iterator, "b", "partition_key", "org.apache.cassandra.db.marshal.UserType");
@@ -174,37 +172,37 @@
174172 verifyNextColumnDefinition(iterator, "f", "static", "org.apache.cassandra.db.marshal.LongType");
175173 verifyNextColumnDefinition(iterator, "g", "static", "org.apache.cassandra.db.marshal.UserType");
176174 verifyNextColumnDefinition(iterator, "h", "regular", "org.apache.cassandra.db.marshal.ListType"
177- , "org.apache.cassandra.db.marshal.UserType");
175+ , "org.apache.cassandra.db.marshal.UserType");
178176 verifyNextColumnDefinition(iterator, "i", "regular", "org.apache.cassandra.db.marshal.MapType"
179- , "org.apache.cassandra.db.marshal.BooleanType", "org.apache.cassandra.db.marshal.UserType");
177+ , "org.apache.cassandra.db.marshal.BooleanType", "org.apache.cassandra.db.marshal.UserType");
180178 verifyNextColumnDefinition(iterator, "j", "regular", "org.apache.cassandra.db.marshal.MapType"
181- , "org.apache.cassandra.db.marshal.UserType", "org.apache.cassandra.db.marshal.BooleanType");
179+ , "org.apache.cassandra.db.marshal.UserType", "org.apache.cassandra.db.marshal.BooleanType");
182180 verifyNextColumnDefinition(iterator, "k", "regular", "org.apache.cassandra.db.marshal.SetType"
183- , "org.apache.cassandra.db.marshal.UserType");
181+ , "org.apache.cassandra.db.marshal.UserType");
184182 }
185183
186184 @Test(groups = "short")
187185 public void should_add_and_drop_a_column() {
188186 // Create a table, add a column to it with an alter table statement and delete that column
189187 session.execute(SchemaBuilder.createTable("ks", "DropColumn")
190- .ifNotExists()
191- .addPartitionKey("a", DataType.cint())
188+ .ifNotExists()
189+ .addPartitionKey("a", DataType.cint())
192190 );
193191
194192 // Add and then drop a column
195193 session.execute(SchemaBuilder.alterTable("ks", "DropColumn")
196- .addColumn("b")
197- .type(DataType.cint())
194+ .addColumn("b")
195+ .type(DataType.cint())
198196 );
199197 session.execute(SchemaBuilder.alterTable("ks", "DropColumn")
200- .dropColumn("b")
198+ .dropColumn("b")
201199 );
202200
203201 // Check that only column a exist
204202 ResultSet rows = session.execute(
205- "SELECT column_name, type, validator "
206- + "FROM system.schema_columns "
207- + "WHERE keyspace_name='ks' AND columnfamily_name='dropcolumn'");
203+ "SELECT column_name, type, validator "
204+ + "FROM system.schema_columns "
205+ + "WHERE keyspace_name='ks' AND columnfamily_name='dropcolumn'");
208206 Iterator<Row> iterator = rows.iterator();
209207 verifyNextColumnDefinition(iterator, "a", "partition_key", "org.apache.cassandra.db.marshal.Int32Type");
210208 assertThat(iterator.hasNext()).isFalse();
@@ -224,7 +222,7 @@
224222 public void should_drop_a_table() {
225223 // Create a table
226224 session.execute(SchemaBuilder.createTable("ks", "DropTable")
227- .addPartitionKey("a", DataType.cint())
225+ .addPartitionKey("a", DataType.cint())
228226 );
229227
230228 // Drop the table
@@ -232,9 +230,9 @@
232230 session.execute(SchemaBuilder.dropTable("DropTable").ifExists());
233231
234232 ResultSet rows = session.execute(
235- "SELECT columnfamily_name "
236- + "FROM system.schema_columnfamilies "
237- + "WHERE keyspace_name='ks' AND columnfamily_name='droptable'");
233+ "SELECT columnfamily_name "
234+ + "FROM system.schema_columnfamilies "
235+ + "WHERE keyspace_name='ks' AND columnfamily_name='droptable'");
238236 if (rows.iterator().hasNext()) {
239237 fail("This table should have been deleted");
240238 }
@@ -244,28 +242,28 @@
244242 public void should_create_an_index() {
245243 // Create a table
246244 session.execute(SchemaBuilder.createTable("ks", "CreateIndex")
247- .addPartitionKey("a", DataType.cint())
248- .addClusteringColumn("b", DataType.cint())
249- .addColumn("c", DataType.map(DataType.cint(), DataType.cint()))
245+ .addPartitionKey("a", DataType.cint())
246+ .addClusteringColumn("b", DataType.cint())
247+ .addColumn("c", DataType.map(DataType.cint(), DataType.cint()))
250248 );
251249
252250 // Create an index on a regular column of the table
253251 session.execute(SchemaBuilder.createIndex("ks_Index")
254- .onTable("ks", "CreateIndex")
255- .andColumn("b")
252+ .onTable("ks", "CreateIndex")
253+ .andColumn("b")
256254 );
257255 session.execute(SchemaBuilder.createIndex("ks_IndexOnMap")
258- .onTable("ks", "CreateIndex")
259- .andKeysOfColumn("c")
256+ .onTable("ks", "CreateIndex")
257+ .andKeysOfColumn("c")
260258 );
261259
262260 // Verify that the indexes exist on the right columns
263261 ResultSet rows = session.execute(
264- "SELECT column_name, index_name, index_options, index_type, component_index "
265- + "FROM system.schema_columns "
266- + "WHERE keyspace_name='ks' "
267- + "AND columnfamily_name='createindex' "
268- + "AND column_name IN ('b', 'c')");
262+ "SELECT column_name, index_name, index_options, index_type, component_index "
263+ + "FROM system.schema_columns "
264+ + "WHERE keyspace_name='ks' "
265+ + "AND columnfamily_name='createindex' "
266+ + "AND column_name IN ('b', 'c')");
269267 Iterator<Row> iterator = rows.iterator();
270268 verifyNextIndexDefinition(iterator, "ks_Index", "{}", "COMPOSITES", 0);
271269 verifyNextIndexDefinition(iterator, "ks_IndexOnMap", "{\"index_keys\":\"\"}", "COMPOSITES", 1);
@@ -285,8 +283,8 @@
285283 public void should_drop_an_index() {
286284 // Create a table
287285 session.execute(SchemaBuilder.createTable("ks", "DropIndex")
288- .addPartitionKey("a", DataType.cint())
289- .addClusteringColumn("b", DataType.cint())
286+ .addPartitionKey("a", DataType.cint())
287+ .addClusteringColumn("b", DataType.cint())
290288 );
291289
292290 // Create an index
@@ -294,8 +292,8 @@
294292 // but a lowercase index name at deletion
295293 // See : https://issues.apache.org/jira/browse/CASSANDRA-8365
296294 session.execute(SchemaBuilder.createIndex("ks_index")
297- .onTable("ks", "DropIndex")
298- .andColumn("b")
295+ .onTable("ks", "DropIndex")
296+ .andColumn("b")
299297 );
300298
301299 // Verify that the PK index and the secondary indexes both exist
@@ -310,10 +308,10 @@
310308
311309 private int numberOfIndexedColumns(String keyspace, String table) {
312310 ResultSet columns = session.execute(
313- "SELECT * "
314- + "FROM system.schema_columns "
315- + "WHERE keyspace_name='ks' "
316- + "AND columnfamily_name='dropindex' ");
311+ "SELECT * "
312+ + "FROM system.schema_columns "
313+ + "WHERE keyspace_name='ks' "
314+ + "AND columnfamily_name='dropindex' ");
317315 int count = 0;
318316 for (Row column : columns) {
319317 if (column.getString("index_name") != null)
modified driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +14 −11
@@ -28,9 +28,10 @@
2828 import org.slf4j.LoggerFactory;
2929
3030 import java.net.InetSocketAddress;
31-import java.net.Socket;
32-import java.net.SocketAddress;
33-import java.util.*;
31+import java.util.Collection;
32+import java.util.Collections;
33+import java.util.Comparator;
34+import java.util.List;
3435 import java.util.concurrent.Executors;
3536 import java.util.concurrent.ScheduledExecutorService;
3637 import java.util.concurrent.TimeUnit;
@@ -70,7 +71,7 @@
7071 public void run() {
7172 try {
7273 report();
73- } catch(Exception e) {
74+ } catch (Exception e) {
7475 logger.error("Error countered.", e);
7576 }
7677 }
@@ -85,7 +86,7 @@
8586
8687 /**
8788 * @return A custom {@link NettyOptions} instance that hooks into afterChannelInitialized added channels may be
88- * monitored.
89+ * monitored.
8990 */
9091 public NettyOptions nettyOptions() {
9192 return nettyOptions;
@@ -100,6 +101,7 @@
100101
101102 /**
102103 * Schedules a {@link #report()} to be called every configured interval.
104+ *
103105 * @param interval how often to report.
104106 * @param timeUnit at what time precision to report at.
105107 */
@@ -115,17 +117,17 @@
115117 }
116118
117119 /**
118- * <p>
120+ * <p/>
119121 * Report for all sockets matching the given predicate. The report format reflects the number of open, closed,
120122 * live and total sockets created. This is logged at DEBUG if enabled.
121- *
122- * <p>
123+ * <p/>
124+ * <p/>
123125 * If TRACE is enabled, each individual socket will be logged as well.
124126 *
125127 * @param channelFilter used to determine which sockets to report on.
126128 */
127129 public void report(Predicate<SocketChannel> channelFilter) {
128- if(logger.isDebugEnabled()) {
130+ if (logger.isDebugEnabled()) {
129131 Iterable<SocketChannel> channels = matchingChannels(channelFilter);
130132 Iterable<SocketChannel> open = Iterables.filter(channels, openChannels);
131133 Iterable<SocketChannel> closed = Iterables.filter(channels, Predicates.not(openChannels));
@@ -137,7 +139,7 @@
137139 Iterables.size(channels),
138140 channelsCreated.get());
139141
140- if(logger.isTraceEnabled()) {
142+ if (logger.isTraceEnabled()) {
141143 logger.trace("Open channels {}.", open);
142144 logger.trace("Closed channels {}.", closed);
143145 }
@@ -149,7 +151,8 @@
149151 public int compare(SocketChannel t0, SocketChannel t1) {
150152 // Should not be null as these are filtered previously in matchingChannels.
151153 assert t0 != null && t0.remoteAddress() != null;
152- assert t1 != null && t1.remoteAddress() != null;;
154+ assert t1 != null && t1.remoteAddress() != null;
155+ ;
153156 return t0.remoteAddress().toString().compareTo(t1.remoteAddress().toString());
154157 }
155158 };
modified driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsTest.java +9 −7
@@ -15,18 +15,20 @@
1515 */
1616 package com.datastax.driver.core.utils;
1717
18+import com.datastax.driver.core.ProtocolVersion;
19+import com.datastax.driver.core.TypeCodec;
20+import org.testng.annotations.Test;
21+
1822 import java.nio.ByteBuffer;
19-import java.util.*;
23+import java.util.HashSet;
24+import java.util.Random;
25+import java.util.Set;
26+import java.util.UUID;
2027 import java.util.concurrent.ConcurrentSkipListSet;
2128
22-import org.testng.annotations.Test;
23-
2429 import static org.testng.Assert.assertEquals;
2530 import static org.testng.Assert.assertTrue;
2631
27-import com.datastax.driver.core.ProtocolVersion;
28-import com.datastax.driver.core.TypeCodec;
29-
3032 public class UUIDsTest {
3133
3234 @Test(groups = "unit")
@@ -102,7 +104,7 @@
102104 int nbPerTstamp = 10;
103105
104106 for (int i = 0; i < nbTstamp; i++) {
105- long tstamp = (long)random.nextInt();
107+ long tstamp = (long) random.nextInt();
106108 for (int j = 0; j < nbPerTstamp; j++) {
107109 assertWithin(new UUID(UUIDs.makeMSB(UUIDs.fromUnixTimestamp(tstamp)), random.nextLong()), UUIDs.startOf(tstamp), UUIDs.endOf(tstamp));
108110 }
modified driver-dse/src/main/java/com/datastax/driver/auth/DseAuthProvider.java +15 −18
@@ -22,27 +22,27 @@
2222 import java.net.InetSocketAddress;
2323
2424 /**
25- * AuthProvider which supplies authenticator instances for clients to connect t
26- * DSE clusters secured with Kerberos
27- *
25+ * AuthProvider which supplies authenticator instances for clients to connect t
26+ * DSE clusters secured with Kerberos
27+ * <p/>
2828 * The SASL protocol name defaults to "dse"; should you need to change that
2929 * it can be overridden using the <code>dse.sasl.protocol</code> system property.
30- * <p>
30+ * <p/>
3131 * Keytab and ticket cache settings are specified using a standard JAAS
3232 * configuration file. The location of the file can be set using the
3333 * <code>java.security.auth.login.config</code> system property or by adding a
3434 * <code>login.config.url.n</code> entry in the <code>java.security</code> properties
3535 * file.
36- * <p>
37- * See the following documents for further details on the
36+ * <p/>
37+ * See the following documents for further details on the
3838 * <a href="https://docs.oracle.com/javase/6/docs/technotes/guides/security/jgss/tutorials/LoginConfigFile.html">JAAS Login Configuration File</a> and the
3939 * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jaas/tutorials/GeneralAcnOnly.html">JAAS Authentication Tutorial</a>
4040 * for more on JAAS in general.
41- *
41+ * <p/>
4242 * <h1>Authentication using ticket cache</h1>
4343 * Run <code>kinit</code> to obtain a ticket and populate the cache before
4444 * connecting. JAAS config:
45-
45+ * <p/>
4646 * <pre>
4747 * DseClient {
4848 * com.sun.security.auth.module.Krb5LoginModule required
@@ -50,13 +50,13 @@
5050 * renewTGT=true;
5151 * };
5252 * </pre>
53- *
54- *
53+ * <p/>
54+ * <p/>
5555 * <h1>Authentication using a keytab file</h1>
5656 * To enable authentication using a keytab file, specify its location on disk.
5757 * If your keytab contains more than one principal key, you should also specify
5858 * which one to select.
59- *
59+ * <p/>
6060 * <pre>
6161 * DseClient {
6262 * com.sun.security.auth.module.Krb5LoginModule required
@@ -65,23 +65,20 @@
6565 * principal="user@MYDOMAIN.COM";
6666 * };
6767 * </pre>
68- *
68+ * <p/>
6969 * To connect to clusters using internal authentication, use the standard method for
7070 * setting credentials. eg:
71- *
71+ * <p/>
7272 * <pre>
7373 * Cluster cluster = Cluster.builder()
7474 * .addContactPoint(hostname)
7575 * .withCredentials("username", "password")
7676 * .build();
7777 * </pre>
78- *
7978 */
80-public class DseAuthProvider implements AuthProvider
81-{
79+public class DseAuthProvider implements AuthProvider {
8280 @Override
83- public Authenticator newAuthenticator(InetSocketAddress host, String authenticator) throws AuthenticationException
84- {
81+ public Authenticator newAuthenticator(InetSocketAddress host, String authenticator) throws AuthenticationException {
8582 return new KerberosAuthenticator(host);
8683 }
8784 }
modified driver-dse/src/main/java/com/datastax/driver/auth/KerberosAuthenticator.java +9 −18
@@ -30,8 +30,7 @@
3030 * PrivilegedSaslClient which performs the priviledged actions on behalf
3131 * of the logged in user.
3232 */
33-public class KerberosAuthenticator implements Authenticator
34-{
33+public class KerberosAuthenticator implements Authenticator {
3534 private static final Logger logger = LoggerFactory.getLogger(KerberosAuthenticator.class);
3635
3736 public static final String JAAS_CONFIG_ENTRY = "DseClient";
@@ -41,8 +40,7 @@
4140
4241 private final PrivilegedSaslClient saslClient;
4342
44- public KerberosAuthenticator(InetSocketAddress host)
45- {
43+ public KerberosAuthenticator(InetSocketAddress host) {
4644 saslClient = new PrivilegedSaslClient(loginSubject(),
4745 SUPPORTED_MECHANISMS,
4846 null,
@@ -52,32 +50,26 @@
5250 null);
5351 }
5452
55- private Subject loginSubject()
56- {
53+ private Subject loginSubject() {
5754 Subject subject = new Subject();
58- try
59- {
55+ try {
6056 LoginContext login = new LoginContext(JAAS_CONFIG_ENTRY, subject);
6157 login.login();
6258 return subject;
63- } catch (LoginException e)
64- {
59+ } catch (LoginException e) {
6560 throw new RuntimeException(e);
6661 }
6762 }
6863
6964 @Override
70- public byte[] initialResponse()
71- {
65+ public byte[] initialResponse() {
7266 return saslClient.getInitialResponse();
7367 }
7468
7569 @Override
76- public byte[] evaluateChallenge(byte[] challenge)
77- {
70+ public byte[] evaluateChallenge(byte[] challenge) {
7871 byte[] response = saslClient.evaluateChallenge(challenge);
79- if (response == null)
80- {
72+ if (response == null) {
8173 // If we generate a null response, then authentication has completed (if
8274 // not, warn), and return without sending a response back to the server.
8375 logger.trace("Response to server is null: authentication should now be complete.");
@@ -91,8 +83,7 @@
9183 }
9284
9385 @Override
94- public void onAuthenticationSuccess(byte[] token)
95- {
86+ public void onAuthenticationSuccess(byte[] token) {
9687 // no-op
9788 }
9889 }
modified driver-dse/src/main/java/com/datastax/driver/auth/PrivilegedSaslClient.java +25 −43
@@ -32,14 +32,12 @@
3232 * the authentication protocol as {@code PrivilegedAction}s with the
3333 * assumed identity of the {@code Subject} supplied in the constructor.
3434 */
35-public class PrivilegedSaslClient
36-{
35+public class PrivilegedSaslClient {
3736 private static final Logger logger = LoggerFactory.getLogger(PrivilegedSaslClient.class);
3837
39- public static final Map<String, String> DEFAULT_PROPERTIES = new HashMap<String, String>()
40- {{
41- put(Sasl.SERVER_AUTH, "true");
42- put(Sasl.QOP, "auth");
38+ public static final Map<String, String> DEFAULT_PROPERTIES = new HashMap<String, String>() {{
39+ put(Sasl.SERVER_AUTH, "true");
40+ put(Sasl.QOP, "auth");
4341 }};
4442 private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
4543
@@ -60,17 +58,13 @@
6058 final String protocol,
6159 final String hostname,
6260 final Map<String, String> properties,
63- final CallbackHandler callbackHandler)
64- {
61+ final CallbackHandler callbackHandler) {
6562 logger.trace("Initalising SASL client");
6663 this.clientIdentity = clientIdentity;
67- saslClient = Subject.doAs(this.clientIdentity, new PrivilegedAction<SaslClient>()
68- {
64+ saslClient = Subject.doAs(this.clientIdentity, new PrivilegedAction<SaslClient>() {
6965 @Override
70- public javax.security.sasl.SaslClient run()
71- {
72- try
73- {
66+ public javax.security.sasl.SaslClient run() {
67+ try {
7468 return Sasl.createSaslClient(
7569 mechanisms,
7670 authzId,
@@ -78,8 +72,7 @@
7872 hostname,
7973 properties,
8074 callbackHandler);
81- } catch (Exception e)
82- {
75+ } catch (Exception e) {
8376 logger.error("Error initialising SASL client", e);
8477 throw new RuntimeException(e);
8578 }
@@ -91,24 +84,19 @@
9184
9285 /**
9386 * Generate an initial token to start the SASL handshake with server.
87+ *
9488 * @return SaslTokenRequestMessage message to be sent to server.
9589 */
96- public byte[] getInitialResponse()
97- {
90+ public byte[] getInitialResponse() {
9891 logger.trace("Initialising SASL handshake from client");
9992 byte[] initialResponse = null;
100- if (saslClient.hasInitialResponse())
101- {
102- initialResponse = Subject.doAs(clientIdentity, new PrivilegedAction<byte[]>()
103- {
93+ if (saslClient.hasInitialResponse()) {
94+ initialResponse = Subject.doAs(clientIdentity, new PrivilegedAction<byte[]>() {
10495 @Override
105- public byte[] run()
106- {
107- try
108- {
96+ public byte[] run() {
97+ try {
10998 return saslClient.evaluateChallenge(EMPTY_BYTE_ARRAY);
110- } catch (Exception e)
111- {
99+ } catch (Exception e) {
112100 throw new RuntimeException(e);
113101 }
114102 }
@@ -119,30 +107,24 @@
119107
120108 /**
121109 * Respond to server's SASL token
110+ *
122111 * @param challenge contains server's SASL token
123112 * @return client's response SASL token, which will be null if authentication is complete
124113 */
125- public byte[] evaluateChallenge(final byte[] challenge)
126- {
114+ public byte[] evaluateChallenge(final byte[] challenge) {
127115 logger.trace("Evaluating SASL server token");
128- if (saslClient.isComplete())
129- {
116+ if (saslClient.isComplete()) {
130117 return null;
131118 }
132- byte[] retval = Subject.doAs(clientIdentity, new PrivilegedAction<byte[]>()
133- {
119+ byte[] retval = Subject.doAs(clientIdentity, new PrivilegedAction<byte[]>() {
134120 @Override
135- public byte[] run()
136- {
137- try
138- {
121+ public byte[] run() {
122+ try {
139123 logger.trace("SASL client evaluating challenge");
140124 byte[] retval = saslClient.evaluateChallenge(challenge);
141125 logger.trace("SASL client is complete = " + saslClient.isComplete());
142126 return retval;
143- }
144- catch (SaslException e)
145- {
127+ } catch (SaslException e) {
146128 logger.error("Failed to generate response to SASL server's token:", e);
147129 throw new RuntimeException(e);
148130 }
@@ -153,10 +135,10 @@
153135
154136 /**
155137 * Is the SASL negotiation with the server complete
138+ *
156139 * @return true iff SASL authentication has successfully completed
157140 */
158- public boolean isComplete()
159- {
141+ public boolean isComplete() {
160142 return saslClient.isComplete();
161143 }
162144 }
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java +7 −6
@@ -46,13 +46,14 @@
4646 return body;
4747 }
4848
49- @Override public boolean equals(Object that) {
50- if(that instanceof MailboxMessage) {
51- MailboxMessage thatM = (MailboxMessage)that;
49+ @Override
50+ public boolean equals(Object that) {
51+ if (that instanceof MailboxMessage) {
52+ MailboxMessage thatM = (MailboxMessage) that;
5253 return recipient.equals(thatM.getRecipient()) &&
53- date.equals(thatM.getDate()) &&
54- sender.equals(thatM.getSender()) &&
55- body.equals(thatM.getBody());
54+ date.equals(thatM.getDate()) &&
55+ sender.equals(thatM.getSender()) &&
56+ body.equals(thatM.getBody());
5657 } else {
5758 return false;
5859 }
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxService.java +3 −0
@@ -22,6 +22,7 @@
2222
2323 /**
2424 * Retrieve all messages for a given recipient.
25+ *
2526 * @param recipient User whose mailbox is being read.
2627 * @return All messages in the mailbox.
2728 */
@@ -29,6 +30,7 @@
2930
3031 /**
3132 * Stores the given message in the appropriate mailbox.
33+ *
3234 * @param message Message to send.
3335 * @return UUID generated for the message.
3436 */
@@ -36,6 +38,7 @@
3638
3739 /**
3840 * Deletes all mail for the given recipient.
41+ *
3942 * @param recipient User whose mailbox will be cleared.
4043 */
4144 public void clearMailbox(String recipient) throws MailboxException;
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/Activator.java +11 −10
@@ -15,28 +15,28 @@
1515 */
1616 package com.datastax.driver.osgi.impl;
1717
18-import java.util.Hashtable;
19-
20-import org.osgi.framework.BundleActivator;
21-import org.osgi.framework.BundleContext;
22-
2318 import com.datastax.driver.core.Cluster;
2419 import com.datastax.driver.core.Session;
2520 import com.datastax.driver.osgi.api.MailboxService;
21+import org.osgi.framework.BundleActivator;
22+import org.osgi.framework.BundleContext;
23+
24+import java.util.Hashtable;
2625
2726 public class Activator implements BundleActivator {
2827
2928 private Cluster cluster;
3029
31- @Override public void start(BundleContext context) throws Exception {
30+ @Override
31+ public void start(BundleContext context) throws Exception {
3232 String contactPointsStr = context.getProperty("cassandra.contactpoints");
33- if(contactPointsStr == null) {
33+ if (contactPointsStr == null) {
3434 contactPointsStr = "127.0.0.1";
3535 }
3636 String[] contactPoints = contactPointsStr.split(",");
3737
3838 String keyspace = context.getProperty("cassandra.keyspace");
39- if(keyspace == null) {
39+ if (keyspace == null) {
4040 keyspace = "mailbox";
4141 }
4242
@@ -49,8 +49,9 @@
4949 context.registerService(MailboxService.class.getName(), mailbox, new Hashtable<String, String>());
5050 }
5151
52- @Override public void stop(BundleContext context) throws Exception {
53- if(cluster != null) {
52+ @Override
53+ public void stop(BundleContext context) throws Exception {
54+ if (cluster != null) {
5455 cluster.close();
5556 }
5657 }
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java +32 −29
@@ -15,11 +15,6 @@
1515 */
1616 package com.datastax.driver.osgi.impl;
1717
18-import java.util.ArrayList;
19-import java.util.Collection;
20-import java.util.Date;
21-import java.util.UUID;
22-
2318 import com.datastax.driver.core.*;
2419 import com.datastax.driver.core.exceptions.InvalidQueryException;
2520 import com.datastax.driver.core.utils.UUIDs;
@@ -27,6 +22,11 @@
2722 import com.datastax.driver.osgi.api.MailboxMessage;
2823 import com.datastax.driver.osgi.api.MailboxService;
2924
25+import java.util.ArrayList;
26+import java.util.Collection;
27+import java.util.Date;
28+import java.util.UUID;
29+
3030 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3131
3232 public class MailboxImpl implements MailboxService {
@@ -51,7 +51,7 @@
5151 }
5252
5353 public synchronized void init() {
54- if(initialized)
54+ if (initialized)
5555 return;
5656
5757 // Create the schema if it does not exist.
@@ -59,53 +59,55 @@
5959 session.execute("USE " + keyspace);
6060 } catch (InvalidQueryException e) {
6161 session.execute("CREATE KEYSPACE " + keyspace +
62- " with replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}");
62+ " with replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}");
6363
6464 session.execute("CREATE TABLE " + keyspace + "." + TABLE + " (" +
65- "recipient text," +
66- "time timeuuid," +
67- "sender text," +
68- "body text," +
69- "PRIMARY KEY (recipient, time))");
65+ "recipient text," +
66+ "time timeuuid," +
67+ "sender text," +
68+ "body text," +
69+ "PRIMARY KEY (recipient, time))");
7070 }
7171
7272 retrieveStatement = session.prepare(select()
73- .from(keyspace, TABLE)
74- .where(eq("recipient", bindMarker())));
73+ .from(keyspace, TABLE)
74+ .where(eq("recipient", bindMarker())));
7575
7676 insertStatement = session.prepare(insertInto(keyspace, TABLE)
77- .value("recipient", bindMarker())
78- .value("time", bindMarker())
79- .value("sender", bindMarker())
80- .value("body", bindMarker()));
77+ .value("recipient", bindMarker())
78+ .value("time", bindMarker())
79+ .value("sender", bindMarker())
80+ .value("body", bindMarker()));
8181
8282 deleteStatement = session.prepare(delete().from(keyspace, TABLE)
83- .where(eq("recipient", bindMarker())));
83+ .where(eq("recipient", bindMarker())));
8484
8585 initialized = true;
8686 }
8787
88- @Override public Collection<MailboxMessage> getMessages(String recipient) throws MailboxException {
88+ @Override
89+ public Collection<MailboxMessage> getMessages(String recipient) throws MailboxException {
8990 try {
9091 BoundStatement statement = new BoundStatement(retrieveStatement);
9192 statement.setString(0, recipient);
9293 ResultSet result = session.execute(statement);
9394
9495 Collection<MailboxMessage> messages = new ArrayList<MailboxMessage>();
95- for(Row input : result) {
96+ for (Row input : result) {
9697 Date date = new Date(UUIDs.unixTimestamp(input.getUUID("time")));
9798 messages.add(new MailboxMessage(input.getString("recipient"),
98- date,
99- input.getString("sender"),
100- input.getString("body")));
99+ date,
100+ input.getString("sender"),
101+ input.getString("body")));
101102 }
102103 return messages;
103- } catch(Exception e) {
104+ } catch (Exception e) {
104105 throw new MailboxException(e);
105106 }
106107 }
107108
108- @Override public UUID sendMessage(MailboxMessage message) throws MailboxException {
109+ @Override
110+ public UUID sendMessage(MailboxMessage message) throws MailboxException {
109111 try {
110112 UUID time = UUIDs.startOf(message.getDate().getTime());
111113
@@ -117,17 +119,18 @@
117119
118120 session.execute(statement);
119121 return time;
120- } catch(Exception e) {
122+ } catch (Exception e) {
121123 throw new MailboxException(e);
122124 }
123125 }
124126
125- @Override public void clearMailbox(String recipient) throws MailboxException {
127+ @Override
128+ public void clearMailbox(String recipient) throws MailboxException {
126129 try {
127130 BoundStatement statement = new BoundStatement(deleteStatement);
128131 statement.setString(0, recipient);
129132 session.execute(statement);
130- } catch(Exception e) {
133+ } catch (Exception e) {
131134 throw new MailboxException(e);
132135 }
133136 }
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/BundleOptions.java +23 −28
@@ -15,22 +15,15 @@
1515 */
1616 package com.datastax.driver.osgi;
1717
18+import com.datastax.driver.core.CCMBridge;
1819 import org.ops4j.pax.exam.Option;
1920 import org.ops4j.pax.exam.options.CompositeOption;
2021 import org.ops4j.pax.exam.options.MavenArtifactProvisionOption;
2122 import org.ops4j.pax.exam.options.UrlProvisionOption;
2223 import org.ops4j.pax.exam.util.PathUtils;
2324
24-import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackage;
25-import static org.ops4j.pax.exam.CoreOptions.bundle;
26-import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
27-import static org.ops4j.pax.exam.CoreOptions.options;
28-import static org.ops4j.pax.exam.CoreOptions.systemPackages;
29-import static org.ops4j.pax.exam.CoreOptions.systemProperty;
30-
31-import com.datastax.driver.core.CCMBridge;
32-
3325 import static com.datastax.driver.osgi.VersionProvider.projectVersion;
26+import static org.ops4j.pax.exam.CoreOptions.*;
3427
3528 public class BundleOptions {
3629
@@ -40,7 +33,7 @@
4033
4134 public static UrlProvisionOption driverBundle(boolean useShaded) {
4235 String classifier = useShaded ? "-shaded" : "";
43- return bundle("reference:file:" + PathUtils.getBaseDir() + "/../../driver-core/target/cassandra-driver-core-" + projectVersion() + classifier + ".jar");
36+ return bundle("reference:file:" + PathUtils.getBaseDir() + "/../../driver-core/target/cassandra-driver-core-" + projectVersion() + classifier + ".jar");
4437 }
4538
4639 public static MavenArtifactProvisionOption guavaBundle() {
@@ -51,13 +44,14 @@
5144 final String nettyVersion = "4.0.33.Final";
5245 return new CompositeOption() {
5346
54- @Override public Option[] getOptions() {
47+ @Override
48+ public Option[] getOptions() {
5549 return options(
56- mavenBundle("io.netty", "netty-buffer", nettyVersion),
57- mavenBundle("io.netty", "netty-codec", nettyVersion),
58- mavenBundle("io.netty", "netty-common", nettyVersion),
59- mavenBundle("io.netty", "netty-handler", nettyVersion),
60- mavenBundle("io.netty", "netty-transport", nettyVersion)
50+ mavenBundle("io.netty", "netty-buffer", nettyVersion),
51+ mavenBundle("io.netty", "netty-codec", nettyVersion),
52+ mavenBundle("io.netty", "netty-common", nettyVersion),
53+ mavenBundle("io.netty", "netty-handler", nettyVersion),
54+ mavenBundle("io.netty", "netty-transport", nettyVersion)
6155 );
6256 }
6357 };
@@ -70,19 +64,20 @@
7064 public static CompositeOption defaultOptions() {
7165 return new CompositeOption() {
7266
73- @Override public Option[] getOptions() {
67+ @Override
68+ public Option[] getOptions() {
7469 return options(
75- // Delegate javax.security.cert to the parent classloader. javax.security.cert.X509Certificate is used in
76- // io.netty.util.internal.EmptyArrays, but not directly by the driver.
77- bootDelegationPackage("javax.security.cert"),
78- systemProperty("cassandra.contactpoints").value(CCMBridge.IP_PREFIX + 1),
79- systemProperty("logback.configurationFile").value("file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"),
80- mavenBundle("org.slf4j", "slf4j-api", "1.7.5"),
81- mavenBundle("ch.qos.logback", "logback-classic", "1.1.3"),
82- mavenBundle("ch.qos.logback", "logback-core", "1.1.3"),
83- mavenBundle("io.dropwizard.metrics", "metrics-core", "3.1.2"),
84- systemPackages("org.testng", "org.junit", "org.junit.runner", "org.junit.runner.manipulation",
85- "org.junit.runner.notification", "com.jcabi.manifests")
70+ // Delegate javax.security.cert to the parent classloader. javax.security.cert.X509Certificate is used in
71+ // io.netty.util.internal.EmptyArrays, but not directly by the driver.
72+ bootDelegationPackage("javax.security.cert"),
73+ systemProperty("cassandra.contactpoints").value(CCMBridge.IP_PREFIX + 1),
74+ systemProperty("logback.configurationFile").value("file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"),
75+ mavenBundle("org.slf4j", "slf4j-api", "1.7.5"),
76+ mavenBundle("ch.qos.logback", "logback-classic", "1.1.3"),
77+ mavenBundle("ch.qos.logback", "logback-core", "1.1.3"),
78+ mavenBundle("io.dropwizard.metrics", "metrics-core", "3.1.2"),
79+ systemPackages("org.testng", "org.junit", "org.junit.runner", "org.junit.runner.manipulation",
80+ "org.junit.runner.notification", "com.jcabi.manifests")
8681 );
8782 }
8883 };
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java +22 −11
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.osgi;
1717
18+import com.datastax.driver.core.CCMBridge;
1819 import org.testng.ITestContext;
1920 import org.testng.ITestListener;
2021 import org.testng.ITestResult;
2122
22-import com.datastax.driver.core.CCMBridge;
23-
2423 /**
2524 * A listener that fires up a single node CCM instance on test class start and tears it
2625 * down on test class end.
27- *
26+ * <p/>
2827 * This is needed for tests that use Pax-Exam since it runs some methods in the OSGi container
2928 * which we do not want.
3029 */
@@ -32,23 +31,35 @@
3231
3332 private CCMBridge ccm;
3433
35- @Override public void onStart(ITestContext context) {
34+ @Override
35+ public void onStart(ITestContext context) {
3636 ccm = CCMBridge.builder("test").withNodes(1).build();
3737 }
3838
39- @Override public void onFinish(ITestContext context) {
40- if(ccm != null) {
39+ @Override
40+ public void onFinish(ITestContext context) {
41+ if (ccm != null) {
4142 ccm.remove();
4243 }
4344 }
4445
45- @Override public void onTestStart(ITestResult result) {}
46+ @Override
47+ public void onTestStart(ITestResult result) {
48+ }
4649
47- @Override public void onTestSuccess(ITestResult result) {}
50+ @Override
51+ public void onTestSuccess(ITestResult result) {
52+ }
4853
49- @Override public void onTestFailure(ITestResult result) {}
54+ @Override
55+ public void onTestFailure(ITestResult result) {
56+ }
5057
51- @Override public void onTestSkipped(ITestResult result) {}
58+ @Override
59+ public void onTestSkipped(ITestResult result) {
60+ }
5261
53- @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {}
62+ @Override
63+ public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
64+ }
5465 }
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/GuavaSanityCheckNegativeIT.java +21 −27
@@ -15,54 +15,49 @@
1515 */
1616 package com.datastax.driver.osgi;
1717
18+import com.datastax.driver.core.Cluster;
1819 import org.ops4j.pax.exam.Configuration;
1920 import org.ops4j.pax.exam.Option;
2021 import org.ops4j.pax.exam.testng.listener.PaxExam;
2122 import org.testng.annotations.Listeners;
2223 import org.testng.annotations.Test;
2324
25+import static com.datastax.driver.osgi.BundleOptions.*;
2426 import static org.ops4j.pax.exam.CoreOptions.options;
2527 import static org.testng.Assert.assertTrue;
2628 import static org.testng.Assert.fail;
2729
28-import com.datastax.driver.core.Cluster;
29-
30-import static com.datastax.driver.osgi.BundleOptions.defaultOptions;
31-import static com.datastax.driver.osgi.BundleOptions.driverBundle;
32-import static com.datastax.driver.osgi.BundleOptions.guavaBundle;
33-import static com.datastax.driver.osgi.BundleOptions.nettyBundles;
34-
3530 @Listeners({PaxExam.class})
36-@Test(groups="short")
31+@Test(groups = "short")
3732 public class GuavaSanityCheckNegativeIT {
3833
3934 @Configuration
4035 public Option[] guava14_0_1Config() {
4136 return options(
42- driverBundle(),
43- nettyBundles(),
44- guavaBundle().version("14.0.1"),
45- defaultOptions()
37+ driverBundle(),
38+ nettyBundles(),
39+ guavaBundle().version("14.0.1"),
40+ defaultOptions()
4641 );
4742 }
4843
4944 @Configuration
5045 public Option[] guava15Config() {
5146 return options(
52- driverBundle(),
53- nettyBundles(),
54- guavaBundle().version("15.0"),
55- defaultOptions()
47+ driverBundle(),
48+ nettyBundles(),
49+ guavaBundle().version("15.0"),
50+ defaultOptions()
5651 );
5752 }
5853
5954 @Configuration
6055 public Option[] guava16Config() {
6156 return options(
62- driverBundle(),
63- nettyBundles(),
64- guavaBundle().version("16.0"),
65- defaultOptions()
57+ driverBundle(),
58+ nettyBundles(),
59+ guavaBundle().version("16.0"),
60+ defaultOptions()
6661 );
6762 }
6863
@@ -73,12 +68,12 @@
7368 * is raised as the cause of an {@link ExceptionInInitializerError} since the failure
7469 * occurs at static initialization.
7570 * </p>
76- *
71+ * <p/>
7772 * The following configurations are tried (defined via methods with the @Configuration annotation):
7873 * <ol>
79- * <li>With Guava 14.0.1</li>
80- * <li>With Guava 15.0</li>
81- * <li>With Guava 16.0</li>
74+ * <li>With Guava 14.0.1</li>
75+ * <li>With Guava 15.0</li>
76+ * <li>With Guava 16.0</li>
8277 * </ol>
8378 *
8479 * @test_category packaging
@@ -90,11 +85,10 @@
9085 try {
9186 Cluster.builder();
9287 fail("Expected an IllegalStateException for Guava version incompatibility");
93- }
94- catch(ExceptionInInitializerError e) {
88+ } catch (ExceptionInInitializerError e) {
9589 try {
9690 throw e.getCause();
97- } catch(IllegalStateException ise) {
91+ } catch (IllegalStateException ise) {
9892 assertTrue(ise.getMessage().contains("Detected Guava issue #1635"));
9993 }
10094 }
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceIT.java +37 −38
@@ -15,71 +15,70 @@
1515 */
1616 package com.datastax.driver.osgi;
1717
18-import java.util.ArrayList;
19-import java.util.Collection;
20-import java.util.GregorianCalendar;
21-
22-import javax.inject.Inject;
18+import com.datastax.driver.osgi.api.MailboxException;
19+import com.datastax.driver.osgi.api.MailboxMessage;
20+import com.datastax.driver.osgi.api.MailboxService;
2321 import org.ops4j.pax.exam.Configuration;
2422 import org.ops4j.pax.exam.Option;
2523 import org.ops4j.pax.exam.testng.listener.PaxExam;
2624 import org.testng.annotations.Listeners;
2725 import org.testng.annotations.Test;
2826
29-import static org.ops4j.pax.exam.CoreOptions.options;
30-import static org.testng.Assert.assertEquals;
31-
32-import com.datastax.driver.osgi.api.MailboxException;
33-import com.datastax.driver.osgi.api.MailboxMessage;
34-import com.datastax.driver.osgi.api.MailboxService;
27+import javax.inject.Inject;
28+import java.util.ArrayList;
29+import java.util.Collection;
30+import java.util.GregorianCalendar;
3531
3632 import static com.datastax.driver.osgi.BundleOptions.*;
33+import static org.ops4j.pax.exam.CoreOptions.options;
34+import static org.testng.Assert.assertEquals;
3735
3836 @Listeners({CCMBridgeListener.class, PaxExam.class})
39-@Test(groups="short")
37+@Test(groups = "short")
4038 public class MailboxServiceIT {
41- @Inject MailboxService service;
39+ @Inject
40+ MailboxService service;
4241
4342 @Configuration
4443 public Option[] shadedConfig() {
4544 return options(
46- driverBundle(true),
47- mailboxBundle(),
48- guavaBundle(),
49- defaultOptions()
45+ driverBundle(true),
46+ mailboxBundle(),
47+ guavaBundle(),
48+ defaultOptions()
5049 );
5150 }
5251
5352 @Configuration
5453 public Option[] defaultConfig() {
5554 return options(
56- driverBundle(),
57- mailboxBundle(),
58- guavaBundle(),
59- nettyBundles(),
60- defaultOptions()
55+ driverBundle(),
56+ mailboxBundle(),
57+ guavaBundle(),
58+ nettyBundles(),
59+ defaultOptions()
6160 );
6261 }
6362
6463 @Configuration
6564 public Option[] guava17Config() {
6665 return options(
67- driverBundle(),
68- mailboxBundle(),
69- nettyBundles(),
70- guavaBundle().version("17.0"),
71- defaultOptions()
66+ driverBundle(),
67+ mailboxBundle(),
68+ nettyBundles(),
69+ guavaBundle().version("17.0"),
70+ defaultOptions()
7271 );
7372 }
7473
7574 @Configuration
7675 public Option[] guava18Config() {
7776 return options(
78- driverBundle(),
79- mailboxBundle(),
80- nettyBundles(),
81- guavaBundle().version("18.0"),
82- defaultOptions()
77+ driverBundle(),
78+ mailboxBundle(),
79+ nettyBundles(),
80+ guavaBundle().version("18.0"),
81+ defaultOptions()
8382 );
8483 }
8584
@@ -88,14 +87,14 @@
8887 * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver. Ensures that
8988 * queries can be made through the service with the current given configuration.
9089 * </p>
91- *
90+ * <p/>
9291 * The following configurations are tried (defined via methods with the @Configuration annotation):
9392 * <ol>
94- * <li>Default bundle (Driver with all of it's dependencies)</li>
95- * <li>Shaded bundle (Driver with netty shaded)</li>
96- * <li>With Guava 16.0.1</li>
97- * <li>With Guava 17</li>
98- * <li>With Guava 18</li>
93+ * <li>Default bundle (Driver with all of it's dependencies)</li>
94+ * <li>Shaded bundle (Driver with netty shaded)</li>
95+ * <li>With Guava 16.0.1</li>
96+ * <li>With Guava 17</li>
97+ * <li>With Guava 18</li>
9998 * </ol>
10099 *
101100 * @test_category packaging
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/VersionProvider.java +5 −4
@@ -15,15 +15,15 @@
1515 */
1616 package com.datastax.driver.osgi;
1717
18+import com.jcabi.manifests.Manifests;
19+
1820 import java.util.regex.Matcher;
1921 import java.util.regex.Pattern;
2022
21-import com.jcabi.manifests.Manifests;
22-
2323 /**
2424 * Attempts to resolve the project version from the Bundle manifest. If not present, will throw RuntimeException
2525 * on initialization. If this happens, try building with 'mvn compile' to generate the Bundle manifest.
26- *
26+ * <p/>
2727 * In IntelliJ you can have compile run after make by right clicking on 'compile' in the 'Maven Projects' tool window.
2828 */
2929 public class VersionProvider {
@@ -31,12 +31,13 @@
3131 private static final Pattern versionPattern = Pattern.compile(("(\\d+.\\d+\\.\\d+)(.*)"));
3232
3333 private static final String PROJECT_VERSION;
34+
3435 static {
3536 String bundleName = Manifests.read("Bundle-SymbolicName");
3637 if (bundleName.equals("com.datastax.driver.osgi")) {
3738 String bundleVersion = Manifests.read("Bundle-Version");
3839 Matcher matcher = versionPattern.matcher(bundleVersion);
39- if(matcher.matches()) {
40+ if (matcher.matches()) {
4041 String majorVersion = matcher.group(1);
4142 // Replace all instances of '.' after the main version with '-' to properly
4243 // resolve the correct version.
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/AsynchronousConsumer.java +6 −8
@@ -15,17 +15,15 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.util.Iterator;
19-import java.util.concurrent.CountDownLatch;
20-import java.util.concurrent.ExecutorService;
21-import java.util.concurrent.Executors;
22-
23-import com.google.common.util.concurrent.FutureCallback;
24-import com.google.common.util.concurrent.Futures;
25-
2618 import com.datastax.driver.core.ResultSet;
2719 import com.datastax.driver.core.ResultSetFuture;
2820 import com.datastax.driver.core.Session;
21+import com.google.common.util.concurrent.FutureCallback;
22+import com.google.common.util.concurrent.Futures;
23+
24+import java.util.concurrent.CountDownLatch;
25+import java.util.concurrent.ExecutorService;
26+import java.util.concurrent.Executors;
2927
3028 import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly;
3129
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/BlockingConsumer.java +1 −4
@@ -15,12 +15,9 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.util.Iterator;
19-
20-import com.google.common.util.concurrent.Uninterruptibles;
21-
2218 import com.datastax.driver.core.Session;
2319 import com.datastax.driver.core.exceptions.DriverException;
20+import com.google.common.util.concurrent.Uninterruptibles;
2421
2522 public class BlockingConsumer implements Consumer {
2623
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Consumer.java +1 −0
@@ -18,5 +18,6 @@
1818 public interface Consumer {
1919
2020 public void start();
21+
2122 public void join();
2223 }
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Generators.java +14 −15
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Random;
20-
2118 import com.datastax.driver.core.*;
22-import com.datastax.driver.core.exceptions.*;
19+import com.datastax.driver.core.exceptions.QueryValidationException;
2320 import com.datastax.driver.core.utils.Bytes;
24-
2521 import joptsimple.OptionParser;
2622 import joptsimple.OptionSet;
2723
24+import java.nio.ByteBuffer;
25+import java.util.Random;
26+
2827 public class Generators {
2928 private static ThreadLocal<Random> random = new ThreadLocal<Random>() {
3029 protected Random initialValue() {
@@ -69,7 +68,7 @@
6968
7069 public OptionParser addOptions(OptionParser parser) {
7170 String msg = "Simple insertion of CQL3 rows (using prepared statements unless the --no-prepare option is used). "
72- + "The inserted rows have a fixed set of columns but no clustering columns.";
71+ + "The inserted rows have a fixed set of columns but no clustering columns.";
7372 parser.formatHelpWith(Stress.Help.formatFor(name(), msg));
7473
7574 parser.accepts("no-prepare", "Do no use prepared statement");
@@ -91,7 +90,7 @@
9190
9291 StringBuilder sb = new StringBuilder();
9392 sb.append("CREATE TABLE standard1 (key bigint PRIMARY KEY");
94- for (int i = 0; i < (Integer)options.valueOf("columns-per-row"); ++i)
93+ for (int i = 0; i < (Integer) options.valueOf("columns-per-row"); ++i)
9594 sb.append(", C").append(i).append(" blob");
9695 sb.append(')');
9796
@@ -104,13 +103,13 @@
104103 public QueryGenerator create(int id, int iterations, OptionSet options, Session session) {
105104
106105 return options.has("no-prepare")
107- ? createRegular(id, iterations, options, session)
108- : createPrepared(id, iterations, options, session);
106+ ? createRegular(id, iterations, options, session)
107+ : createPrepared(id, iterations, options, session);
109108 }
110109
111110 public QueryGenerator createRegular(int id, int iterations, OptionSet options, final Session session) {
112- final int valueSize = (Integer)options.valueOf("value-size");
113- final int columnsPerRow = (Integer)options.valueOf("columns-per-row");
111+ final int valueSize = (Integer) options.valueOf("value-size");
112+ final int columnsPerRow = (Integer) options.valueOf("columns-per-row");
114113 final long prefix = (long) id << 32;
115114
116115 return new AbstractGenerator(iterations) {
@@ -130,8 +129,8 @@
130129 }
131130
132131 public QueryGenerator createPrepared(int id, int iterations, OptionSet options, Session session) {
133- final int valueSize = (Integer)options.valueOf("value-size");
134- final int columnsPerRow = (Integer)options.valueOf("columns-per-row");
132+ final int valueSize = (Integer) options.valueOf("value-size");
133+ final int columnsPerRow = (Integer) options.valueOf("columns-per-row");
135134 final long prefix = (long) id << 32;
136135
137136 StringBuilder sb = new StringBuilder();
@@ -184,8 +183,8 @@
184183
185184 public QueryGenerator create(int id, int iterations, OptionSet options, Session session) {
186185 return options.has("no-prepare")
187- ? createRegular(id, iterations, session)
188- : createPrepared(id, iterations, session);
186+ ? createRegular(id, iterations, session)
187+ : createPrepared(id, iterations, session);
189188 }
190189
191190 public QueryGenerator createRegular(long id, int iterations, final Session session) {
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/QueryGenerator.java +5 −3
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.util.Iterator;
19-
2018 import com.datastax.driver.core.*;
21-
2219 import joptsimple.OptionParser;
2320 import joptsimple.OptionSet;
2421
22+import java.util.Iterator;
23+
2524 public abstract class QueryGenerator implements Iterator<QueryGenerator.Request> {
2625
2726 protected final int iterations;
@@ -38,8 +37,11 @@
3837
3938 public interface Builder {
4039 public String name();
40+
4141 public OptionParser addOptions(OptionParser parser);
42+
4243 public void prepare(OptionSet options, Session session);
44+
4345 public QueryGenerator create(int id, int iterations, OptionSet options, Session session);
4446 }
4547
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Reporter.java +23 −17
@@ -15,15 +15,21 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.io.*;
19-import java.util.concurrent.*;
20-import java.util.concurrent.atomic.AtomicInteger;
21-
2218 import com.yammer.metrics.Metrics;
23-import com.yammer.metrics.core.*;
24-import com.yammer.metrics.reporting.*;
19+import com.yammer.metrics.core.Meter;
20+import com.yammer.metrics.core.Timer;
21+import com.yammer.metrics.core.TimerContext;
2522 import com.yammer.metrics.stats.Snapshot;
2623
24+import java.io.File;
25+import java.io.FileOutputStream;
26+import java.io.IOException;
27+import java.io.PrintStream;
28+import java.util.concurrent.Executors;
29+import java.util.concurrent.ScheduledExecutorService;
30+import java.util.concurrent.TimeUnit;
31+import java.util.concurrent.atomic.AtomicInteger;
32+
2733 public class Reporter implements Runnable {
2834
2935 private Meter requests;
@@ -67,8 +73,8 @@
6773 this.iterations = iterations;
6874
6975 // Middle = exclude first and last 10% (note: if requests is -1, we'll end up with negative bounds, which will always exclude. It's fine if we never stop anyway)
70- this.middleLowBound = (int)(0.1 * iterations);
71- this.middleHighBound = (int)(0.9 * iterations);
76+ this.middleLowBound = (int) (0.1 * iterations);
77+ this.middleHighBound = (int) (0.9 * iterations);
7278 }
7379
7480 private static String formatHeader(String[] args) {
@@ -162,14 +168,14 @@
162168
163169 private void reportToCSV(Report report) {
164170 csv.println(new StringBuilder()
165- .append(report.elapsed).append(',')
166- .append(report.totalOps).append(',')
167- .append(report.intervalRate).append(',')
168- .append(report.meanRate).append(',')
169- .append(report.meanLatency).append(',')
170- .append(report.latency95th).append(',')
171- .append(report.latency99th).append(',')
172- .append(report.stdDev));
171+ .append(report.elapsed).append(',')
172+ .append(report.totalOps).append(',')
173+ .append(report.intervalRate).append(',')
174+ .append(report.meanRate).append(',')
175+ .append(report.meanLatency).append(',')
176+ .append(report.latency95th).append(',')
177+ .append(report.latency99th).append(',')
178+ .append(report.stdDev));
173179 }
174180
175181 private void stopCSV(Report lastReport) {
@@ -197,7 +203,7 @@
197203
198204 private void printReportToConsole(Report report) {
199205 long delay = report.timestamp - lastConsoleTimestamp;
200- double intervalRate = (((double)(report.totalOps - lastConsoleOpCount)) / delay) * 1000;
206+ double intervalRate = (((double) (report.totalOps - lastConsoleOpCount)) / delay) * 1000;
201207
202208 String msg = String.format(" %8d | %12d | %13.2f | %12.2f | %17.3f | %17.3f | %17.3f | %9.3f",
203209 report.elapsed, report.totalOps, intervalRate, report.meanRate, report.meanLatency, report.latency95th, report.latency99th, report.stdDev);
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Stress.java +27 −26
@@ -15,32 +15,33 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.io.IOException;
19-import java.util.*;
20-
2118 import com.datastax.driver.core.*;
22-import com.datastax.driver.core.exceptions.*;
23-
19+import com.datastax.driver.core.exceptions.NoHostAvailableException;
20+import joptsimple.*;
2421 import org.apache.log4j.PropertyConfigurator;
2522
26-import joptsimple.*;
23+import java.io.IOException;
24+import java.util.HashMap;
25+import java.util.List;
26+import java.util.Map;
2727
2828 /**
2929 * A simple stress tool to demonstrate the use of the driver.
30- *
30+ * <p/>
3131 * Sample usage:
32- * stress insert -n 100000
33- * stress read -n 10000
32+ * stress insert -n 100000
33+ * stress read -n 10000
3434 */
3535 public class Stress {
3636
3737 private static final Map<String, QueryGenerator.Builder> generators = new HashMap<String, QueryGenerator.Builder>();
38+
3839 static {
3940 PropertyConfigurator.configure(System.getProperty("log4j.configuration", "./conf/log4j.properties"));
4041
41- QueryGenerator.Builder[] gs = new QueryGenerator.Builder[] {
42- Generators.INSERTER,
43- Generators.READER
42+ QueryGenerator.Builder[] gs = new QueryGenerator.Builder[]{
43+ Generators.INSERTER,
44+ Generators.READER
4445 };
4546
4647 for (QueryGenerator.Builder b : gs)
@@ -60,7 +61,7 @@
6061 accepts("connections-per-host", "The number of connections per hosts (default: based on the number of threads)").withRequiredArg().ofType(Integer.class);
6162 }};
6263 String msg = "Where <generator> can be one of " + generators.keySet() + '\n'
63- + "You can get more help on a particular generator with: stress <generator> -h";
64+ + "You can get more help on a particular generator with: stress <generator> -h";
6465 parser.formatHelpWith(Help.formatFor("<generator>", msg));
6566 return parser;
6667 }
@@ -175,7 +176,7 @@
175176 public static Help formatFor(String generator, String header) {
176177 // It's a pain in the ass to get the real console width in JAVA so hardcode it. But it's the 21th
177178 // century, we're not stuck at 80 characters anymore.
178- int width = 120;
179+ int width = 120;
179180 return new Help(new BuiltinHelpFormatter(width, 4), generator, header);
180181 }
181182
@@ -195,19 +196,19 @@
195196 Stresser stresser = Stresser.forCommandLineArguments(args);
196197 OptionSet options = stresser.getOptions();
197198
198- int requests = options.has("n") ? (Integer)options.valueOf("n") : -1;
199- int concurrency = (Integer)options.valueOf("t");
199+ int requests = options.has("n") ? (Integer) options.valueOf("n") : -1;
200+ int concurrency = (Integer) options.valueOf("t");
200201
201- String reportFileName = (String)options.valueOf("report-file");
202+ String reportFileName = (String) options.valueOf("report-file");
202203
203204 boolean async = options.has("async");
204205
205- int iterations = (requests == -1 ? -1 : requests / concurrency);
206+ int iterations = (requests == -1 ? -1 : requests / concurrency);
206207
207208 final int maxRequestsPerConnection = 128;
208209 int maxConnections = options.has("connections-per-host")
209- ? (Integer)options.valueOf("connections-per-host")
210- : concurrency / maxRequestsPerConnection + 1;
210+ ? (Integer) options.valueOf("connections-per-host")
211+ : concurrency / maxRequestsPerConnection + 1;
211212
212213 PoolingOptions pools = new PoolingOptions();
213214 pools.setNewConnectionThreshold(HostDistance.LOCAL, concurrency);
@@ -226,10 +227,10 @@
226227 try {
227228 // Create session to hosts
228229 Cluster cluster = new Cluster.Builder()
229- .addContactPoints(String.valueOf(options.valueOf("ip")))
230- .withPoolingOptions(pools)
231- .withSocketOptions(new SocketOptions().setTcpNoDelay(true))
232- .build();
230+ .addContactPoints(String.valueOf(options.valueOf("ip")))
231+ .withPoolingOptions(pools)
232+ .withSocketOptions(new SocketOptions().setTcpNoDelay(true))
233+ .build();
233234
234235 if (options.has("compression"))
235236 cluster.getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.SNAPPY);
@@ -242,13 +243,13 @@
242243 System.out.println("Preparing test...");
243244 stresser.prepare(session);
244245
245- Reporter reporter = new Reporter((Integer)options.valueOf("print-delay"), reportFileName, args, requests);
246+ Reporter reporter = new Reporter((Integer) options.valueOf("print-delay"), reportFileName, args, requests);
246247
247248 Consumer[] consumers = new Consumer[concurrency];
248249 for (int i = 0; i < concurrency; i++) {
249250 QueryGenerator generator = stresser.newGenerator(i, session, iterations);
250251 consumers[i] = async ? new AsynchronousConsumer(session, generator, reporter) :
251- new BlockingConsumer(session, generator, reporter);
252+ new BlockingConsumer(session, generator, reporter);
252253 }
253254
254255 System.out.println("Starting to stress test...");
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/MappingCodec.java +5 −6
@@ -15,26 +15,25 @@
1515 */
1616 package com.datastax.driver.extras.codecs;
1717
18-import java.nio.ByteBuffer;
19-
20-import com.google.common.reflect.TypeToken;
21-
2218 import com.datastax.driver.core.ProtocolVersion;
2319 import com.datastax.driver.core.TypeCodec;
2420 import com.datastax.driver.core.exceptions.InvalidTypeException;
21+import com.google.common.reflect.TypeToken;
22+
23+import java.nio.ByteBuffer;
2524
2625 /**
2726 * An abstract {@link TypeCodec} that maps a Java Pojo to another Java object
2827 * that can in turn be serialized into a CQL type.
2928 * This can serve as a base for libraries dealing with Pojo mappings.
30- * <p>
29+ * <p/>
3130 * This codec can be seen as a convenience base class for libraries
3231 * dealing with Pojo-to-Pojo mappings, but it comes
3332 * with a performance penalty: each Java object is serialized
3433 * in two steps: first to an intermediate object, and then to a {@link ByteBuffer},
3534 * which means that each serialization actually incurs in two potentially
3635 * expensive operations being carried.
37- * <p>
36+ * <p/>
3837 * If such operations are really expensive, and your mapping library is capable
3938 * of serializing objects directly to {@link ByteBuffer}s,
4039 * consider writing your own codec instead of using this one.
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/ParsingCodec.java +5 −6
@@ -15,25 +15,24 @@
1515 */
1616 package com.datastax.driver.extras.codecs;
1717
18-import java.nio.ByteBuffer;
19-
20-import com.google.common.reflect.TypeToken;
21-
2218 import com.datastax.driver.core.ProtocolVersion;
2319 import com.datastax.driver.core.TypeCodec;
2420 import com.datastax.driver.core.exceptions.InvalidTypeException;
21+import com.google.common.reflect.TypeToken;
22+
23+import java.nio.ByteBuffer;
2524
2625 /**
2726 * An abstract {@link TypeCodec} that stores JAVA objects as serialized strings.
2827 * This can serve as a base for codecs dealing with XML or JSON formats.
29- * <p>
28+ * <p/>
3029 * This codec can be seen as a convenience base class to help
3130 * implementing Java-to-XML or Java-to-JSON mappings, but it comes
3231 * with a performance penalty: each Java object is serialized
3332 * in two steps: first to a String, and then to a {@link ByteBuffer},
3433 * which means that each serialization actually incurs in two potentially
3534 * expensive operations being carried.
36- * <p>
35+ * <p/>
3736 * If you are using an XML or JSON library that supports writing Java objects
3837 * directly to {@link ByteBuffer}s, consider writing your own codec instead of
3938 * using this one.
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/AbstractArrayCodec.java +8 −9
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.extras.codecs.arrays;
1717
18-import java.lang.reflect.Array;
19-
20-import static com.google.common.base.Preconditions.checkArgument;
21-
2218 import com.datastax.driver.core.DataType;
2319 import com.datastax.driver.core.ParseUtils;
2420 import com.datastax.driver.core.TypeCodec;
2521 import com.datastax.driver.core.exceptions.InvalidTypeException;
2622
23+import java.lang.reflect.Array;
24+
2725 import static com.datastax.driver.core.ParseUtils.skipSpaces;
26+import static com.google.common.base.Preconditions.checkArgument;
2827
2928 /**
3029 * Base class for all codecs dealing with Java arrays.
@@ -35,7 +34,7 @@
3534 public abstract class AbstractArrayCodec<T> extends TypeCodec<T> {
3635
3736 /**
38- * @param cqlType The CQL type. Must be a list type.
37+ * @param cqlType The CQL type. Must be a list type.
3938 * @param javaClass The Java type. Must be an array class.
4039 */
4140 public AbstractArrayCodec(DataType.CollectionType cqlType, Class<T> javaClass) {
@@ -80,7 +79,7 @@
8079 // second pass: parse elements
8180 T array = newInstance(length);
8281 int i = 0;
83- for( ; idx < value.length(); i++) {
82+ for (; idx < value.length(); i++) {
8483 int n = skipLiteral(value, idx);
8584 parseElement(value.substring(idx, n), array, i);
8685 idx = skipSpaces(value, n);
@@ -105,8 +104,8 @@
105104 * Format the {@code index}th element of {@code array} to {@code output}.
106105 *
107106 * @param output The StringBuilder to write to.
108- * @param array The array to read from.
109- * @param index The element index.
107+ * @param array The array to read from.
108+ * @param index The element index.
110109 */
111110 protected abstract void formatElement(StringBuilder output, T array, int index);
112111
@@ -121,7 +120,7 @@
121120
122121 private int getArrayLength(String value, int idx) {
123122 int length = 1;
124- for( ; idx < value.length(); length++) {
123+ for (; idx < value.length(); length++) {
125124 idx = skipLiteral(value, idx);
126125 idx = skipSpaces(value, idx);
127126 if (value.charAt(idx) == ']')
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/AbstractPrimitiveArrayCodec.java +16 −14
@@ -15,16 +15,16 @@
1515 */
1616 package com.datastax.driver.extras.codecs.arrays;
1717
18-import java.lang.reflect.Array;
19-import java.nio.ByteBuffer;
20-
21-import static com.google.common.base.Preconditions.checkArgument;
22-
2318 import com.datastax.driver.core.CodecUtils;
2419 import com.datastax.driver.core.DataType;
2520 import com.datastax.driver.core.ProtocolVersion;
2621 import com.datastax.driver.core.exceptions.InvalidTypeException;
2722
23+import java.lang.reflect.Array;
24+import java.nio.ByteBuffer;
25+
26+import static com.google.common.base.Preconditions.checkArgument;
27+
2828 /**
2929 * Base class for all codecs dealing with Java primitive arrays.
3030 * This class provides a more efficient implementation of {@link #serialize(Object, ProtocolVersion)}
@@ -35,7 +35,7 @@
3535 public abstract class AbstractPrimitiveArrayCodec<T> extends AbstractArrayCodec<T> {
3636
3737 /**
38- * @param cqlType The CQL type. Must be a list type.
38+ * @param cqlType The CQL type. Must be a list type.
3939 * @param javaClass The Java type. Must be an array class.
4040 */
4141 public AbstractPrimitiveArrayCodec(DataType.CollectionType cqlType, Class<T> javaClass) {
@@ -51,8 +51,8 @@
5151 // native method
5252 int length = Array.getLength(array);
5353 checkArgument(isProtocolV3OrAbove || length < 65536,
54- "Native protocol version %d supports up to 65535 elements in any collection - but collection contains %d elements",
55- protocolVersion.toInt(), length);
54+ "Native protocol version %d supports up to 65535 elements in any collection - but collection contains %d elements",
55+ protocolVersion.toInt(), length);
5656 /*
5757 * Encoding of lists in the native protocol:
5858 * [size of list] [size of element 1][element1] [size of element 2][element2]...
@@ -101,18 +101,20 @@
101101
102102 /**
103103 * Write the {@code index}th element of {@code array} to {@code output}.
104- * @param output The ByteBuffer to write to.
105- * @param array The array to read from.
106- * @param index The element index.
104+ *
105+ * @param output The ByteBuffer to write to.
106+ * @param array The array to read from.
107+ * @param index The element index.
107108 * @param protocolVersion The protocol version to use.
108109 */
109110 protected abstract void serializeElement(ByteBuffer output, T array, int index, ProtocolVersion protocolVersion);
110111
111112 /**
112113 * Read the {@code index}th element of {@code array} from {@code input}.
113- * @param input The ByteBuffer to read from.
114- * @param array The array to write to.
115- * @param index The element index.
114+ *
115+ * @param input The ByteBuffer to read from.
116+ * @param array The array to write to.
117+ * @param index The element index.
116118 * @param protocolVersion The protocol version to use.
117119 */
118120 protected abstract void deserializeElement(ByteBuffer input, T array, int index, ProtocolVersion protocolVersion);
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/DoubleArrayCodec.java +3 −3
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.extras.codecs.arrays;
1717
18-import java.nio.ByteBuffer;
19-
2018 import com.datastax.driver.core.DataType;
2119 import com.datastax.driver.core.ProtocolVersion;
2220
21+import java.nio.ByteBuffer;
22+
2323 /**
2424 * A codec that maps the CQL type {@code list<double>} to the Java type {@code double[]}.
25- * <p>
25+ * <p/>
2626 * Note that this codec is designed for performance and converts CQL lists
2727 * <em>directly</em> to {@code double[]}, thus avoiding any unnecessary
2828 * boxing and unboxing of Java primitive {@code double} values;
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/FloatArrayCodec.java +3 −3
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.extras.codecs.arrays;
1717
18-import java.nio.ByteBuffer;
19-
2018 import com.datastax.driver.core.DataType;
2119 import com.datastax.driver.core.ProtocolVersion;
2220
21+import java.nio.ByteBuffer;
22+
2323 /**
2424 * A codec that maps the CQL type {@code list<float>} to the Java type {@code float[]}.
25- * <p>
25+ * <p/>
2626 * Note that this codec is designed for performance and converts CQL lists
2727 * <em>directly</em> to {@code float[]}, thus avoiding any unnecessary
2828 * boxing and unboxing of Java primitive {@code float} values;
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/IntArrayCodec.java +3 −3
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.extras.codecs.arrays;
1717
18-import java.nio.ByteBuffer;
19-
2018 import com.datastax.driver.core.DataType;
2119 import com.datastax.driver.core.ProtocolVersion;
2220
21+import java.nio.ByteBuffer;
22+
2323 /**
2424 * A codec that maps the CQL type {@code list<int>} to the Java type {@code int[]}.
25- * <p>
25+ * <p/>
2626 * Note that this codec is designed for performance and converts CQL lists
2727 * <em>directly</em> to {@code int[]}, thus avoiding any unnecessary
2828 * boxing and unboxing of Java primitive {@code int} values;
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/LongArrayCodec.java +3 −3
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.extras.codecs.arrays;
1717
18-import java.nio.ByteBuffer;
19-
2018 import com.datastax.driver.core.DataType;
2119 import com.datastax.driver.core.ProtocolVersion;
2220
21+import java.nio.ByteBuffer;
22+
2323 /**
2424 * A codec that maps the CQL type {@code list<long>} to the Java type {@code long[]}.
25- * <p>
25+ * <p/>
2626 * Note that this codec is designed for performance and converts CQL lists
2727 * <em>directly</em> to {@code long[]}, thus avoiding any unnecessary
2828 * boxing and unboxing of Java primitive {@code long} values;
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/ObjectArrayCodec.java +8 −8
@@ -15,21 +15,21 @@
1515 */
1616 package com.datastax.driver.extras.codecs.arrays;
1717
18-import java.lang.reflect.Array;
19-import java.nio.BufferUnderflowException;
20-import java.nio.ByteBuffer;
21-
2218 import com.datastax.driver.core.CodecUtils;
2319 import com.datastax.driver.core.DataType;
2420 import com.datastax.driver.core.ProtocolVersion;
2521 import com.datastax.driver.core.TypeCodec;
2622 import com.datastax.driver.core.exceptions.InvalidTypeException;
2723
24+import java.lang.reflect.Array;
25+import java.nio.BufferUnderflowException;
26+import java.nio.ByteBuffer;
27+
2828 /**
2929 * Codec dealing with Java object arrays.
3030 * Serialization and deserialization of elements in the array is
3131 * delegated to the provided element codec.
32- * <p>
32+ * <p/>
3333 * For example, to create a codec that maps {@code list<text>} to {@code String[]},
3434 * declare the following:
3535 * <pre>{@code
@@ -65,8 +65,8 @@
6565 bb = eltCodec.serialize(elt, protocolVersion);
6666 } catch (ClassCastException e) {
6767 throw new InvalidTypeException(
68- String.format("Invalid type for %s element, expecting %s but got %s",
69- cqlType, eltCodec.getJavaType(), elt.getClass()), e);
68+ String.format("Invalid type for %s element, expecting %s but got %s",
69+ cqlType, eltCodec.getJavaType(), elt.getClass()), e);
7070 }
7171 bbs[i++] = bb;
7272 }
@@ -104,6 +104,6 @@
104104 @Override
105105 @SuppressWarnings("unchecked")
106106 protected E[] newInstance(int size) {
107- return (E[])Array.newInstance(getJavaType().getRawType().getComponentType(), size);
107+ return (E[]) Array.newInstance(getJavaType().getRawType().getComponentType(), size);
108108 }
109109 }
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/date/SimpleDateCodec.java +8 −16
@@ -15,34 +15,26 @@
1515 */
1616 package com.datastax.driver.extras.codecs.date;
1717
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.InvalidTypeException;
20+
1821 import java.nio.ByteBuffer;
1922 import java.text.ParseException;
2023 import java.util.Date;
2124
25+import static com.datastax.driver.core.CodecUtils.*;
26+import static com.datastax.driver.core.ParseUtils.*;
2227 import static java.util.concurrent.TimeUnit.MILLISECONDS;
2328
24-import com.datastax.driver.core.*;
25-import com.datastax.driver.core.exceptions.InvalidTypeException;
26-
27-import static com.datastax.driver.core.CodecUtils.fromCqlDateToDaysSinceEpoch;
28-import static com.datastax.driver.core.CodecUtils.fromDaysSinceEpochToCqlDate;
29-import static com.datastax.driver.core.CodecUtils.fromSignedToUnsignedInt;
30-import static com.datastax.driver.core.CodecUtils.fromUnsignedToSignedInt;
31-import static com.datastax.driver.core.ParseUtils.isLongLiteral;
32-import static com.datastax.driver.core.ParseUtils.isQuoted;
33-import static com.datastax.driver.core.ParseUtils.parseDate;
34-import static com.datastax.driver.core.ParseUtils.quote;
35-import static com.datastax.driver.core.ParseUtils.unquote;
36-
3729 /**
3830 * A {@link TypeCodec} that maps CQL dates to Java primitive ints,
3931 * representing the number of days since the Epoch.
40- * <p>
32+ * <p/>
4133 * This codec can serve as a replacement for the driver's built-in
4234 * {@link TypeCodec#date() date} codec,
4335 * when application code prefers to deal with raw days than with
4436 * {@link LocalDate} instances.
45- * <p>
37+ * <p/>
4638 * <strong>Important</strong>: this codec cannot work with {@link SimpleStatement}s!
4739 * If you try to insert CQL date values as {@code int}s in a {@link SimpleStatement},
4840 * the insertion would succeed but the values wouldn't be properly encoded.
@@ -96,7 +88,7 @@
9688
9789 try {
9890 Date date = parseDate(value, pattern);
99- return (int)MILLISECONDS.toDays(date.getTime());
91+ return (int) MILLISECONDS.toDays(date.getTime());
10092 } catch (ParseException e) {
10193 throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value), e);
10294 }
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/date/SimpleTimestampCodec.java +5 −6
@@ -15,22 +15,21 @@
1515 */
1616 package com.datastax.driver.extras.codecs.date;
1717
18-import java.nio.ByteBuffer;
19-import java.text.ParseException;
20-
21-import static java.lang.Long.parseLong;
22-
2318 import com.datastax.driver.core.DataType;
2419 import com.datastax.driver.core.ProtocolVersion;
2520 import com.datastax.driver.core.TypeCodec;
2621 import com.datastax.driver.core.exceptions.InvalidTypeException;
2722
23+import java.nio.ByteBuffer;
24+import java.text.ParseException;
25+
2826 import static com.datastax.driver.core.ParseUtils.*;
27+import static java.lang.Long.parseLong;
2928
3029 /**
3130 * A {@link TypeCodec} that maps CQL timestamps to Java primitive longs,
3231 * representing the number of milliseconds since the Epoch.
33- * <p>
32+ * <p/>
3433 * This codec can serve as a replacement for the driver's built-in
3534 * {@link TypeCodec#timestamp() timestamp} codec,
3635 * when application code prefers to deal with raw milliseconds than with
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/enums/EnumNameCodec.java +1 −1
@@ -21,7 +21,7 @@
2121 /**
2222 * A codec that serializes {@link Enum} instances as CQL {@code varchar}s
2323 * representing their programmatic names as returned by {@link Enum#name()}.
24- * <p>
24+ * <p/>
2525 * <strong>Note that this codec relies on the enum constant names;
2626 * it is therefore vital that enum names never change.</strong>
2727 *
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/enums/EnumOrdinalCodec.java +3 −3
@@ -15,16 +15,16 @@
1515 */
1616 package com.datastax.driver.extras.codecs.enums;
1717
18-import java.nio.ByteBuffer;
19-
2018 import com.datastax.driver.core.ProtocolVersion;
2119 import com.datastax.driver.core.TypeCodec;
2220 import com.datastax.driver.core.exceptions.InvalidTypeException;
2321
22+import java.nio.ByteBuffer;
23+
2424 /**
2525 * A codec that serializes {@link Enum} instances as CQL {@code int}s
2626 * representing their ordinal values as returned by {@link Enum#ordinal()}.
27- * <p>
27+ * <p/>
2828 * <strong>Note that this codec relies on the enum constants declaration order;
2929 * it is therefore vital that this order remains immutable.</strong>
3030 *
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/guava/OptionalCodec.java +9 −8
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.extras.codecs.guava;
1717
18-import java.util.Collection;
19-import java.util.Map;
20-
18+import com.datastax.driver.core.TypeCodec;
19+import com.datastax.driver.extras.codecs.MappingCodec;
2120 import com.google.common.base.Optional;
2221 import com.google.common.base.Predicate;
2322 import com.google.common.reflect.TypeParameter;
2423 import com.google.common.reflect.TypeToken;
2524
26-import com.datastax.driver.core.TypeCodec;
27-import com.datastax.driver.extras.codecs.MappingCodec;
25+import java.util.Collection;
26+import java.util.Map;
2827
2928 /**
3029 * A codec that wraps other codecs around Guava's {@link Optional} API.
@@ -40,14 +39,16 @@
4039 @Override
4140 public boolean apply(T input) {
4241 return input == null
43- || input instanceof Collection && ((Collection)input).isEmpty()
44- || input instanceof Map && ((Map)input).isEmpty();
42+ || input instanceof Collection && ((Collection) input).isEmpty()
43+ || input instanceof Map && ((Map) input).isEmpty();
4544 }
4645 });
4746 }
4847
4948 public OptionalCodec(TypeCodec<T> codec, Predicate<T> isAbsent) {
50- super(codec, new TypeToken<Optional<T>>(){}.where(new TypeParameter<T>(){}, codec.getJavaType()));
49+ super(codec, new TypeToken<Optional<T>>() {
50+ }.where(new TypeParameter<T>() {
51+ }, codec.getJavaType()));
5152 this.isAbsent = isAbsent;
5253 }
5354
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/InstantCodec.java +30 −38
@@ -15,30 +15,22 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18+import com.datastax.driver.core.DataType;
19+import com.datastax.driver.core.ProtocolVersion;
20+import com.datastax.driver.core.TypeCodec;
21+import com.datastax.driver.core.exceptions.InvalidTypeException;
22+
1823 import java.nio.ByteBuffer;
1924 import java.time.Instant;
2025 import java.time.format.DateTimeFormatter;
2126 import java.time.format.DateTimeFormatterBuilder;
2227 import java.time.format.DateTimeParseException;
23-import java.util.Date;
2428
29+import static com.datastax.driver.core.ParseUtils.*;
2530 import static java.lang.Long.parseLong;
2631 import static java.time.Instant.ofEpochMilli;
2732 import static java.time.ZoneOffset.UTC;
28-import static java.time.temporal.ChronoField.HOUR_OF_DAY;
29-import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
30-import static java.time.temporal.ChronoField.NANO_OF_SECOND;
31-import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
32-
33-import com.datastax.driver.core.DataType;
34-import com.datastax.driver.core.ProtocolVersion;
35-import com.datastax.driver.core.TypeCodec;
36-import com.datastax.driver.core.exceptions.InvalidTypeException;
37-
38-import static com.datastax.driver.core.ParseUtils.isLongLiteral;
39-import static com.datastax.driver.core.ParseUtils.isQuoted;
40-import static com.datastax.driver.core.ParseUtils.quote;
41-import static com.datastax.driver.core.ParseUtils.unquote;
33+import static java.time.temporal.ChronoField.*;
4234
4335 /**
4436 * <p>
@@ -46,7 +38,7 @@
4638 * allowing the setting and retrieval of {@code timestamp}
4739 * columns as {@link Instant} instances.
4840 * </p>
49- *
41+ * <p/>
5042 * <p>
5143 * Since C* <code>timestamp</code> columns do not preserve timezones
5244 * any attached timezone information will be lost.
@@ -65,30 +57,30 @@
6557 * the ISO formats accepted in CQL.
6658 */
6759 private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
68- .parseCaseSensitive()
69- .parseStrict()
70- .append(DateTimeFormatter.ISO_LOCAL_DATE)
71- .optionalStart()
72- .appendLiteral('T')
73- .appendValue(HOUR_OF_DAY, 2)
74- .appendLiteral(':')
75- .appendValue(MINUTE_OF_HOUR, 2)
76- .optionalEnd()
77- .optionalStart()
78- .appendLiteral(':')
79- .appendValue(SECOND_OF_MINUTE, 2)
80- .optionalEnd()
81- .optionalStart()
82- .appendFraction(NANO_OF_SECOND, 0, 9, true)
83- .optionalEnd()
84- .optionalStart()
85- .appendZoneId()
86- .optionalEnd()
87- .toFormatter()
88- .withZone(UTC);
60+ .parseCaseSensitive()
61+ .parseStrict()
62+ .append(DateTimeFormatter.ISO_LOCAL_DATE)
63+ .optionalStart()
64+ .appendLiteral('T')
65+ .appendValue(HOUR_OF_DAY, 2)
66+ .appendLiteral(':')
67+ .appendValue(MINUTE_OF_HOUR, 2)
68+ .optionalEnd()
69+ .optionalStart()
70+ .appendLiteral(':')
71+ .appendValue(SECOND_OF_MINUTE, 2)
72+ .optionalEnd()
73+ .optionalStart()
74+ .appendFraction(NANO_OF_SECOND, 0, 9, true)
75+ .optionalEnd()
76+ .optionalStart()
77+ .appendZoneId()
78+ .optionalEnd()
79+ .toFormatter()
80+ .withZone(UTC);
8981
9082 private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
91- .withZone(UTC);
83+ .withZone(UTC);
9284
9385
9486 private InstantCodec() {
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/LocalDateCodec.java +7 −11
@@ -15,24 +15,20 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18+import com.datastax.driver.core.DataType;
19+import com.datastax.driver.core.ProtocolVersion;
20+import com.datastax.driver.core.TypeCodec;
21+import com.datastax.driver.core.exceptions.InvalidTypeException;
22+
1823 import java.nio.ByteBuffer;
1924 import java.time.LocalDate;
2025 import java.time.temporal.ChronoUnit;
2126
27+import static com.datastax.driver.core.CodecUtils.*;
28+import static com.datastax.driver.core.ParseUtils.*;
2229 import static java.lang.Long.parseLong;
2330 import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE;
2431
25-import com.datastax.driver.core.*;
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
27-
28-import static com.datastax.driver.core.CodecUtils.fromCqlDateToDaysSinceEpoch;
29-import static com.datastax.driver.core.CodecUtils.fromSignedToUnsignedInt;
30-import static com.datastax.driver.core.CodecUtils.fromUnsignedToSignedInt;
31-import static com.datastax.driver.core.ParseUtils.isLongLiteral;
32-import static com.datastax.driver.core.ParseUtils.isQuoted;
33-import static com.datastax.driver.core.ParseUtils.quote;
34-import static com.datastax.driver.core.ParseUtils.unquote;
35-
3632 /**
3733 * {@link TypeCodec} that maps
3834 * {@link java.time.LocalDate} to CQL {@code date}.
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodec.java +4 −4
@@ -15,16 +15,16 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18-import java.nio.ByteBuffer;
19-import java.time.LocalTime;
20-import java.time.format.DateTimeFormatter;
21-
2218 import com.datastax.driver.core.DataType;
2319 import com.datastax.driver.core.ParseUtils;
2420 import com.datastax.driver.core.ProtocolVersion;
2521 import com.datastax.driver.core.TypeCodec;
2622 import com.datastax.driver.core.exceptions.InvalidTypeException;
2723
24+import java.nio.ByteBuffer;
25+import java.time.LocalTime;
26+import java.time.format.DateTimeFormatter;
27+
2828 import static com.datastax.driver.core.ParseUtils.quote;
2929
3030 /**
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/OptionalCodec.java +10 −9
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18+import com.datastax.driver.core.TypeCodec;
19+import com.datastax.driver.extras.codecs.MappingCodec;
20+import com.google.common.reflect.TypeParameter;
21+import com.google.common.reflect.TypeToken;
22+
1823 import java.util.Collection;
1924 import java.util.Map;
2025 import java.util.Optional;
2126 import java.util.function.Predicate;
2227
23-import com.google.common.reflect.TypeParameter;
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.TypeCodec;
27-import com.datastax.driver.extras.codecs.MappingCodec;
28-
2928 /**
3029 * A codec that wraps other codecs around JDK 8's {@link Optional} API.
3130 *
@@ -40,15 +39,17 @@
4039 @Override
4140 public boolean test(T input) {
4241 return input == null
43- || input instanceof Collection && ((Collection)input).isEmpty()
44- || input instanceof Map && ((Map)input).isEmpty();
42+ || input instanceof Collection && ((Collection) input).isEmpty()
43+ || input instanceof Map && ((Map) input).isEmpty();
4544
4645 }
4746 });
4847 }
4948
5049 public OptionalCodec(TypeCodec<T> codec, Predicate<T> isAbsent) {
51- super(codec, new TypeToken<Optional<T>>(){}.where(new TypeParameter<T>(){}, codec.getJavaType()));
50+ super(codec, new TypeToken<Optional<T>>() {
51+ }.where(new TypeParameter<T>() {
52+ }, codec.getJavaType()));
5253 this.isAbsent = isAbsent;
5354 }
5455
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodec.java +44 −49
@@ -15,6 +15,9 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.InvalidTypeException;
20+
1821 import java.nio.ByteBuffer;
1922 import java.time.Instant;
2023 import java.time.ZoneId;
@@ -25,27 +28,19 @@
2528 import java.time.format.DateTimeParseException;
2629 import java.util.List;
2730
28-import static java.time.temporal.ChronoField.HOUR_OF_DAY;
29-import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
30-import static java.time.temporal.ChronoField.NANO_OF_SECOND;
31-import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
32-
33-import static com.google.common.base.Preconditions.checkArgument;
34-
35-import com.datastax.driver.core.*;
36-import com.datastax.driver.core.exceptions.InvalidTypeException;
37-
3831 import static com.datastax.driver.core.ParseUtils.isLongLiteral;
3932 import static com.datastax.driver.core.ParseUtils.quote;
33+import static com.google.common.base.Preconditions.checkArgument;
34+import static java.time.temporal.ChronoField.*;
4035
4136 /**
42- * <p>
37+ * <p/>
4338 * {@link TypeCodec} that maps
4439 * {@link ZonedDateTime} to CQL {@code tuple<timestamp,varchar>},
4540 * providing a pattern for maintaining timezone information in
4641 * Cassandra.
47- *
48- * <p>
42+ * <p/>
43+ * <p/>
4944 * Since Cassandra's <code>timestamp</code> type preserves only
5045 * milliseconds since epoch, any timezone information
5146 * would normally be lost. By using a
@@ -64,27 +59,27 @@
6459 * the ISO formats accepted in CQL.
6560 */
6661 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
67- .parseCaseSensitive()
68- .parseStrict()
69- .append(DateTimeFormatter.ISO_LOCAL_DATE)
70- .optionalStart()
71- .appendLiteral('T')
72- .appendValue(HOUR_OF_DAY, 2)
73- .appendLiteral(':')
74- .appendValue(MINUTE_OF_HOUR, 2)
75- .optionalEnd()
76- .optionalStart()
77- .appendLiteral(':')
78- .appendValue(SECOND_OF_MINUTE, 2)
79- .optionalEnd()
80- .optionalStart()
81- .appendFraction(NANO_OF_SECOND, 0, 9, true)
82- .optionalEnd()
83- .optionalStart()
84- .appendZoneOrOffsetId()
85- .optionalEnd()
86- .toFormatter()
87- .withZone(ZoneOffset.UTC);
62+ .parseCaseSensitive()
63+ .parseStrict()
64+ .append(DateTimeFormatter.ISO_LOCAL_DATE)
65+ .optionalStart()
66+ .appendLiteral('T')
67+ .appendValue(HOUR_OF_DAY, 2)
68+ .appendLiteral(':')
69+ .appendValue(MINUTE_OF_HOUR, 2)
70+ .optionalEnd()
71+ .optionalStart()
72+ .appendLiteral(':')
73+ .appendValue(SECOND_OF_MINUTE, 2)
74+ .optionalEnd()
75+ .optionalStart()
76+ .appendFraction(NANO_OF_SECOND, 0, 9, true)
77+ .optionalEnd()
78+ .optionalStart()
79+ .appendZoneOrOffsetId()
80+ .optionalEnd()
81+ .toFormatter()
82+ .withZone(ZoneOffset.UTC);
8883
8984 private static final DateTimeFormatter ZONE_FORMATTER = DateTimeFormatter.ofPattern("xxx");
9085
@@ -92,9 +87,9 @@
9287 super(tupleType, ZonedDateTime.class);
9388 List<DataType> types = tupleType.getComponentTypes();
9489 checkArgument(
95- types.size() == 2 && types.get(0).equals(DataType.timestamp()) && types.get(1).equals(DataType.varchar()),
96- "Expected tuple<timestamp,varchar>, got %s",
97- tupleType);
90+ types.size() == 2 && types.get(0).equals(DataType.timestamp()) && types.get(1).equals(DataType.varchar()),
91+ "Expected tuple<timestamp,varchar>, got %s",
92+ tupleType);
9893 }
9994
10095 @Override
@@ -104,43 +99,43 @@
10499
105100 @Override
106101 protected ByteBuffer serializeField(ZonedDateTime source, int index, ProtocolVersion protocolVersion) {
107- if(index == 0) {
102+ if (index == 0) {
108103 long millis = source.toInstant().toEpochMilli();
109104 return bigint().serializeNoBoxing(millis, protocolVersion);
110105 }
111- if(index == 1) {
106+ if (index == 1) {
112107 return varchar().serialize(ZONE_FORMATTER.format(source.getOffset()), protocolVersion);
113108 }
114- throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
109+ throw new IndexOutOfBoundsException("Tuple index out of bounds. " + index);
115110 }
116111
117112 @Override
118113 protected ZonedDateTime deserializeAndSetField(ByteBuffer input, ZonedDateTime target, int index, ProtocolVersion protocolVersion) {
119- if(index == 0) {
114+ if (index == 0) {
120115 long millis = bigint().deserializeNoBoxing(input, protocolVersion);
121116 return Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC);
122117 }
123- if(index == 1) {
118+ if (index == 1) {
124119 String zoneId = varchar().deserialize(input, protocolVersion);
125120 return target.withZoneSameInstant(ZoneId.of(zoneId));
126121 }
127- throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
122+ throw new IndexOutOfBoundsException("Tuple index out of bounds. " + index);
128123 }
129124
130125 @Override
131126 protected String formatField(ZonedDateTime value, int index) {
132- if(index == 0) {
127+ if (index == 0) {
133128 return quote(FORMATTER.format(value));
134129 }
135- if(index == 1) {
130+ if (index == 1) {
136131 return quote(ZONE_FORMATTER.format(value.getOffset()));
137132 }
138- throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
133+ throw new IndexOutOfBoundsException("Tuple index out of bounds. " + index);
139134 }
140135
141136 @Override
142137 protected ZonedDateTime parseAndSetField(String input, ZonedDateTime target, int index) {
143- if(index == 0) {
138+ if (index == 0) {
144139 // strip enclosing single quotes, if any
145140 if (ParseUtils.isQuoted(input))
146141 input = ParseUtils.unquote(input);
@@ -158,10 +153,10 @@
158153 throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", target));
159154 }
160155 }
161- if(index == 1) {
156+ if (index == 1) {
162157 String zoneId = varchar().parse(input);
163158 return target.withZoneSameInstant(ZoneId.of(zoneId));
164159 }
165- throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
160+ throw new IndexOutOfBoundsException("Tuple index out of bounds. " + index);
166161 }
167162 }
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/package-info.java +2 −3
@@ -19,11 +19,10 @@
1919 * {@link com.datastax.driver.core.TypeCodec TypeCodec} instances useful for
2020 * serializing between CQL types and Java 8 types, such as the ones from the
2121 * {@link java.time} API and {@link java.util.Optional}.
22- *
23- * <p>
22+ * <p/>
23+ * <p/>
2424 * Note that, while the driver remains globally compatible with older JDKs,
2525 * classes in this package require the presence of a Java 8 or higher
2626 * at runtime.
27- *
2827 */
2928 package com.datastax.driver.extras.codecs.jdk8;
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/joda/DateTimeCodec.java +31 −33
@@ -15,9 +15,8 @@
1515 */
1616 package com.datastax.driver.extras.codecs.joda;
1717
18-import java.nio.ByteBuffer;
19-import java.util.List;
20-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.InvalidTypeException;
2120 import org.joda.time.DateTime;
2221 import org.joda.time.DateTimeZone;
2322 import org.joda.time.format.DateTimeFormat;
@@ -25,23 +24,22 @@
2524 import org.joda.time.format.DateTimeFormatterBuilder;
2625 import org.joda.time.format.ISODateTimeFormat;
2726
28-import static com.google.common.base.Preconditions.checkArgument;
29-import static org.joda.time.DateTimeZone.UTC;
30-
31-import com.datastax.driver.core.*;
32-import com.datastax.driver.core.exceptions.InvalidTypeException;
27+import java.nio.ByteBuffer;
28+import java.util.List;
3329
3430 import static com.datastax.driver.core.ParseUtils.isLongLiteral;
3531 import static com.datastax.driver.core.ParseUtils.quote;
32+import static com.google.common.base.Preconditions.checkArgument;
33+import static org.joda.time.DateTimeZone.UTC;
3634
3735 /**
38- * <p>
36+ * <p/>
3937 * {@link TypeCodec} that maps
4038 * {@link DateTime} to CQL {@code tuple<timestamp,varchar>},
4139 * providing a pattern for maintaining timezone information in
4240 * Cassandra.
43- *
44- * <p>
41+ * <p/>
42+ * <p/>
4543 * Since Cassandra's <code>timestamp</code> type preserves only
4644 * milliseconds since epoch, any timezone information
4745 * would normally be lost. By using a
@@ -60,13 +58,13 @@
6058 * the ISO formats accepted in CQL.
6159 */
6260 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
63- .append(ISODateTimeFormat.dateOptionalTimeParser().getParser())
64- .appendOptional(
65- new DateTimeFormatterBuilder()
66- .appendTimeZoneOffset("Z", true, 2, 4)
67- .toParser())
68- .toFormatter()
69- .withZoneUTC();
61+ .append(ISODateTimeFormat.dateOptionalTimeParser().getParser())
62+ .appendOptional(
63+ new DateTimeFormatterBuilder()
64+ .appendTimeZoneOffset("Z", true, 2, 4)
65+ .toParser())
66+ .toFormatter()
67+ .withZoneUTC();
7068
7169 private static final DateTimeFormatter ZONE_FORMATTER = DateTimeFormat.forPattern("ZZ");
7270
@@ -74,9 +72,9 @@
7472 super(tupleType, DateTime.class);
7573 List<DataType> types = tupleType.getComponentTypes();
7674 checkArgument(
77- types.size() == 2 && types.get(0).equals(DataType.timestamp()) && types.get(1).equals(DataType.varchar()),
78- "Expected tuple<timestamp,varchar>, got %s",
79- tupleType);
75+ types.size() == 2 && types.get(0).equals(DataType.timestamp()) && types.get(1).equals(DataType.varchar()),
76+ "Expected tuple<timestamp,varchar>, got %s",
77+ tupleType);
8078 }
8179
8280 @Override
@@ -86,43 +84,43 @@
8684
8785 @Override
8886 protected ByteBuffer serializeField(DateTime source, int index, ProtocolVersion protocolVersion) {
89- if(index == 0) {
87+ if (index == 0) {
9088 long millis = source.getMillis();
9189 return bigint().serializeNoBoxing(millis, protocolVersion);
9290 }
93- if(index == 1) {
91+ if (index == 1) {
9492 return varchar().serialize(ZONE_FORMATTER.print(source), protocolVersion);
9593 }
96- throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
94+ throw new IndexOutOfBoundsException("Tuple index out of bounds. " + index);
9795 }
9896
9997 @Override
10098 protected DateTime deserializeAndSetField(ByteBuffer input, DateTime target, int index, ProtocolVersion protocolVersion) {
101- if(index == 0) {
99+ if (index == 0) {
102100 long millis = bigint().deserializeNoBoxing(input, protocolVersion);
103101 return new DateTime(millis);
104102 }
105- if(index == 1) {
103+ if (index == 1) {
106104 String zoneId = varchar().deserialize(input, protocolVersion);
107105 return target.withZone(DateTimeZone.forID(zoneId));
108106 }
109- throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
107+ throw new IndexOutOfBoundsException("Tuple index out of bounds. " + index);
110108 }
111109
112110 @Override
113111 protected String formatField(DateTime value, int index) {
114- if(index == 0) {
112+ if (index == 0) {
115113 return quote(value.withZone(UTC).toString());
116114 }
117- if(index == 1) {
115+ if (index == 1) {
118116 return quote(ZONE_FORMATTER.print(value));
119117 }
120- throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
118+ throw new IndexOutOfBoundsException("Tuple index out of bounds. " + index);
121119 }
122120
123121 @Override
124122 protected DateTime parseAndSetField(String input, DateTime target, int index) {
125- if(index == 0) {
123+ if (index == 0) {
126124 // strip enclosing single quotes, if any
127125 if (ParseUtils.isQuoted(input))
128126 input = ParseUtils.unquote(input);
@@ -140,11 +138,11 @@
140138 throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", target));
141139 }
142140 }
143- if(index == 1) {
141+ if (index == 1) {
144142 String zoneId = varchar().parse(input);
145143 return target.withZone(DateTimeZone.forID(zoneId));
146144 }
147- throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
145+ throw new IndexOutOfBoundsException("Tuple index out of bounds. " + index);
148146 }
149147
150148 }
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/joda/InstantCodec.java +14 −19
@@ -15,25 +15,20 @@
1515 */
1616 package com.datastax.driver.extras.codecs.joda;
1717
18-import java.nio.ByteBuffer;
19-
20-import static java.lang.Long.parseLong;
21-
18+import com.datastax.driver.core.DataType;
19+import com.datastax.driver.core.ProtocolVersion;
20+import com.datastax.driver.core.TypeCodec;
21+import com.datastax.driver.core.exceptions.InvalidTypeException;
2222 import org.joda.time.Instant;
2323 import org.joda.time.format.DateTimeFormat;
2424 import org.joda.time.format.DateTimeFormatter;
2525 import org.joda.time.format.DateTimeFormatterBuilder;
2626 import org.joda.time.format.ISODateTimeFormat;
2727
28-import com.datastax.driver.core.DataType;
29-import com.datastax.driver.core.ProtocolVersion;
30-import com.datastax.driver.core.TypeCodec;
31-import com.datastax.driver.core.exceptions.InvalidTypeException;
28+import java.nio.ByteBuffer;
3229
33-import static com.datastax.driver.core.ParseUtils.isLongLiteral;
34-import static com.datastax.driver.core.ParseUtils.isQuoted;
35-import static com.datastax.driver.core.ParseUtils.quote;
36-import static com.datastax.driver.core.ParseUtils.unquote;
30+import static com.datastax.driver.core.ParseUtils.*;
31+import static java.lang.Long.parseLong;
3732
3833 /**
3934 * {@link TypeCodec} that maps {@link Instant} to CQL {@code timestamp}.
@@ -51,13 +46,13 @@
5146 * the ISO formats accepted in CQL.
5247 */
5348 private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
54- .append(ISODateTimeFormat.dateOptionalTimeParser().getParser())
55- .appendOptional(
56- new DateTimeFormatterBuilder()
57- .appendTimeZoneOffset("Z", true, 2, 4)
58- .toParser())
59- .toFormatter()
60- .withZoneUTC();
49+ .append(ISODateTimeFormat.dateOptionalTimeParser().getParser())
50+ .appendOptional(
51+ new DateTimeFormatterBuilder()
52+ .appendTimeZoneOffset("Z", true, 2, 4)
53+ .toParser())
54+ .toFormatter()
55+ .withZoneUTC();
6156
6257 private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ").withZoneUTC();
6358
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/joda/LocalDateCodec.java +9 −15
@@ -15,27 +15,21 @@
1515 */
1616 package com.datastax.driver.extras.codecs.joda;
1717
18-import java.nio.ByteBuffer;
19-
20-import static java.lang.Long.parseLong;
21-
18+import com.datastax.driver.core.DataType;
19+import com.datastax.driver.core.ProtocolVersion;
20+import com.datastax.driver.core.TypeCodec;
21+import com.datastax.driver.core.exceptions.InvalidTypeException;
2222 import org.joda.time.Days;
2323 import org.joda.time.LocalDate;
2424 import org.joda.time.format.DateTimeFormat;
2525 import org.joda.time.format.DateTimeFormatter;
2626
27-import static org.joda.time.Days.daysBetween;
28-
29-import com.datastax.driver.core.*;
30-import com.datastax.driver.core.exceptions.InvalidTypeException;
27+import java.nio.ByteBuffer;
3128
32-import static com.datastax.driver.core.CodecUtils.fromCqlDateToDaysSinceEpoch;
33-import static com.datastax.driver.core.CodecUtils.fromSignedToUnsignedInt;
34-import static com.datastax.driver.core.CodecUtils.fromUnsignedToSignedInt;
35-import static com.datastax.driver.core.ParseUtils.isLongLiteral;
36-import static com.datastax.driver.core.ParseUtils.isQuoted;
37-import static com.datastax.driver.core.ParseUtils.quote;
38-import static com.datastax.driver.core.ParseUtils.unquote;
29+import static com.datastax.driver.core.CodecUtils.*;
30+import static com.datastax.driver.core.ParseUtils.*;
31+import static java.lang.Long.parseLong;
32+import static org.joda.time.Days.daysBetween;
3933
4034 /**
4135 * {@link TypeCodec} that maps
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/joda/LocalTimeCodec.java +9 −11
@@ -15,27 +15,25 @@
1515 */
1616 package com.datastax.driver.extras.codecs.joda;
1717
18-import java.nio.ByteBuffer;
19-
20-import static java.util.concurrent.TimeUnit.MILLISECONDS;
21-import static java.util.concurrent.TimeUnit.NANOSECONDS;
22-
23-import org.joda.time.LocalTime;
24-import org.joda.time.format.DateTimeFormat;
25-import org.joda.time.format.DateTimeFormatter;
26-
2718 import com.datastax.driver.core.DataType;
2819 import com.datastax.driver.core.ParseUtils;
2920 import com.datastax.driver.core.ProtocolVersion;
3021 import com.datastax.driver.core.TypeCodec;
3122 import com.datastax.driver.core.exceptions.InvalidTypeException;
23+import org.joda.time.LocalTime;
24+import org.joda.time.format.DateTimeFormat;
25+import org.joda.time.format.DateTimeFormatter;
26+
27+import java.nio.ByteBuffer;
3228
3329 import static com.datastax.driver.core.ParseUtils.quote;
30+import static java.util.concurrent.TimeUnit.MILLISECONDS;
31+import static java.util.concurrent.TimeUnit.NANOSECONDS;
3432
3533 /**
3634 * {@link TypeCodec} that maps {@link LocalTime} to CQL {@code time} (long representing nanoseconds since midnight).
37- *
38- * <p>
35+ * <p/>
36+ * <p/>
3937 * IMPORTANT: {@link LocalTime} has millisecond precision; nanoseconds below one millisecond will be lost
4038 * during deserialization.
4139 */
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/joda/package-info.java +3 −4
@@ -18,12 +18,12 @@
1818 * This package contains a collection of convenience
1919 * {@link com.datastax.driver.core.TypeCodec TypeCodec} instances useful for
2020 * serializing between CQL types and Joda Time types such as {@link org.joda.time.DateTime}.
21- *
22- * <p>
21+ * <p/>
22+ * <p/>
2323 * Note that classes in this package require the presence of
2424 * <a href="http://www.joda.org/joda-time/">Joda Time library</a> at runtime.
2525 * If you use Maven, this can be done by declaring the following dependency in your project:
26- *
26+ * <p/>
2727 * <pre>{@code
2828 * <dependency>
2929 * <groupId>joda-time</groupId>
@@ -31,6 +31,5 @@
3131 * <version>2.9.1</version>
3232 * </dependency>
3333 * }</pre>
34- *
3534 */
3635 package com.datastax.driver.extras.codecs.joda;
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/json/JacksonJsonCodec.java +15 −16
@@ -15,34 +15,33 @@
1515 */
1616 package com.datastax.driver.extras.codecs.json;
1717
18-import java.io.IOException;
19-import java.nio.ByteBuffer;
20-
21-import com.fasterxml.jackson.core.JsonProcessingException;
22-import com.fasterxml.jackson.databind.JavaType;
23-import com.fasterxml.jackson.databind.ObjectMapper;
24-import com.fasterxml.jackson.databind.type.TypeFactory;
25-
2618 import com.datastax.driver.core.DataType;
2719 import com.datastax.driver.core.ParseUtils;
2820 import com.datastax.driver.core.ProtocolVersion;
2921 import com.datastax.driver.core.TypeCodec;
3022 import com.datastax.driver.core.exceptions.InvalidTypeException;
3123 import com.datastax.driver.core.utils.Bytes;
24+import com.fasterxml.jackson.core.JsonProcessingException;
25+import com.fasterxml.jackson.databind.JavaType;
26+import com.fasterxml.jackson.databind.ObjectMapper;
27+import com.fasterxml.jackson.databind.type.TypeFactory;
28+
29+import java.io.IOException;
30+import java.nio.ByteBuffer;
3231
3332 /**
3433 * A JSON codec that uses the <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a>
3534 * library to perform serialization and deserialization of JSON objects.
36- *
37- * <p>
35+ * <p/>
36+ * <p/>
3837 * This codec maps a single Java object to a single JSON structure at a time;
3938 * mapping of arrays or collections to root-level JSON arrays is not supported,
4039 * but such a codec can be easily crafted after this one.
41- *
42- * <p>
40+ * <p/>
41+ * <p/>
4342 * Note that this codec requires the presence of Jackson library at runtime.
4443 * If you use Maven, this can be done by declaring the following dependency in your project:
45- *
44+ * <p/>
4645 * <pre>{@code
4746 * <dependency>
4847 * <groupId>com.fasterxml.jackson.core</groupId>
@@ -50,7 +49,6 @@
5049 * <version>2.6.3</version>
5150 * </dependency>
5251 * }</pre>
53- *
5452 */
5553 public class JacksonJsonCodec<T> extends TypeCodec<T> {
5654
@@ -77,7 +75,7 @@
7775 if (bytes == null)
7876 return null;
7977 try {
80- return (T)objectMapper.readValue(Bytes.getArray(bytes), toJacksonJavaType());
78+ return (T) objectMapper.readValue(Bytes.getArray(bytes), toJacksonJavaType());
8179 } catch (IOException e) {
8280 throw new InvalidTypeException(e.getMessage(), e);
8381 }
@@ -105,7 +103,7 @@
105103 throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
106104 String json = ParseUtils.unquote(value);
107105 try {
108- return (T)objectMapper.readValue(json, toJacksonJavaType());
106+ return (T) objectMapper.readValue(json, toJacksonJavaType());
109107 } catch (IOException e) {
110108 throw new InvalidTypeException(e.getMessage(), e);
111109 }
@@ -114,6 +112,7 @@
114112 /**
115113 * This method acts as a bridge between Guava's {@link com.google.common.reflect.TypeToken TypeToken} API, which is used
116114 * by the driver, and Jackson's {@link JavaType} API.
115+ *
117116 * @return A {@link JavaType} instance corresponding to the codec's {@link #getJavaType() Java type}.
118117 */
119118 protected JavaType toJacksonJavaType() {
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodec.java +13 −15
@@ -15,12 +15,6 @@
1515 */
1616 package com.datastax.driver.extras.codecs.json;
1717
18-import java.io.*;
19-import java.nio.ByteBuffer;
20-import java.util.Map;
21-
22-import javax.json.*;
23-
2418 import com.datastax.driver.core.DataType;
2519 import com.datastax.driver.core.ParseUtils;
2620 import com.datastax.driver.core.ProtocolVersion;
@@ -28,26 +22,31 @@
2822 import com.datastax.driver.core.exceptions.InvalidTypeException;
2923 import com.datastax.driver.core.utils.Bytes;
3024
25+import javax.json.*;
26+import java.io.*;
27+import java.nio.ByteBuffer;
28+import java.util.Map;
29+
3130 /**
3231 * A JSON codec that uses the
3332 * <a href="https://jcp.org/en/jsr/detail?id=353">Java API for JSON processing</a>
3433 * to perform serialization and deserialization of JSON structures.
35- * <p>
34+ * <p/>
3635 * More specifically, this codec maps an arbitrary {@link JsonStructure} to
3736 * a CQL {@code varchar} column.
38- * <p>
37+ * <p/>
3938 * This codec handles the Java type {@link JsonStructure}.
4039 * It is therefore required that values are set and retrieved using that exact Java type;
4140 * users should manually downcast to either {@link JsonObject} or {@link JsonArray},
4241 * as in the example below:
4342 * <pre>{@code
44- *
43+ * <p/>
4544 * // setting values
4645 * JsonObject myObject = ...
4746 * PreparedStatement ps = ...
4847 * // set values using JsonStructure as target Java type
4948 * BoundStatement bs = ps.bind().set(1, myObject, JsonStructure.class);
50- *
49+ * <p/>
5150 * // retrieving values
5251 * Row row = session.execute(bs).one();
5352 * // use JsonStructure as target Java type to retrieve values
@@ -57,27 +56,26 @@
5756 * ...
5857 * }
5958 * }</pre>
60- *
61- * <p>
59+ * <p/>
60+ * <p/>
6261 * Note that at runtime, this codec requires the presence of both JSR-353 API
6362 * and a JSR-353-compatible runtime library, such as
6463 * <a href="https://jsonp.java.net/download.html">JSR-353's reference implementation</a>.
6564 * If you use Maven, this can be done by declaring the following dependencies in your project:
66- *
65+ * <p/>
6766 * <pre>{@code
6867 * <dependency>
6968 * <groupId>javax.json</groupId>
7069 * <artifactId>javax.json-api</artifactId>
7170 * <version>1.0</version>
7271 * </dependency>
73- *
72+ * <p/>
7473 * <dependency>
7574 * <groupId>org.glassfish</groupId>
7675 * <artifactId>javax.json</artifactId>
7776 * <version>1.0.4</version>
7877 * </dependency>
7978 * }</pre>
80- *
8179 */
8280 public class Jsr353JsonCodec extends TypeCodec<JsonStructure> {
8381
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/package-info.java +33 −33
@@ -16,40 +16,40 @@
1616
1717 /**
1818 * This package and its subpackages contain several convenience {@link com.datastax.driver.core.TypeCodec TypeCodec}s.
19- *
19+ * <p/>
2020 * <table summary="Supported Mappings">
21- * <tr>
22- * <th>Package</th>
23- * <th>Description</th>
24- * </tr>
25- * <tr>
26- * <td>{@link com.datastax.driver.extras.codecs.arrays}</td>
27- * <td>codecs mapping CQL lists to Java arrays.</td>
28- * </tr>
29- * <tr>
30- * <td>{@link com.datastax.driver.extras.codecs.date}</td>
31- * <td>codecs mapping CQL temporal types to Java primitive types.</td>
32- * </tr>
33- * <tr>
34- * <td>{@link com.datastax.driver.extras.codecs.enums}</td>
35- * <td>codecs mapping CQL types to Java enums.</td>
36- * </tr>
37- * <tr>
38- * <td>{@link com.datastax.driver.extras.codecs.guava}</td>
39- * <td>codecs mapping CQL types to Guava-specific Java types.</td>
40- * </tr>
41- * <tr>
42- * <td>{@link com.datastax.driver.extras.codecs.jdk8}</td>
43- * <td>codecs mapping CQL types to Java 8 types, including {@code java.time} API and {@code java.util.Optional}.</td>
44- * </tr>
45- * <tr>
46- * <td>{@link com.datastax.driver.extras.codecs.joda}</td>
47- * <td>codecs mapping CQL types to Joda Time types.</td>
48- * </tr>
49- * <tr>
50- * <td>{@link com.datastax.driver.extras.codecs.json}</td>
51- * <td>codecs mapping CQL varchars to JSON structures.</td>
52- * </tr>
21+ * <tr>
22+ * <th>Package</th>
23+ * <th>Description</th>
24+ * </tr>
25+ * <tr>
26+ * <td>{@link com.datastax.driver.extras.codecs.arrays}</td>
27+ * <td>codecs mapping CQL lists to Java arrays.</td>
28+ * </tr>
29+ * <tr>
30+ * <td>{@link com.datastax.driver.extras.codecs.date}</td>
31+ * <td>codecs mapping CQL temporal types to Java primitive types.</td>
32+ * </tr>
33+ * <tr>
34+ * <td>{@link com.datastax.driver.extras.codecs.enums}</td>
35+ * <td>codecs mapping CQL types to Java enums.</td>
36+ * </tr>
37+ * <tr>
38+ * <td>{@link com.datastax.driver.extras.codecs.guava}</td>
39+ * <td>codecs mapping CQL types to Guava-specific Java types.</td>
40+ * </tr>
41+ * <tr>
42+ * <td>{@link com.datastax.driver.extras.codecs.jdk8}</td>
43+ * <td>codecs mapping CQL types to Java 8 types, including {@code java.time} API and {@code java.util.Optional}.</td>
44+ * </tr>
45+ * <tr>
46+ * <td>{@link com.datastax.driver.extras.codecs.joda}</td>
47+ * <td>codecs mapping CQL types to Joda Time types.</td>
48+ * </tr>
49+ * <tr>
50+ * <td>{@link com.datastax.driver.extras.codecs.json}</td>
51+ * <td>codecs mapping CQL varchars to JSON structures.</td>
52+ * </tr>
5353 * </table>
5454 */
5555 package com.datastax.driver.extras.codecs;
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/arrays/ArrayCodecsTest.java +50 −51
@@ -15,82 +15,81 @@
1515 */
1616 package com.datastax.driver.extras.codecs.arrays;
1717
18-import java.util.Collection;
19-import java.util.List;
20-
21-import com.google.common.collect.Lists;
22-import com.google.common.primitives.Primitives;
23-import org.testng.annotations.DataProvider;
24-import org.testng.annotations.Test;
25-
26-import static org.assertj.core.api.Assertions.assertThat;
27-
2818 import com.datastax.driver.core.*;
2919 import com.datastax.driver.mapping.Mapper;
3020 import com.datastax.driver.mapping.MappingManager;
3121 import com.datastax.driver.mapping.annotations.Column;
3222 import com.datastax.driver.mapping.annotations.PartitionKey;
3323 import com.datastax.driver.mapping.annotations.Table;
24+import com.google.common.collect.Lists;
25+import com.google.common.primitives.Primitives;
26+import org.testng.annotations.DataProvider;
27+import org.testng.annotations.Test;
28+
29+import java.util.Collection;
30+import java.util.List;
31+
32+import static org.assertj.core.api.Assertions.assertThat;
3433
3534 public class ArrayCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
3635
3736 private static final ObjectArrayCodec<String> stringArrayCodec = new ObjectArrayCodec<String>(
38- DataType.list(DataType.varchar()),
39- String[].class,
40- TypeCodec.varchar());
37+ DataType.list(DataType.varchar()),
38+ String[].class,
39+ TypeCodec.varchar());
4140
4241 @Override
4342 protected Collection<String> getTableDefinitions() {
4443 return Lists.newArrayList(
45- "CREATE TABLE lists ("
46- + "pk int PRIMARY KEY, "
47- + "l_int list<int>, "
48- + "l_bigint list<bigint>, "
49- + "l_float list<float>, "
50- + "l_double list<double>, "
51- + "l_string list<text> "
52- + ")",
53- "INSERT INTO lists (pk, l_int, l_bigint, l_float, l_double, l_string) VALUES (1, "
54- + "[1, 2, 3], "
55- + "[4, 5, 6], "
56- + "[1.0, 2.0, 3.0], "
57- + "[4.0, 5.0, 6.0], "
58- + "['a', 'b', 'c'] "
59- + ")"
44+ "CREATE TABLE lists ("
45+ + "pk int PRIMARY KEY, "
46+ + "l_int list<int>, "
47+ + "l_bigint list<bigint>, "
48+ + "l_float list<float>, "
49+ + "l_double list<double>, "
50+ + "l_string list<text> "
51+ + ")",
52+ "INSERT INTO lists (pk, l_int, l_bigint, l_float, l_double, l_string) VALUES (1, "
53+ + "[1, 2, 3], "
54+ + "[4, 5, 6], "
55+ + "[1.0, 2.0, 3.0], "
56+ + "[4.0, 5.0, 6.0], "
57+ + "['a', 'b', 'c'] "
58+ + ")"
6059 );
6160 }
6261
6362 @Override
6463 protected Cluster.Builder configure(Cluster.Builder builder) {
6564 return builder.withCodecRegistry(
66- new CodecRegistry()
67- .register(IntArrayCodec.instance)
68- .register(LongArrayCodec.instance)
69- .register(FloatArrayCodec.instance)
70- .register(DoubleArrayCodec.instance)
71- .register(stringArrayCodec)
65+ new CodecRegistry()
66+ .register(IntArrayCodec.instance)
67+ .register(LongArrayCodec.instance)
68+ .register(FloatArrayCodec.instance)
69+ .register(DoubleArrayCodec.instance)
70+ .register(stringArrayCodec)
7271 );
7372 }
7473
7574 @DataProvider(name = "ArrayCodecsTest-serializing")
7675 public static Object[][] parametersForSerializationTests() {
7776 return new Object[][]{
78- { "l_int", int[].class, new int[]{ 1, 2, 3 } },
79- { "l_bigint", long[].class, new long[]{ 4, 5, 6 } },
80- { "l_float", float[].class, new float[]{ 1, 2, 3 } },
81- { "l_double", double[].class, new double[]{ 4, 5, 6 } },
82- { "l_string", String[].class, new String[]{ "a", "b", "c" } }
77+ {"l_int", int[].class, new int[]{1, 2, 3}},
78+ {"l_bigint", long[].class, new long[]{4, 5, 6}},
79+ {"l_float", float[].class, new float[]{1, 2, 3}},
80+ {"l_double", double[].class, new double[]{4, 5, 6}},
81+ {"l_string", String[].class, new String[]{"a", "b", "c"}}
8382 };
8483 }
8584
8685 @DataProvider(name = "ArrayCodecsTest-formatting")
8786 public static Object[][] parametersForFormattingTests() {
8887 return new Object[][]{
89- { new IntArrayCodec(), new int[]{ 1, 2, 3 }, new int[0], "[1,2,3]" },
90- { new LongArrayCodec(), new long[]{ 4, 5, 6 }, new long[0], "[4,5,6]" },
91- { new FloatArrayCodec(), new float[]{ 1, 2, 3 }, new float[0], "[1.0,2.0,3.0]" },
92- { new DoubleArrayCodec(), new double[]{ 4, 5, 6 }, new double[0], "[4.0,5.0,6.0]" },
93- { stringArrayCodec, new String[]{ "a", "b", "c" }, new String[0], "['a','b','c']" }
88+ {new IntArrayCodec(), new int[]{1, 2, 3}, new int[0], "[1,2,3]"},
89+ {new LongArrayCodec(), new long[]{4, 5, 6}, new long[0], "[4,5,6]"},
90+ {new FloatArrayCodec(), new float[]{1, 2, 3}, new float[0], "[1.0,2.0,3.0]"},
91+ {new DoubleArrayCodec(), new double[]{4, 5, 6}, new double[0], "[4.0,5.0,6.0]"},
92+ {stringArrayCodec, new String[]{"a", "b", "c"}, new String[0], "['a','b','c']"}
9493 };
9594 }
9695
@@ -105,8 +104,8 @@
105104 public <A> void should_set_list_column_with_array(String columnName, Class<A> arrayClass, A expected) {
106105 PreparedStatement ps = session.prepare(String.format("INSERT INTO lists (pk, %s) VALUES (?, ?)", columnName));
107106 BoundStatement bs = ps.bind()
108- .setInt(0, 2)
109- .set(columnName, expected, arrayClass);
107+ .setInt(0, 2)
108+ .set(columnName, expected, arrayClass);
110109 session.execute(bs);
111110 Row row = session.execute(String.format("SELECT %s FROM lists WHERE pk = 2", columnName)).one();
112111 List<?> list = row.getList(columnName, Primitives.wrap(arrayClass.getComponentType()));
@@ -166,11 +165,11 @@
166165
167166 public Mapped() {
168167 pk = 42;
169- strings = new String[]{ "a", "b", "c" };
170- ints = new int[]{ 1, 2, 3 };
171- longs = new long[]{ 4, 5, 6 };
172- floats = new float[]{ 1, 2, 3 };
173- doubles = new double[]{ 4, 5, 6 };
168+ strings = new String[]{"a", "b", "c"};
169+ ints = new int[]{1, 2, 3};
170+ longs = new long[]{4, 5, 6};
171+ floats = new float[]{1, 2, 3};
172+ doubles = new double[]{4, 5, 6};
174173 }
175174
176175 public int getPk() {
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/date/SimpleDateCodecTest.java +18 −19
@@ -15,44 +15,43 @@
1515 */
1616 package com.datastax.driver.extras.codecs.date;
1717
18-import java.text.ParseException;
19-
20-import static java.util.concurrent.TimeUnit.MILLISECONDS;
21-
2218 import org.testng.annotations.DataProvider;
2319 import org.testng.annotations.Test;
2420
21+import java.text.ParseException;
22+
2523 import static com.datastax.driver.core.Assertions.assertThat;
2624 import static com.datastax.driver.core.CodecUtils.fromCqlDateToDaysSinceEpoch;
2725 import static com.datastax.driver.core.ParseUtils.parseDate;
2826 import static com.datastax.driver.core.ProtocolVersion.V4;
27+import static java.util.concurrent.TimeUnit.MILLISECONDS;
2928
3029 public class SimpleDateCodecTest {
3130
3231 @DataProvider(name = "SimpleDateCodecTest.parse")
3332 public Object[][] parseParameters() throws ParseException {
34- int _2014_01_01 = (int)MILLISECONDS.toDays(parseDate("2014-01-01", "yyyy-MM-dd").getTime());
33+ int _2014_01_01 = (int) MILLISECONDS.toDays(parseDate("2014-01-01", "yyyy-MM-dd").getTime());
3534 return new Object[][]{
36- { null , null },
37- { "" , null },
38- { "NULL" , null },
39- { "0" , fromCqlDateToDaysSinceEpoch(0) },
40- { "'2147483648'" , 0 },
41- // SimpleDateFormat is unable to parse year -5877641
42- //{ "'-5877641-06-23'" , fromCqlDateToDaysSinceEpoch(0) },
43- { "'1970-01-01'" , 0 },
44- { "'2014-01-01'" , _2014_01_01 }
35+ {null, null},
36+ {"", null},
37+ {"NULL", null},
38+ {"0", fromCqlDateToDaysSinceEpoch(0)},
39+ {"'2147483648'", 0},
40+ // SimpleDateFormat is unable to parse year -5877641
41+ //{ "'-5877641-06-23'" , fromCqlDateToDaysSinceEpoch(0) },
42+ {"'1970-01-01'", 0},
43+ {"'2014-01-01'", _2014_01_01}
4544 };
4645 }
4746
4847 @DataProvider(name = "SimpleDateCodecTest.format")
4948 public Object[][] formatParameters() throws ParseException {
50- int _2014_01_01 = (int)MILLISECONDS.toDays(parseDate("2014-01-01", "yyyy-MM-dd").getTime());
49+ int _2014_01_01 = (int) MILLISECONDS.toDays(parseDate("2014-01-01", "yyyy-MM-dd").getTime());
5150 return new Object[][]{
52- { null , "NULL" },
53- { fromCqlDateToDaysSinceEpoch(0), "'0'" },
54- { 0 , "'2147483648'" },
55- { _2014_01_01 , "'2147499719'" }
51+ {null, "NULL"},
52+ {fromCqlDateToDaysSinceEpoch(0), "'0'"},
53+ {0, "'2147483648'"},
54+ {_2014_01_01, "'2147499719'"}
5655 };
5756 }
5857
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/date/SimpleDateCodecsTest.java +22 −24
@@ -15,23 +15,21 @@
1515 */
1616 package com.datastax.driver.extras.codecs.date;
1717
18-import java.util.*;
19-
20-import com.google.common.collect.ImmutableMap;
21-import org.testng.annotations.BeforeClass;
22-import org.testng.annotations.Test;
23-
24-import static com.google.common.collect.Lists.newArrayList;
25-import static org.assertj.core.api.Assertions.assertThat;
26-
2718 import com.datastax.driver.core.*;
28-import com.datastax.driver.core.LocalDate;
2919 import com.datastax.driver.core.utils.CassandraVersion;
3020 import com.datastax.driver.mapping.Mapper;
3121 import com.datastax.driver.mapping.MappingManager;
3222 import com.datastax.driver.mapping.annotations.Column;
3323 import com.datastax.driver.mapping.annotations.PartitionKey;
3424 import com.datastax.driver.mapping.annotations.Table;
25+import com.google.common.collect.ImmutableMap;
26+import org.testng.annotations.BeforeClass;
27+import org.testng.annotations.Test;
28+
29+import java.util.*;
30+
31+import static com.google.common.collect.Lists.newArrayList;
32+import static org.assertj.core.api.Assertions.assertThat;
3533
3634 @CassandraVersion(major = 2.2)
3735 public class SimpleDateCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -39,21 +37,21 @@
3937 @Override
4038 protected Collection<String> getTableDefinitions() {
4139 return Collections.singletonList(
42- "CREATE TABLE IF NOT EXISTS foo ("
43- + "c1 text PRIMARY KEY, "
44- + "cdate date, "
45- + "ctimestamp timestamp, "
46- + "cdates frozen<list<date>>, "
47- + "ctimestamps frozen<map<text,timestamp>> "
48- + ")");
40+ "CREATE TABLE IF NOT EXISTS foo ("
41+ + "c1 text PRIMARY KEY, "
42+ + "cdate date, "
43+ + "ctimestamp timestamp, "
44+ + "cdates frozen<list<date>>, "
45+ + "ctimestamps frozen<map<text,timestamp>> "
46+ + ")");
4947 }
5048
5149 @BeforeClass(groups = "short")
5250 public void registerCodecs() throws Exception {
5351 CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
5452 codecRegistry
55- .register(SimpleDateCodec.instance)
56- .register(SimpleTimestampCodec.instance);
53+ .register(SimpleDateCodec.instance)
54+ .register(SimpleTimestampCodec.instance);
5755 }
5856
5957
@@ -67,7 +65,7 @@
6765 * @expected_result properly maps.
6866 * @since 2.2.0
6967 */
70- @Test(groups="short")
68+ @Test(groups = "short")
7169 public void should_map_date_to_days_since_epoch() {
7270 // given
7371 int days = 12345;
@@ -96,7 +94,7 @@
9694 * @expected_result properly maps.
9795 * @since 2.2.0
9896 */
99- @Test(groups="short")
97+ @Test(groups = "short")
10098 public void should_map_timestamp_to_millis_since_epoch() {
10199 // given
102100 long millis = new Date().getTime();
@@ -142,17 +140,17 @@
142140 private int days;
143141
144142 @Column(name = "ctimestamps")
145- private Map<String,Long> mapOfMillis;
143+ private Map<String, Long> mapOfMillis;
146144
147145 @Column(name = "cdates")
148146 private List<Integer> listOfDays;
149147
150- public Mapped(){
148+ public Mapped() {
151149 c1 = "mapper";
152150 millis = 123456;
153151 days = 123;
154152 mapOfMillis = ImmutableMap.of("foo", 123456L);
155- listOfDays = newArrayList(123,456);
153+ listOfDays = newArrayList(123, 456);
156154 }
157155
158156 public String getC1() {
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/date/SimpleTimestampCodecTest.java +15 −15
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.extras.codecs.date;
1717
18-import java.text.ParseException;
19-
2018 import org.testng.annotations.DataProvider;
2119 import org.testng.annotations.Test;
2220
21+import java.text.ParseException;
22+
2323 import static com.datastax.driver.core.Assertions.assertThat;
2424 import static com.datastax.driver.core.ParseUtils.parseDate;
2525 import static com.datastax.driver.core.ProtocolVersion.V4;
@@ -29,25 +29,25 @@
2929 @DataProvider(name = "SimpleTimestampCodecTest.parse")
3030 public Object[][] parseParameters() throws ParseException {
3131 return new Object[][]{
32- { null , null },
33- { "" , null },
34- { "NULL" , null },
35- { "0" , 0L },
36- { "'2010-06-30T01:20'" , parseDate("2010-06-30T01:20:00.000Z").getTime() },
37- { "'2010-06-30T01:20Z'" , parseDate("2010-06-30T01:20:00.000Z").getTime() },
38- { "'2010-06-30T01:20:47'" , parseDate("2010-06-30T01:20:47.000Z").getTime() },
39- { "'2010-06-30T01:20:47+01:00'" , parseDate("2010-06-30T00:20:47.000Z").getTime() },
40- { "'2010-06-30T01:20:47.999'" , parseDate("2010-06-30T01:20:47.999Z").getTime() },
41- { "'2010-06-30T01:20:47.999+01:00'" , parseDate("2010-06-30T00:20:47.999Z").getTime() }
32+ {null, null},
33+ {"", null},
34+ {"NULL", null},
35+ {"0", 0L},
36+ {"'2010-06-30T01:20'", parseDate("2010-06-30T01:20:00.000Z").getTime()},
37+ {"'2010-06-30T01:20Z'", parseDate("2010-06-30T01:20:00.000Z").getTime()},
38+ {"'2010-06-30T01:20:47'", parseDate("2010-06-30T01:20:47.000Z").getTime()},
39+ {"'2010-06-30T01:20:47+01:00'", parseDate("2010-06-30T00:20:47.000Z").getTime()},
40+ {"'2010-06-30T01:20:47.999'", parseDate("2010-06-30T01:20:47.999Z").getTime()},
41+ {"'2010-06-30T01:20:47.999+01:00'", parseDate("2010-06-30T00:20:47.999Z").getTime()}
4242 };
4343 }
4444
4545 @DataProvider(name = "SimpleTimestampCodecTest.format")
4646 public Object[][] formatParameters() throws ParseException {
4747 return new Object[][]{
48- { null , "NULL" },
49- { 0L , "'0'" },
50- { 123456L, "'123456'" }
48+ {null, "NULL"},
49+ {0L, "'0'"},
50+ {123456L, "'123456'"}
5151 };
5252 }
5353
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/enums/EnumCodecsTest.java +60 −53
@@ -15,25 +15,20 @@
1515 */
1616 package com.datastax.driver.extras.codecs.enums;
1717
18-import java.util.Collection;
19-import java.util.List;
20-import java.util.Map;
21-import java.util.Set;
22-
23-import com.google.common.collect.ImmutableMap;
24-import com.google.common.reflect.TypeToken;
25-import org.testng.annotations.BeforeMethod;
26-import org.testng.annotations.Test;
27-
28-import static com.google.common.collect.Lists.newArrayList;
29-import static com.google.common.collect.Sets.newHashSet;
30-import static org.assertj.core.api.Assertions.assertThat;
31-
3218 import com.datastax.driver.core.*;
3319 import com.datastax.driver.core.utils.CassandraVersion;
3420 import com.datastax.driver.mapping.Mapper;
3521 import com.datastax.driver.mapping.MappingManager;
3622 import com.datastax.driver.mapping.annotations.*;
23+import com.google.common.collect.ImmutableMap;
24+import com.google.common.reflect.TypeToken;
25+import org.testng.annotations.BeforeMethod;
26+import org.testng.annotations.Test;
27+
28+import java.util.Collection;
29+import java.util.List;
30+import java.util.Map;
31+import java.util.Set;
3732
3833 import static com.datastax.driver.core.DataType.cint;
3934 import static com.datastax.driver.core.DataType.text;
@@ -41,13 +36,16 @@
4136 import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Bar.BAR_2;
4237 import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Foo.FOO_1;
4338 import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Foo.FOO_2;
39+import static com.google.common.collect.Lists.newArrayList;
40+import static com.google.common.collect.Sets.newHashSet;
41+import static org.assertj.core.api.Assertions.assertThat;
4442
4543 /**
4644 * A test that validates that Enums are correctly mapped to varchars (with EnumNameCodec)
4745 * and ints (with EnumOrdinalCodec).
4846 * It also validates that both codecs may coexist in the same CodecRegistry.
4947 */
50-@CassandraVersion(major=2.1)
48+@CassandraVersion(major = 2.1)
5149 public class EnumCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
5250
5351 private final String insertQuery = "INSERT INTO t1 (pk, foo, foos, bar, bars, foobars, tup, udt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
@@ -65,41 +63,41 @@
6563 @Override
6664 protected Collection<String> getTableDefinitions() {
6765 return newArrayList(
68- "CREATE TYPE IF NOT EXISTS udt1 ("
69- + "foo int,"
70- + "bar text)",
71- "CREATE TABLE IF NOT EXISTS t1 ("
72- + "pk int, "
73- + "foo int, "
74- + "foos list<int>, "
75- + "bar text, "
76- + "bars set<text>, "
77- + "foobars map<int,text>, "
78- + "tup frozen<tuple<int,varchar>>, "
79- + "udt frozen<udt1>,"
80- + "primary key (pk, foo))"
66+ "CREATE TYPE IF NOT EXISTS udt1 ("
67+ + "foo int,"
68+ + "bar text)",
69+ "CREATE TABLE IF NOT EXISTS t1 ("
70+ + "pk int, "
71+ + "foo int, "
72+ + "foos list<int>, "
73+ + "bar text, "
74+ + "bars set<text>, "
75+ + "foobars map<int,text>, "
76+ + "tup frozen<tuple<int,varchar>>, "
77+ + "udt frozen<udt1>,"
78+ + "primary key (pk, foo))"
8179 );
8280 }
8381
8482 @Override
8583 protected Cluster.Builder configure(Cluster.Builder builder) {
8684 return builder.withCodecRegistry(
87- new CodecRegistry()
88- .register(new EnumOrdinalCodec<Foo>(Foo.class))
89- .register(new EnumNameCodec<Bar>(Bar.class))
85+ new CodecRegistry()
86+ .register(new EnumOrdinalCodec<Foo>(Foo.class))
87+ .register(new EnumNameCodec<Bar>(Bar.class))
9088 );
9189 }
9290
93- @BeforeMethod(groups="short")
91+ @BeforeMethod(groups = "short")
9492 public void before() {
9593 TupleType tup = cluster.getMetadata().newTupleType(cint(), text());
9694 tupleValue = tup.newValue()
97- .set(0, FOO_1, Foo.class)
98- .set(1, BAR_1, Bar.class);
95+ .set(0, FOO_1, Foo.class)
96+ .set(1, BAR_1, Bar.class);
9997 UserType udt = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt1");
10098 udtValue = udt.newValue()
101- .set("foo", FOO_1, Foo.class)
102- .set("bar", BAR_1, Bar.class);
99+ .set("foo", FOO_1, Foo.class)
100+ .set("bar", BAR_1, Bar.class);
103101 }
104102
105103 @Test(groups = "short")
@@ -122,18 +120,19 @@
122120 @Test(groups = "short")
123121 public void should_use_enum_codecs_with_prepared_statements_2() {
124122 session.execute(session.prepare(insertQuery).bind()
125- .setInt(0, pk)
126- .set(1, FOO_1, Foo.class)
127- .setList(2, foos, Foo.class)
128- .set(3, BAR_1, Bar.class)
129- .set(4, bars, new TypeToken<Set<Bar>>(){})
130- .setMap(5, foobars, Foo.class, Bar.class)
131- .setTupleValue(6, tupleValue)
132- .setUDTValue(7, udtValue)
123+ .setInt(0, pk)
124+ .set(1, FOO_1, Foo.class)
125+ .setList(2, foos, Foo.class)
126+ .set(3, BAR_1, Bar.class)
127+ .set(4, bars, new TypeToken<Set<Bar>>() {
128+ })
129+ .setMap(5, foobars, Foo.class, Bar.class)
130+ .setTupleValue(6, tupleValue)
131+ .setUDTValue(7, udtValue)
133132 );
134133 PreparedStatement ps = session.prepare(selectQuery);
135134 ResultSet rows = session.execute(ps.bind()
136- .setInt(0, pk)
135+ .setInt(0, pk)
137136 );
138137 Row row = rows.one();
139138 assertRow(row);
@@ -200,8 +199,10 @@
200199 assertThat(row.getObject(2)).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal())); // uses the built-in ListCodec(IntCodec) because CQL type is list<int>
201200 assertThat(row.getList(2, Integer.class)).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal()));
202201 assertThat(row.getList("foos", Foo.class)).isEqualTo(newArrayList(FOO_1, FOO_2));
203- assertThat(row.get(2, new TypeToken<List<Integer>>(){})).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal()));
204- assertThat(row.get("foos", new TypeToken<List<Foo>>(){})).isEqualTo(newArrayList(FOO_1, FOO_2));
202+ assertThat(row.get(2, new TypeToken<List<Integer>>() {
203+ })).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal()));
204+ assertThat(row.get("foos", new TypeToken<List<Foo>>() {
205+ })).isEqualTo(newArrayList(FOO_1, FOO_2));
205206
206207 assertThat(row.getObject(3)).isEqualTo(BAR_1.name()); // uses the built-in VarcharCodec because CQL type is varchar
207208 assertThat(row.getString("bar")).isEqualTo(BAR_1.name()); // forces VarcharCodec
@@ -211,8 +212,10 @@
211212 assertThat(row.getObject(4)).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name())); // uses the built-in SetCodec(VarcharCodec) because CQL type is set<varchar>
212213 assertThat(row.getSet(4, String.class)).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name()));
213214 assertThat(row.getSet("bars", Bar.class)).isEqualTo(newHashSet(BAR_1, BAR_2));
214- assertThat(row.get(4, new TypeToken<Set<String>>(){})).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name()));
215- assertThat(row.get("bars", new TypeToken<Set<Bar>>(){})).isEqualTo(newHashSet(BAR_1, BAR_2));
215+ assertThat(row.get(4, new TypeToken<Set<String>>() {
216+ })).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name()));
217+ assertThat(row.get("bars", new TypeToken<Set<Bar>>() {
218+ })).isEqualTo(newHashSet(BAR_1, BAR_2));
216219
217220 // uses default built-in codec MapCodec(IntCodec, VarcharCodec) because CQL type is map<int, varchar>
218221 assertThat(row.getObject(5)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
@@ -224,10 +227,14 @@
224227 assertThat(row.getMap(5, Foo.class, Bar.class)).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2));
225228
226229 // get + TypeToken with combinations of built-in or EnumX codecs
227- assertThat(row.get("foobars", new TypeToken<Map<Integer, String>>(){})).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
228- assertThat(row.get("foobars", new TypeToken<Map<Foo, String>>(){})).isEqualTo(ImmutableMap.of(FOO_1, BAR_1.name(), FOO_2, BAR_2.name()));
229- assertThat(row.get("foobars", new TypeToken<Map<Integer, Bar>>(){})).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1, FOO_2.ordinal(), BAR_2));
230- assertThat(row.get("foobars", new TypeToken<Map<Foo, Bar>>(){})).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2));
230+ assertThat(row.get("foobars", new TypeToken<Map<Integer, String>>() {
231+ })).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
232+ assertThat(row.get("foobars", new TypeToken<Map<Foo, String>>() {
233+ })).isEqualTo(ImmutableMap.of(FOO_1, BAR_1.name(), FOO_2, BAR_2.name()));
234+ assertThat(row.get("foobars", new TypeToken<Map<Integer, Bar>>() {
235+ })).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1, FOO_2.ordinal(), BAR_2));
236+ assertThat(row.get("foobars", new TypeToken<Map<Foo, Bar>>() {
237+ })).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2));
231238
232239 assertThat(row.getTupleValue(6).getInt(0)).isEqualTo(FOO_1.ordinal());
233240 assertThat(row.get(6, TupleValue.class).get(0, Foo.class)).isEqualTo(FOO_1);
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/guava/OptionalCodecTest.java +17 −25
@@ -15,31 +15,23 @@
1515 */
1616 package com.datastax.driver.extras.codecs.guava;
1717
18-import java.math.BigDecimal;
19-import java.util.Collection;
20-import java.util.Collections;
21-import java.util.List;
22-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
20+import com.datastax.driver.core.querybuilder.BuiltStatement;
21+import com.datastax.driver.core.utils.CassandraVersion;
2322 import com.google.common.base.Optional;
2423 import com.google.common.collect.Lists;
2524 import org.testng.annotations.BeforeMethod;
2625 import org.testng.annotations.Test;
2726
28-import static org.assertj.core.api.Assertions.assertThat;
29-
30-import com.datastax.driver.core.*;
31-import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
32-import com.datastax.driver.core.querybuilder.BuiltStatement;
33-import com.datastax.driver.core.utils.CassandraVersion;
27+import java.math.BigDecimal;
28+import java.util.Collection;
29+import java.util.Collections;
30+import java.util.List;
3431
35-import static com.datastax.driver.core.TypeCodec.bigint;
36-import static com.datastax.driver.core.TypeCodec.decimal;
37-import static com.datastax.driver.core.TypeCodec.list;
38-import static com.datastax.driver.core.TypeCodec.varchar;
39-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
40-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
41-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
42-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
32+import static com.datastax.driver.core.TypeCodec.*;
33+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
34+import static org.assertj.core.api.Assertions.assertThat;
4335
4436 public class OptionalCodecTest extends PerClassSingleNodeCluster {
4537
@@ -79,8 +71,8 @@
7971 * @jira_ticket JAVA-846
8072 * @since 2.2.0
8173 */
82- @Test(groups="short")
83- @CassandraVersion(major=2.2)
74+ @Test(groups = "short")
75+ @CassandraVersion(major = 2.2)
8476 public void should_map_unset_value_to_absent() {
8577 PreparedStatement insertPrep = session.prepare(this.insertStmt);
8678 PreparedStatement selectPrep = session.prepare(this.selectStmt);
@@ -109,7 +101,7 @@
109101 * @jira_ticket JAVA-846
110102 * @since 2.2.0
111103 */
112- @Test(groups="short")
104+ @Test(groups = "short")
113105 public void should_map_absent_null_value_to_absent() {
114106 PreparedStatement insertPrep = session.prepare(this.insertStmt);
115107 PreparedStatement selectPrep = session.prepare(this.selectStmt);
@@ -141,7 +133,7 @@
141133 * @jira_ticket JAVA-846
142134 * @since 2.2.0
143135 */
144- @Test(groups="short")
136+ @Test(groups = "short")
145137 public void should_map_some_back_to_itself() {
146138 PreparedStatement insertPrep = session.prepare(this.insertStmt);
147139 PreparedStatement selectPrep = session.prepare(this.selectStmt);
@@ -169,7 +161,7 @@
169161 assertThat(returnData.get()).isEqualTo(data);
170162 }
171163
172- @Test(groups="short")
164+ @Test(groups = "short")
173165 public void should_map_a_primitive_type_to_absent() {
174166 OptionalCodec<Long> optionalLongCodec = new OptionalCodec<Long>(bigint());
175167 cluster.getConfiguration().getCodecRegistry().register(optionalLongCodec);
@@ -193,7 +185,7 @@
193185 assertThat(row.get("c4", Long.class)).isNull();
194186 }
195187
196- @Test(groups="short")
188+ @Test(groups = "short")
197189 public void should_map_a_nullable_type_to_absent() {
198190 OptionalCodec<BigDecimal> optionalDecimalCodec = new OptionalCodec<BigDecimal>(decimal());
199191 cluster.getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/InstantCodecTest.java +18 −20
@@ -15,43 +15,41 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18-import java.time.Instant;
19-import java.time.ZonedDateTime;
20-
18+import com.datastax.driver.core.Assertions;
2119 import org.testng.annotations.DataProvider;
2220 import org.testng.annotations.Test;
2321
24-import static org.assertj.core.api.Assertions.assertThat;
25-
26-import com.datastax.driver.core.Assertions;
22+import java.time.Instant;
23+import java.time.ZonedDateTime;
2724
2825 import static com.datastax.driver.core.ProtocolVersion.V4;
26+import static org.assertj.core.api.Assertions.assertThat;
2927
3028 public class InstantCodecTest {
3129
3230 @DataProvider(name = "InstantCodecTest.parse")
3331 public Object[][] parseParameters() {
3432 return new Object[][]{
35- { null , null },
36- { "" , null },
37- { "NULL" , null },
38- { "0" , Instant.ofEpochMilli(0) },
39- { "1277860847999" , Instant.ofEpochMilli(1277860847999L) },
40- { "'2010-06-30T01:20'" , Instant.parse("2010-06-30T01:20:00.000Z") },
41- { "'2010-06-30T01:20Z'" , Instant.parse("2010-06-30T01:20:00.000Z") },
42- { "'2010-06-30T01:20:47'" , Instant.parse("2010-06-30T01:20:47.000Z") },
43- { "'2010-06-30T01:20:47+01:00'" , Instant.parse("2010-06-30T00:20:47.000Z") },
44- { "'2010-06-30T01:20:47.999'" , Instant.parse("2010-06-30T01:20:47.999Z") },
45- { "'2010-06-30T01:20:47.999+01:00'" , Instant.parse("2010-06-30T00:20:47.999Z") }
33+ {null, null},
34+ {"", null},
35+ {"NULL", null},
36+ {"0", Instant.ofEpochMilli(0)},
37+ {"1277860847999", Instant.ofEpochMilli(1277860847999L)},
38+ {"'2010-06-30T01:20'", Instant.parse("2010-06-30T01:20:00.000Z")},
39+ {"'2010-06-30T01:20Z'", Instant.parse("2010-06-30T01:20:00.000Z")},
40+ {"'2010-06-30T01:20:47'", Instant.parse("2010-06-30T01:20:47.000Z")},
41+ {"'2010-06-30T01:20:47+01:00'", Instant.parse("2010-06-30T00:20:47.000Z")},
42+ {"'2010-06-30T01:20:47.999'", Instant.parse("2010-06-30T01:20:47.999Z")},
43+ {"'2010-06-30T01:20:47.999+01:00'", Instant.parse("2010-06-30T00:20:47.999Z")}
4644 };
4745 }
4846
4947 @DataProvider(name = "InstantCodecTest.format")
5048 public Object[][] formatParameters() {
5149 return new Object[][]{
52- { null , "NULL" },
53- { Instant.ofEpochMilli(0) , "'1970-01-01T00:00:00.000+00:00'" },
54- { ZonedDateTime.parse("2010-06-30T02:20:47.999+01:00").toInstant(), "'2010-06-30T01:20:47.999+00:00'" }
50+ {null, "NULL"},
51+ {Instant.ofEpochMilli(0), "'1970-01-01T00:00:00.000+00:00'"},
52+ {ZonedDateTime.parse("2010-06-30T02:20:47.999+01:00").toInstant(), "'2010-06-30T01:20:47.999+00:00'"}
5553 };
5654 }
5755
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/Jdk8TimeCodecsTest.java +32 −34
@@ -15,20 +15,6 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18-import java.time.Instant;
19-import java.time.LocalDate;
20-import java.time.LocalTime;
21-import java.time.ZonedDateTime;
22-import java.util.*;
23-
24-import com.google.common.collect.ImmutableMap;
25-import org.testng.annotations.BeforeClass;
26-import org.testng.annotations.Test;
27-
28-import static com.google.common.collect.Lists.newArrayList;
29-import static com.google.common.collect.Sets.newHashSet;
30-import static org.assertj.core.api.Assertions.assertThat;
31-
3218 import com.datastax.driver.core.*;
3319 import com.datastax.driver.core.utils.CassandraVersion;
3420 import com.datastax.driver.mapping.Mapper;
@@ -36,27 +22,39 @@
3622 import com.datastax.driver.mapping.annotations.Column;
3723 import com.datastax.driver.mapping.annotations.PartitionKey;
3824 import com.datastax.driver.mapping.annotations.Table;
25+import com.google.common.collect.ImmutableMap;
26+import org.testng.annotations.BeforeClass;
27+import org.testng.annotations.Test;
28+
29+import java.time.Instant;
30+import java.time.LocalDate;
31+import java.time.LocalTime;
32+import java.time.ZonedDateTime;
33+import java.util.*;
3934
4035 import static com.datastax.driver.core.DataType.timestamp;
4136 import static com.datastax.driver.core.DataType.varchar;
37+import static com.google.common.collect.Lists.newArrayList;
38+import static com.google.common.collect.Sets.newHashSet;
39+import static org.assertj.core.api.Assertions.assertThat;
4240
43-@CassandraVersion(major=2.2)
41+@CassandraVersion(major = 2.2)
4442 public class Jdk8TimeCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
4543
4644 @Override
4745 protected Collection<String> getTableDefinitions() {
4846 return Collections.singletonList(
4947 "CREATE TABLE IF NOT EXISTS foo ("
50- + "c1 text PRIMARY KEY, "
51- + "cdate date, "
52- + "ctime time, "
53- + "ctimestamp timestamp, "
54- + "ctuple tuple<timestamp,varchar>, "
55- + "cdates frozen<list<date>>, "
56- + "ctimes frozen<set<time>>, "
57- + "ctimestamps frozen<map<text,timestamp>>, "
58- + "ctuples frozen<map<tuple<timestamp,varchar>,varchar>>"
59- + ")");
48+ + "c1 text PRIMARY KEY, "
49+ + "cdate date, "
50+ + "ctime time, "
51+ + "ctimestamp timestamp, "
52+ + "ctuple tuple<timestamp,varchar>, "
53+ + "cdates frozen<list<date>>, "
54+ + "ctimes frozen<set<time>>, "
55+ + "ctimestamps frozen<map<text,timestamp>>, "
56+ + "ctuples frozen<map<tuple<timestamp,varchar>,varchar>>"
57+ + ")");
6058 }
6159
6260 @BeforeClass(groups = "short")
@@ -64,10 +62,10 @@
6462 TupleType dateWithTimeZoneType = cluster.getMetadata().newTupleType(timestamp(), varchar());
6563 CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
6664 codecRegistry
67- .register(LocalTimeCodec.instance)
68- .register(LocalDateCodec.instance)
69- .register(InstantCodec.instance)
70- .register(new ZonedDateTimeCodec(dateWithTimeZoneType));
65+ .register(LocalTimeCodec.instance)
66+ .register(LocalDateCodec.instance)
67+ .register(InstantCodec.instance)
68+ .register(new ZonedDateTimeCodec(dateWithTimeZoneType));
7169 }
7270
7371 /**
@@ -81,7 +79,7 @@
8179 * @jira_ticket JAVA-606
8280 * @since 2.2.0
8381 */
84- @Test(groups="short")
82+ @Test(groups = "short")
8583 public void should_map_time_to_localtime() {
8684 // given
8785 LocalTime time = LocalTime.of(12, 16, 34, 999);
@@ -106,7 +104,7 @@
106104 * @jira_ticket JAVA-606
107105 * @since 2.2.0
108106 */
109- @Test(groups="short")
107+ @Test(groups = "short")
110108 public void should_map_date_to_localdate() {
111109 // given
112110 LocalDate localDate = LocalDate.of(2015, 1, 1);
@@ -132,7 +130,7 @@
132130 * @jira_ticket JAVA-606
133131 * @since 2.2.0
134132 */
135- @Test(groups="short")
133+ @Test(groups = "short")
136134 public void should_map_timestamp_to_instant() {
137135 // given
138136 Instant instant = Instant.parse("2010-06-30T01:20:30Z");
@@ -157,7 +155,7 @@
157155 * @jira_ticket JAVA-606
158156 * @since 2.2.0
159157 */
160- @Test(groups="short")
158+ @Test(groups = "short")
161159 public void should_map_tuple_to_zoneddatetime() {
162160 // given
163161 ZonedDateTime expected = ZonedDateTime.parse("2010-06-30T01:20+05:30");
@@ -176,7 +174,7 @@
176174 assertThat(actual.getZone()).isEqualTo(expected.getZone());
177175 }
178176
179- @Test(groups="short")
177+ @Test(groups = "short")
180178 public void should_use_mapper_to_store_and_retrieve_values_with_custom_jdk8_codecs() {
181179 // given
182180 MappingManager manager = new MappingManager(session);
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/LocalDateCodecTest.java +14 −16
@@ -15,16 +15,14 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18-import java.time.LocalDate;
19-
18+import com.datastax.driver.core.Assertions;
2019 import org.testng.annotations.DataProvider;
2120 import org.testng.annotations.Test;
2221
23-import static org.assertj.core.api.Assertions.assertThat;
24-
25-import com.datastax.driver.core.Assertions;
22+import java.time.LocalDate;
2623
2724 import static com.datastax.driver.core.ProtocolVersion.V4;
25+import static org.assertj.core.api.Assertions.assertThat;
2826
2927 public class LocalDateCodecTest {
3028
@@ -34,23 +32,23 @@
3432 @DataProvider(name = "LocalDateCodecTest.parse")
3533 public Object[][] parseParameters() {
3634 return new Object[][]{
37- { null , null },
38- { "" , null },
39- { "NULL" , null },
40- { "0" , MIN },
41- { "'2147483648'" , EPOCH },
42- { "'-5877641-06-23'" , MIN },
43- { "'1970-01-01'" , EPOCH },
44- { "'2014-01-01'" , LocalDate.parse("2014-01-01") }
35+ {null, null},
36+ {"", null},
37+ {"NULL", null},
38+ {"0", MIN},
39+ {"'2147483648'", EPOCH},
40+ {"'-5877641-06-23'", MIN},
41+ {"'1970-01-01'", EPOCH},
42+ {"'2014-01-01'", LocalDate.parse("2014-01-01")}
4543 };
4644 }
4745
4846 @DataProvider(name = "LocalDateCodecTest.format")
4947 public Object[][] formatParameters() {
5048 return new Object[][]{
51- { null , "NULL" },
52- { LocalDate.ofEpochDay(0) , "'1970-01-01'" },
53- { LocalDate.parse("2010-06-30"), "'2010-06-30'" }
49+ {null, "NULL"},
50+ {LocalDate.ofEpochDay(0), "'1970-01-01'"},
51+ {LocalDate.parse("2010-06-30"), "'2010-06-30'"}
5452 };
5553 }
5654
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodecTest.java +14 −16
@@ -15,17 +15,15 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18-import java.time.LocalTime;
19-
18+import com.datastax.driver.core.Assertions;
2019 import org.testng.annotations.DataProvider;
2120 import org.testng.annotations.Test;
2221
23-import static org.assertj.core.api.Assertions.assertThat;
24-
25-import com.datastax.driver.core.Assertions;
22+import java.time.LocalTime;
2623
2724 import static com.datastax.driver.core.ParseUtils.quote;
2825 import static com.datastax.driver.core.ProtocolVersion.V4;
26+import static org.assertj.core.api.Assertions.assertThat;
2927
3028 public class LocalTimeCodecTest {
3129
@@ -34,23 +32,23 @@
3432 LocalTime time = LocalTime.parse("13:25:47.123456789");
3533 String nanosOfDay = quote(Long.toString(time.toNanoOfDay()));
3634 return new Object[][]{
37- { null , null },
38- { "" , null },
39- { "NULL" , null },
40- { nanosOfDay , LocalTime.parse("13:25:47.123456789") },
41- { "'13:25:47'" , LocalTime.parse("13:25:47") },
42- { "'13:25:47.123'" , LocalTime.parse("13:25:47.123") },
43- { "'13:25:47.123456'" , LocalTime.parse("13:25:47.123456") },
44- { "'13:25:47.123456789'", LocalTime.parse("13:25:47.123456789") }
35+ {null, null},
36+ {"", null},
37+ {"NULL", null},
38+ {nanosOfDay, LocalTime.parse("13:25:47.123456789")},
39+ {"'13:25:47'", LocalTime.parse("13:25:47")},
40+ {"'13:25:47.123'", LocalTime.parse("13:25:47.123")},
41+ {"'13:25:47.123456'", LocalTime.parse("13:25:47.123456")},
42+ {"'13:25:47.123456789'", LocalTime.parse("13:25:47.123456789")}
4543 };
4644 }
4745
4846 @DataProvider(name = "LocalTimeCodecTest.format")
4947 public Object[][] formatParameters() {
5048 return new Object[][]{
51- { null , "NULL" },
52- { LocalTime.NOON , "'12:00:00.000'" },
53- { LocalTime.parse("02:20:47.999999"), "'02:20:47.999'" }
49+ {null, "NULL"},
50+ {LocalTime.NOON, "'12:00:00.000'"},
51+ {LocalTime.parse("02:20:47.999999"), "'02:20:47.999'"}
5452 };
5553 }
5654
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/OptionalCodecTest.java +16 −24
@@ -15,32 +15,24 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
20+import com.datastax.driver.core.querybuilder.BuiltStatement;
21+import com.datastax.driver.core.utils.CassandraVersion;
22+import com.google.common.collect.Lists;
23+import org.testng.annotations.BeforeMethod;
24+import org.testng.annotations.Test;
25+
1826 import java.math.BigDecimal;
1927 import java.util.Collection;
2028 import java.util.Collections;
2129 import java.util.List;
2230 import java.util.Optional;
2331
24-import com.google.common.collect.Lists;
25-import org.testng.annotations.BeforeMethod;
26-import org.testng.annotations.Test;
27-
32+import static com.datastax.driver.core.TypeCodec.*;
33+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2834 import static org.assertj.core.api.Assertions.assertThat;
2935
30-import com.datastax.driver.core.*;
31-import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
32-import com.datastax.driver.core.querybuilder.BuiltStatement;
33-import com.datastax.driver.core.utils.CassandraVersion;
34-
35-import static com.datastax.driver.core.TypeCodec.bigint;
36-import static com.datastax.driver.core.TypeCodec.decimal;
37-import static com.datastax.driver.core.TypeCodec.list;
38-import static com.datastax.driver.core.TypeCodec.varchar;
39-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
40-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
41-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
42-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
43-
4436 public class OptionalCodecTest extends PerClassSingleNodeCluster {
4537
4638 private final OptionalCodec<List<String>> optionalCodec = new OptionalCodec<List<String>>(list(varchar()));
@@ -79,8 +71,8 @@
7971 * @jira_ticket JAVA-606
8072 * @since 2.2.0
8173 */
82- @Test(groups="short")
83- @CassandraVersion(major=2.2)
74+ @Test(groups = "short")
75+ @CassandraVersion(major = 2.2)
8476 public void should_map_unset_value_to_empty() {
8577 PreparedStatement insertPrep = session.prepare(this.insertStmt);
8678 PreparedStatement selectPrep = session.prepare(this.selectStmt);
@@ -109,7 +101,7 @@
109101 * @jira_ticket JAVA-606
110102 * @since 2.2.0
111103 */
112- @Test(groups="short")
104+ @Test(groups = "short")
113105 public void should_map_absent_null_value_to_empty() {
114106 PreparedStatement insertPrep = session.prepare(this.insertStmt);
115107 PreparedStatement selectPrep = session.prepare(this.selectStmt);
@@ -141,7 +133,7 @@
141133 * @jira_ticket JAVA-606
142134 * @since 2.2.0
143135 */
144- @Test(groups="short")
136+ @Test(groups = "short")
145137 public void should_map_some_back_to_itself() {
146138 PreparedStatement insertPrep = session.prepare(this.insertStmt);
147139 PreparedStatement selectPrep = session.prepare(this.selectStmt);
@@ -169,7 +161,7 @@
169161 assertThat(returnData.get()).isEqualTo(data);
170162 }
171163
172- @Test(groups="short")
164+ @Test(groups = "short")
173165 public void should_map_a_primitive_type_to_empty() {
174166 OptionalCodec<Long> optionalLongCodec = new OptionalCodec<Long>(bigint());
175167 cluster.getConfiguration().getCodecRegistry().register(optionalLongCodec);
@@ -193,7 +185,7 @@
193185 assertThat(row.get("c4", Long.class)).isNull();
194186 }
195187
196- @Test(groups="short")
188+ @Test(groups = "short")
197189 public void should_map_a_nullable_type_to_empty() {
198190 OptionalCodec<BigDecimal> optionalDecimalCodec = new OptionalCodec<BigDecimal>(decimal());
199191 cluster.getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodecTest.java +20 −23
@@ -15,29 +15,26 @@
1515 */
1616 package com.datastax.driver.extras.codecs.jdk8;
1717
18+import com.datastax.driver.core.Assertions;
19+import com.datastax.driver.core.TupleType;
20+import org.testng.annotations.DataProvider;
21+import org.testng.annotations.Test;
22+
1823 import java.time.ZoneOffset;
1924 import java.time.ZonedDateTime;
2025
26+import static com.datastax.driver.core.DataType.timestamp;
27+import static com.datastax.driver.core.DataType.varchar;
28+import static com.datastax.driver.core.ProtocolVersion.V4;
29+import static com.google.common.collect.Lists.newArrayList;
2130 import static java.time.Instant.ofEpochMilli;
2231 import static java.time.Instant.parse;
2332 import static java.time.ZoneOffset.UTC;
2433 import static java.time.ZonedDateTime.ofInstant;
25-
26-import org.testng.annotations.DataProvider;
27-import org.testng.annotations.Test;
28-
29-import static com.google.common.collect.Lists.newArrayList;
3034 import static org.assertj.core.api.Assertions.assertThat;
3135 import static org.mockito.Mockito.mock;
3236 import static org.mockito.Mockito.when;
3337
34-import com.datastax.driver.core.Assertions;
35-import com.datastax.driver.core.TupleType;
36-
37-import static com.datastax.driver.core.DataType.timestamp;
38-import static com.datastax.driver.core.DataType.varchar;
39-import static com.datastax.driver.core.ProtocolVersion.V4;
40-
4138 public class ZonedDateTimeCodecTest {
4239
4340 private final TupleType tupleType = mock(TupleType.class);
@@ -45,23 +42,23 @@
4542 @DataProvider(name = "ZonedDateTimeCodecTest.parse")
4643 public Object[][] parseParameters() {
4744 return new Object[][]{
48- { null , null },
49- { "" , null },
50- { "NULL" , null },
51- { "(0 ,'+01:00')" , ofInstant(ofEpochMilli(0) , ZoneOffset.of("+01:00")) },
52- { "(1277860847999 ,'+01:00')" , ofInstant(parse("2010-06-30T01:20:47.999Z"), ZoneOffset.of("+01:00")) },
53- { "('2010-06-30T01:20Z' ,'+01:00')" , ofInstant(parse("2010-06-30T01:20:00.000Z"), ZoneOffset.of("+01:00")) },
54- { "('2010-06-30T01:20:47Z' ,'+01:00')" , ofInstant(parse("2010-06-30T01:20:47.000Z"), ZoneOffset.of("+01:00")) },
55- { "('2010-06-30T01:20:47.999Z','+01:00')" , ofInstant(parse("2010-06-30T01:20:47.999Z"), ZoneOffset.of("+01:00")) }
45+ {null, null},
46+ {"", null},
47+ {"NULL", null},
48+ {"(0 ,'+01:00')", ofInstant(ofEpochMilli(0), ZoneOffset.of("+01:00"))},
49+ {"(1277860847999 ,'+01:00')", ofInstant(parse("2010-06-30T01:20:47.999Z"), ZoneOffset.of("+01:00"))},
50+ {"('2010-06-30T01:20Z' ,'+01:00')", ofInstant(parse("2010-06-30T01:20:00.000Z"), ZoneOffset.of("+01:00"))},
51+ {"('2010-06-30T01:20:47Z' ,'+01:00')", ofInstant(parse("2010-06-30T01:20:47.000Z"), ZoneOffset.of("+01:00"))},
52+ {"('2010-06-30T01:20:47.999Z','+01:00')", ofInstant(parse("2010-06-30T01:20:47.999Z"), ZoneOffset.of("+01:00"))}
5653 };
5754 }
5855
5956 @DataProvider(name = "ZonedDateTimeCodecTest.format")
6057 public Object[][] formatParameters() {
6158 return new Object[][]{
62- { null , "NULL" },
63- { ofInstant(ofEpochMilli(0), UTC) , "('1970-01-01T00:00:00Z','+00:00')" },
64- { ZonedDateTime.parse("2010-06-30T01:20:47.999+01:00"), "('2010-06-30T00:20:47.999Z','+01:00')" }
59+ {null, "NULL"},
60+ {ofInstant(ofEpochMilli(0), UTC), "('1970-01-01T00:00:00Z','+00:00')"},
61+ {ZonedDateTime.parse("2010-06-30T01:20:47.999+01:00"), "('2010-06-30T00:20:47.999Z','+01:00')"}
6562 };
6663 }
6764
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/DateTimeCodecTest.java +16 −19
@@ -15,11 +15,15 @@
1515 */
1616 package com.datastax.driver.extras.codecs.joda;
1717
18+import com.datastax.driver.core.Assertions;
19+import com.datastax.driver.core.TupleType;
1820 import org.joda.time.DateTime;
19-import org.joda.time.DateTimeZone;
2021 import org.testng.annotations.DataProvider;
2122 import org.testng.annotations.Test;
2223
24+import static com.datastax.driver.core.DataType.timestamp;
25+import static com.datastax.driver.core.DataType.varchar;
26+import static com.datastax.driver.core.ProtocolVersion.V4;
2327 import static com.google.common.collect.Lists.newArrayList;
2428 import static org.assertj.core.api.Assertions.assertThat;
2529 import static org.joda.time.DateTimeZone.UTC;
@@ -27,13 +31,6 @@
2731 import static org.mockito.Mockito.mock;
2832 import static org.mockito.Mockito.when;
2933
30-import com.datastax.driver.core.Assertions;
31-import com.datastax.driver.core.TupleType;
32-
33-import static com.datastax.driver.core.DataType.timestamp;
34-import static com.datastax.driver.core.DataType.varchar;
35-import static com.datastax.driver.core.ProtocolVersion.V4;
36-
3734 public class DateTimeCodecTest {
3835
3936 private final TupleType tupleType = mock(TupleType.class);
@@ -41,23 +38,23 @@
4138 @DataProvider(name = "DateTimeCodecTest.parse")
4239 public Object[][] parseParameters() {
4340 return new Object[][]{
44- { null , null },
45- { "" , null },
46- { "NULL" , null },
47- { "(0 ,'UTC')" , new DateTime(0, forID("UTC")) },
48- { "(1277860847999 ,'+01:00')" , new DateTime("2010-06-30T02:20:47.999+01:00", forID("+01:00")) },
49- { "('2010-06-30T01:20Z' ,'+01:00')" , new DateTime("2010-06-30T02:20:00.000+01:00", forID("+01:00")) },
50- { "('2010-06-30T01:20:47Z' ,'+01:00')" , new DateTime("2010-06-30T02:20:47.000+01:00", forID("+01:00")) },
51- { "('2010-06-30T01:20:47.999Z','+01:00')" , new DateTime("2010-06-30T02:20:47.999+01:00", forID("+01:00")) }
41+ {null, null},
42+ {"", null},
43+ {"NULL", null},
44+ {"(0 ,'UTC')", new DateTime(0, forID("UTC"))},
45+ {"(1277860847999 ,'+01:00')", new DateTime("2010-06-30T02:20:47.999+01:00", forID("+01:00"))},
46+ {"('2010-06-30T01:20Z' ,'+01:00')", new DateTime("2010-06-30T02:20:00.000+01:00", forID("+01:00"))},
47+ {"('2010-06-30T01:20:47Z' ,'+01:00')", new DateTime("2010-06-30T02:20:47.000+01:00", forID("+01:00"))},
48+ {"('2010-06-30T01:20:47.999Z','+01:00')", new DateTime("2010-06-30T02:20:47.999+01:00", forID("+01:00"))}
5249 };
5350 }
5451
5552 @DataProvider(name = "DateTimeCodecTest.format")
5653 public Object[][] formatParameters() {
5754 return new Object[][]{
58- { null , "NULL" },
59- { new DateTime(0).withZone(UTC) , "('1970-01-01T00:00:00.000Z','+00:00')" },
60- { new DateTime("2010-06-30T01:20:47.999+01:00", forID("+01:00")), "('2010-06-30T00:20:47.999Z','+01:00')" }
55+ {null, "NULL"},
56+ {new DateTime(0).withZone(UTC), "('1970-01-01T00:00:00.000Z','+00:00')"},
57+ {new DateTime("2010-06-30T01:20:47.999+01:00", forID("+01:00")), "('2010-06-30T00:20:47.999Z','+01:00')"}
6158 };
6259 }
6360
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/InstantCodecTest.java +17 −19
@@ -15,43 +15,41 @@
1515 */
1616 package com.datastax.driver.extras.codecs.joda;
1717
18-import java.text.ParseException;
19-
18+import com.datastax.driver.core.Assertions;
2019 import org.joda.time.Instant;
2120 import org.testng.annotations.DataProvider;
2221 import org.testng.annotations.Test;
2322
24-import static org.assertj.core.api.Assertions.assertThat;
25-
26-import com.datastax.driver.core.Assertions;
23+import java.text.ParseException;
2724
2825 import static com.datastax.driver.core.ProtocolVersion.V4;
26+import static org.assertj.core.api.Assertions.assertThat;
2927
3028 public class InstantCodecTest {
3129
3230 @DataProvider(name = "InstantCodecTest.parse")
3331 public Object[][] parseParameters() {
3432 return new Object[][]{
35- { null , null },
36- { "" , null },
37- { "NULL" , null },
38- { "0" , new Instant(0) },
39- { "1277860847999" , new Instant(1277860847999L) },
40- { "'2010-06-30T01:20'" , Instant.parse("2010-06-30T01:20:00.000Z") },
41- { "'2010-06-30T01:20Z'" , Instant.parse("2010-06-30T01:20:00.000Z") },
42- { "'2010-06-30T01:20:47'" , Instant.parse("2010-06-30T01:20:47.000Z") },
43- { "'2010-06-30T01:20:47+01:00'" , Instant.parse("2010-06-30T00:20:47.000Z") },
44- { "'2010-06-30T01:20:47.999'" , Instant.parse("2010-06-30T01:20:47.999Z") },
45- { "'2010-06-30T01:20:47.999+01:00'" , Instant.parse("2010-06-30T00:20:47.999Z") }
33+ {null, null},
34+ {"", null},
35+ {"NULL", null},
36+ {"0", new Instant(0)},
37+ {"1277860847999", new Instant(1277860847999L)},
38+ {"'2010-06-30T01:20'", Instant.parse("2010-06-30T01:20:00.000Z")},
39+ {"'2010-06-30T01:20Z'", Instant.parse("2010-06-30T01:20:00.000Z")},
40+ {"'2010-06-30T01:20:47'", Instant.parse("2010-06-30T01:20:47.000Z")},
41+ {"'2010-06-30T01:20:47+01:00'", Instant.parse("2010-06-30T00:20:47.000Z")},
42+ {"'2010-06-30T01:20:47.999'", Instant.parse("2010-06-30T01:20:47.999Z")},
43+ {"'2010-06-30T01:20:47.999+01:00'", Instant.parse("2010-06-30T00:20:47.999Z")}
4644 };
4745 }
4846
4947 @DataProvider(name = "InstantCodecTest.format")
5048 public Object[][] formatParameters() throws ParseException {
5149 return new Object[][]{
52- { null , "NULL" },
53- { new Instant(0) , "'1970-01-01T00:00:00.000+00:00'" },
54- { Instant.parse("2010-06-30T02:20:47.999+01:00").toInstant(), "'2010-06-30T01:20:47.999+00:00'" }
50+ {null, "NULL"},
51+ {new Instant(0), "'1970-01-01T00:00:00.000+00:00'"},
52+ {Instant.parse("2010-06-30T02:20:47.999+01:00").toInstant(), "'2010-06-30T01:20:47.999+00:00'"}
5553 };
5654 }
5755
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/JodaTimeCodecsTest.java +34 −37
@@ -15,11 +15,13 @@
1515 */
1616 package com.datastax.driver.extras.codecs.joda;
1717
18-import java.util.*;
19-
20-import static java.util.concurrent.TimeUnit.MILLISECONDS;
21-import static java.util.concurrent.TimeUnit.NANOSECONDS;
22-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.utils.CassandraVersion;
20+import com.datastax.driver.mapping.Mapper;
21+import com.datastax.driver.mapping.MappingManager;
22+import com.datastax.driver.mapping.annotations.Column;
23+import com.datastax.driver.mapping.annotations.PartitionKey;
24+import com.datastax.driver.mapping.annotations.Table;
2325 import com.google.common.collect.ImmutableMap;
2426 import org.joda.time.DateTime;
2527 import org.joda.time.Instant;
@@ -28,38 +30,33 @@
2830 import org.testng.annotations.BeforeClass;
2931 import org.testng.annotations.Test;
3032
31-import static com.google.common.collect.Lists.newArrayList;
32-import static com.google.common.collect.Sets.newHashSet;
33-import static org.assertj.core.api.Assertions.assertThat;
34-
35-import com.datastax.driver.core.*;
36-import com.datastax.driver.core.utils.CassandraVersion;
37-import com.datastax.driver.mapping.Mapper;
38-import com.datastax.driver.mapping.MappingManager;
39-import com.datastax.driver.mapping.annotations.Column;
40-import com.datastax.driver.mapping.annotations.PartitionKey;
41-import com.datastax.driver.mapping.annotations.Table;
33+import java.util.*;
4234
4335 import static com.datastax.driver.core.DataType.timestamp;
4436 import static com.datastax.driver.core.DataType.varchar;
37+import static com.google.common.collect.Lists.newArrayList;
38+import static com.google.common.collect.Sets.newHashSet;
39+import static java.util.concurrent.TimeUnit.MILLISECONDS;
40+import static java.util.concurrent.TimeUnit.NANOSECONDS;
41+import static org.assertj.core.api.Assertions.assertThat;
4542
46-@CassandraVersion(major=2.2)
43+@CassandraVersion(major = 2.2)
4744 public class JodaTimeCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
4845
4946 @Override
5047 protected Collection<String> getTableDefinitions() {
5148 return Collections.singletonList(
52- "CREATE TABLE IF NOT EXISTS foo ("
53- + "c1 text PRIMARY KEY, "
54- + "cdate date, "
55- + "ctime time, "
56- + "ctimestamp timestamp, "
57- + "ctuple tuple<timestamp,varchar>, "
58- + "cdates frozen<list<date>>, "
59- + "ctimes frozen<set<time>>, "
60- + "ctimestamps frozen<map<text,timestamp>>, "
61- + "ctuples frozen<map<tuple<timestamp,varchar>,varchar>>"
62- + ")");
49+ "CREATE TABLE IF NOT EXISTS foo ("
50+ + "c1 text PRIMARY KEY, "
51+ + "cdate date, "
52+ + "ctime time, "
53+ + "ctimestamp timestamp, "
54+ + "ctuple tuple<timestamp,varchar>, "
55+ + "cdates frozen<list<date>>, "
56+ + "ctimes frozen<set<time>>, "
57+ + "ctimestamps frozen<map<text,timestamp>>, "
58+ + "ctuples frozen<map<tuple<timestamp,varchar>,varchar>>"
59+ + ")");
6360 }
6461
6562 @BeforeClass(groups = "short")
@@ -67,10 +64,10 @@
6764 TupleType dateWithTimeZoneType = cluster.getMetadata().newTupleType(timestamp(), varchar());
6865 CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
6966 codecRegistry
70- .register(LocalTimeCodec.instance)
71- .register(LocalDateCodec.instance)
72- .register(InstantCodec.instance)
73- .register(new DateTimeCodec(dateWithTimeZoneType));
67+ .register(LocalTimeCodec.instance)
68+ .register(LocalDateCodec.instance)
69+ .register(InstantCodec.instance)
70+ .register(new DateTimeCodec(dateWithTimeZoneType));
7471 }
7572
7673 /**
@@ -84,7 +81,7 @@
8481 * @jira_ticket JAVA-846
8582 * @since 2.2.0
8683 */
87- @Test(groups="short")
84+ @Test(groups = "short")
8885 public void should_map_time_to_localtime() {
8986 // given
9087 LocalTime time = new LocalTime(12, 16, 34, 999);
@@ -109,7 +106,7 @@
109106 * @jira_ticket JAVA-846
110107 * @since 2.2.0
111108 */
112- @Test(groups="short")
109+ @Test(groups = "short")
113110 public void should_map_date_to_localdate() {
114111 // given
115112 LocalDate localDate = new LocalDate(2015, 1, 1);
@@ -135,7 +132,7 @@
135132 * @jira_ticket JAVA-846
136133 * @since 2.2.0
137134 */
138- @Test(groups="short")
135+ @Test(groups = "short")
139136 public void should_map_timestamp_to_instant() {
140137 // given
141138 Instant instant = Instant.parse("2010-06-30T01:20+05:00");
@@ -160,7 +157,7 @@
160157 * @jira_ticket JAVA-846
161158 * @since 2.2.0
162159 */
163- @Test(groups="short")
160+ @Test(groups = "short")
164161 public void should_map_tuple_to_datetime() {
165162 // given
166163 DateTime expected = DateTime.parse("2010-06-30T01:20+05:30");
@@ -178,7 +175,7 @@
178175 assertThat(row.get("ctuple", DateTime.class).getZone()).isEqualTo(expected.getZone());
179176 }
180177
181- @Test(groups="short")
178+ @Test(groups = "short")
182179 public void should_use_mapper_to_store_and_retrieve_values_with_custom_joda_codecs() {
183180 // given
184181 MappingManager manager = new MappingManager(session);
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/LocalDateCodecTest.java +13 −15
@@ -15,15 +15,13 @@
1515 */
1616 package com.datastax.driver.extras.codecs.joda;
1717
18+import com.datastax.driver.core.Assertions;
1819 import org.joda.time.LocalDate;
1920 import org.testng.annotations.DataProvider;
2021 import org.testng.annotations.Test;
2122
22-import static org.assertj.core.api.Assertions.assertThat;
23-
24-import com.datastax.driver.core.Assertions;
25-
2623 import static com.datastax.driver.core.ProtocolVersion.V4;
24+import static org.assertj.core.api.Assertions.assertThat;
2725
2826 public class LocalDateCodecTest {
2927
@@ -33,23 +31,23 @@
3331 @DataProvider(name = "LocalDateCodecTest")
3432 public Object[][] parseParameters() {
3533 return new Object[][]{
36- { null , null },
37- { "" , null },
38- { "NULL" , null },
39- { "0" , MIN },
40- { "'2147483648'" , EPOCH },
41- { "'-5877641-06-23'" , MIN },
42- { "'1970-01-01'" , EPOCH },
43- { "'2014-01-01'" , LocalDate.parse("2014-01-01") }
34+ {null, null},
35+ {"", null},
36+ {"NULL", null},
37+ {"0", MIN},
38+ {"'2147483648'", EPOCH},
39+ {"'-5877641-06-23'", MIN},
40+ {"'1970-01-01'", EPOCH},
41+ {"'2014-01-01'", LocalDate.parse("2014-01-01")}
4442 };
4543 }
4644
4745 @DataProvider(name = "LocalDateCodecTest.format")
4846 public Object[][] formatParameters() {
4947 return new Object[][]{
50- { null , "NULL" },
51- { EPOCH , "'1970-01-01'" },
52- { LocalDate.parse("2010-06-30"), "'2010-06-30'" }
48+ {null, "NULL"},
49+ {EPOCH, "'1970-01-01'"},
50+ {LocalDate.parse("2010-06-30"), "'2010-06-30'"}
5351 };
5452 }
5553
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/LocalTimeCodecTest.java +14 −17
@@ -15,18 +15,15 @@
1515 */
1616 package com.datastax.driver.extras.codecs.joda;
1717
18-import static java.util.concurrent.TimeUnit.MILLISECONDS;
19-
18+import com.datastax.driver.core.Assertions;
2019 import org.joda.time.LocalTime;
2120 import org.testng.annotations.DataProvider;
2221 import org.testng.annotations.Test;
2322
24-import static org.assertj.core.api.Assertions.assertThat;
25-
26-import com.datastax.driver.core.Assertions;
27-
2823 import static com.datastax.driver.core.ParseUtils.quote;
2924 import static com.datastax.driver.core.ProtocolVersion.V4;
25+import static java.util.concurrent.TimeUnit.MILLISECONDS;
26+import static org.assertj.core.api.Assertions.assertThat;
3027
3128 public class LocalTimeCodecTest {
3229
@@ -35,23 +32,23 @@
3532 LocalTime time = LocalTime.parse("13:25:47.123456789");
3633 String nanosOfDay = quote(Long.toString(MILLISECONDS.toNanos(time.getMillisOfDay())));
3734 return new Object[][]{
38- { null , null },
39- { "" , null },
40- { "NULL" , null },
41- { nanosOfDay , LocalTime.parse("13:25:47.123456789") },
42- { "'13:25:47'" , LocalTime.parse("13:25:47") },
43- { "'13:25:47.123'" , LocalTime.parse("13:25:47.123") },
44- { "'13:25:47.123456'" , LocalTime.parse("13:25:47.123456") },
45- { "'13:25:47.123456789'", LocalTime.parse("13:25:47.123456789") }
35+ {null, null},
36+ {"", null},
37+ {"NULL", null},
38+ {nanosOfDay, LocalTime.parse("13:25:47.123456789")},
39+ {"'13:25:47'", LocalTime.parse("13:25:47")},
40+ {"'13:25:47.123'", LocalTime.parse("13:25:47.123")},
41+ {"'13:25:47.123456'", LocalTime.parse("13:25:47.123456")},
42+ {"'13:25:47.123456789'", LocalTime.parse("13:25:47.123456789")}
4643 };
4744 }
4845
4946 @DataProvider(name = "LocalTimeCodecTest.format")
5047 public Object[][] formatParameters() {
5148 return new Object[][]{
52- { null , "NULL" },
53- { LocalTime.parse("12:00") , "'12:00:00.000'" },
54- { LocalTime.parse("02:20:47.999999"), "'02:20:47.999'" }
49+ {null, "NULL"},
50+ {LocalTime.parse("12:00"), "'12:00:00.000'"},
51+ {LocalTime.parse("02:20:47.999999"), "'02:20:47.999'"}
5552 };
5653 }
5754
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/JacksonJsonCodecTest.java +37 −42
@@ -15,37 +15,32 @@
1515 */
1616 package com.datastax.driver.extras.codecs.json;
1717
18-import java.util.ArrayList;
19-import java.util.Collection;
20-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.querybuilder.BuiltStatement;
20+import com.datastax.driver.core.utils.CassandraVersion;
2121 import com.fasterxml.jackson.annotation.JsonCreator;
2222 import com.fasterxml.jackson.annotation.JsonProperty;
2323 import com.google.common.base.Objects;
2424 import com.google.common.collect.Lists;
2525 import org.testng.annotations.Test;
2626
27-import static org.assertj.core.api.Assertions.assertThat;
28-
29-import com.datastax.driver.core.*;
30-import com.datastax.driver.core.querybuilder.BuiltStatement;
31-import com.datastax.driver.core.utils.CassandraVersion;
27+import java.util.ArrayList;
28+import java.util.Collection;
3229
33-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
34-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
35-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
36-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
30+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
31+import static org.assertj.core.api.Assertions.assertThat;
3732
3833 public class JacksonJsonCodecTest extends CCMBridge.PerClassSingleNodeCluster {
3934
4035 private static final JacksonJsonCodec<User> jsonCodec = new JacksonJsonCodec<User>(User.class);
4136
42- private static final User alice = new User(1, "Alice");
43- private static final User bob = new User(2, "Bob");
37+ private static final User alice = new User(1, "Alice");
38+ private static final User bob = new User(2, "Bob");
4439 private static final User charlie = new User(3, "Charlie");
4540
46- private static final String bobJson = "{\"id\":2,\"name\":\"Bob\"}";
41+ private static final String bobJson = "{\"id\":2,\"name\":\"Bob\"}";
4742 private static final String charlieJson = "{\"id\":3,\"name\":\"Charlie\"}";
48- private static final String aliceJson = "{\"id\":1,\"name\":\"Alice\"}";
43+ private static final String aliceJson = "{\"id\":1,\"name\":\"Alice\"}";
4944
5045 private static final ArrayList<User> bobAndCharlie = Lists.newArrayList(bob, charlie);
5146
@@ -57,14 +52,14 @@
5752 @Override
5853 protected Collection<String> getTableDefinitions() {
5954 return Lists.newArrayList(
60- "CREATE TABLE t1 (c1 text, c2 text, c3 list<text>, PRIMARY KEY (c1, c2))"
55+ "CREATE TABLE t1 (c1 text, c2 text, c3 list<text>, PRIMARY KEY (c1, c2))"
6156 );
6257 }
6358
6459 @Override
6560 protected Cluster.Builder configure(Cluster.Builder builder) {
6661 return builder.withCodecRegistry(
67- new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
62+ new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
6863 );
6964 }
7065
@@ -87,7 +82,7 @@
8782 }
8883
8984 @Test(groups = "short")
90- @CassandraVersion(major=2.0)
85+ @CassandraVersion(major = 2.0)
9186 public void should_use_custom_codec_with_simple_statements() {
9287 session.execute(insertQuery, notAJsonString, alice, bobAndCharlie);
9388 ResultSet rows = session.execute(selectQuery, notAJsonString, alice);
@@ -98,13 +93,13 @@
9893 @Test(groups = "short")
9994 public void should_use_custom_codec_with_built_statements_1() {
10095 BuiltStatement insertStmt = insertInto("t1")
101- .value("c1", bindMarker())
102- .value("c2", bindMarker())
103- .value("c3", bindMarker());
96+ .value("c1", bindMarker())
97+ .value("c2", bindMarker())
98+ .value("c3", bindMarker());
10499 BuiltStatement selectStmt = select("c1", "c2", "c3")
105- .from("t1")
106- .where(eq("c1", bindMarker()))
107- .and(eq("c2", bindMarker()));
100+ .from("t1")
101+ .where(eq("c1", bindMarker()))
102+ .and(eq("c2", bindMarker()));
108103 session.execute(session.prepare(insertStmt).bind(notAJsonString, alice, bobAndCharlie));
109104 ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, alice));
110105 Row row = rows.one();
@@ -114,14 +109,14 @@
114109 @Test(groups = "short")
115110 public void should_use_custom_codec_with_built_statements_2() {
116111 BuiltStatement insertStmt = insertInto("t1")
117- .value("c1", notAJsonString)
118- .value("c2", alice)
119- .value("c3", bobAndCharlie);
112+ .value("c1", notAJsonString)
113+ .value("c2", alice)
114+ .value("c3", bobAndCharlie);
120115 BuiltStatement selectStmt =
121- select("c1", "c2", "c3")
122- .from("t1")
123- .where(eq("c1", notAJsonString))
124- .and(eq("c2", alice));
116+ select("c1", "c2", "c3")
117+ .from("t1")
118+ .where(eq("c1", notAJsonString))
119+ .and(eq("c2", alice));
125120 session.execute(insertStmt);
126121 ResultSet rows = session.execute(selectStmt);
127122 Row row = rows.one();
@@ -143,17 +138,17 @@
143138 @Test(groups = "short")
144139 public void should_use_custom_codec_with_prepared_statements_2() {
145140 session.execute(session.prepare(insertQuery).bind()
146- .setString(0, notAJsonString)
147- .set(1, alice, User.class)
148- .setList(2, bobAndCharlie, User.class)
141+ .setString(0, notAJsonString)
142+ .set(1, alice, User.class)
143+ .setList(2, bobAndCharlie, User.class)
149144 );
150145 PreparedStatement ps = session.prepare(selectQuery);
151146 ResultSet rows = session.execute(ps.bind()
152- .setString(0, notAJsonString)
153- // this set() method conveys information about the java type of alice
154- // so the registry will look for a codec accepting varchar <-> User
155- // and will find jsonCodec because it is the only matching one
156- .set(1, alice, User.class)
147+ .setString(0, notAJsonString)
148+ // this set() method conveys information about the java type of alice
149+ // so the registry will look for a codec accepting varchar <-> User
150+ // and will find jsonCodec because it is the only matching one
151+ .set(1, alice, User.class)
157152 );
158153 Row row = rows.one();
159154 assertRow(row);
@@ -209,9 +204,9 @@
209204 return true;
210205 if (o == null || getClass() != o.getClass())
211206 return false;
212- User user = (User)o;
207+ User user = (User) o;
213208 return Objects.equal(id, user.id) &&
214- Objects.equal(name, user.name);
209+ Objects.equal(name, user.name);
215210 }
216211
217212 @Override
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodecTest.java +32 −37
@@ -15,32 +15,27 @@
1515 */
1616 package com.datastax.driver.extras.codecs.json;
1717
18-import java.io.IOException;
19-import java.io.StringWriter;
20-import java.util.Collection;
21-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.querybuilder.BuiltStatement;
20+import com.datastax.driver.core.utils.CassandraVersion;
2221 import com.google.common.collect.Lists;
23-import javax.json.*;
2422 import org.testng.annotations.DataProvider;
2523 import org.testng.annotations.Test;
2624
27-import static org.assertj.core.api.Assertions.assertThat;
28-
29-import com.datastax.driver.core.*;
30-import com.datastax.driver.core.querybuilder.BuiltStatement;
31-import com.datastax.driver.core.utils.CassandraVersion;
25+import javax.json.*;
26+import java.io.IOException;
27+import java.io.StringWriter;
28+import java.util.Collection;
3229
33-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
34-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
35-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
36-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
30+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
31+import static org.assertj.core.api.Assertions.assertThat;
3732
3833 public class Jsr353JsonCodecTest extends CCMBridge.PerClassSingleNodeCluster {
3934
4035 private static final Jsr353JsonCodec jsonCodec = new Jsr353JsonCodec();
4136
42- private static final JsonObject alice = Json.createObjectBuilder().add("id", 1).add("name", "Alice") .build();
43- private static final JsonObject bob = Json.createObjectBuilder().add("id", 2).add("name", "Bob") .build();
37+ private static final JsonObject alice = Json.createObjectBuilder().add("id", 1).add("name", "Alice").build();
38+ private static final JsonObject bob = Json.createObjectBuilder().add("id", 2).add("name", "Bob").build();
4439 private static final JsonObject charlie = Json.createObjectBuilder().add("id", 3).add("name", "Charlie").build();
4540
4641 private static final JsonArray bobAndCharlie = Json.createArrayBuilder().add(bob).add(charlie).build();
@@ -53,22 +48,22 @@
5348 @Override
5449 protected Collection<String> getTableDefinitions() {
5550 return Lists.newArrayList(
56- "CREATE TABLE t1 (c1 text, c2 text, PRIMARY KEY (c1, c2))"
51+ "CREATE TABLE t1 (c1 text, c2 text, PRIMARY KEY (c1, c2))"
5752 );
5853 }
5954
6055 @Override
6156 protected Cluster.Builder configure(Cluster.Builder builder) {
6257 return builder.withCodecRegistry(
63- new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
58+ new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
6459 );
6560 }
6661
6762 @DataProvider(name = "Jsr353JsonCodecTest")
6863 public static Object[][] parameters() {
69- return new Object[][] {
70- { alice },
71- { bobAndCharlie }
64+ return new Object[][]{
65+ {alice},
66+ {bobAndCharlie}
7267 };
7368 }
7469
@@ -89,7 +84,7 @@
8984 }
9085
9186 @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
92- @CassandraVersion(major=2.0)
87+ @CassandraVersion(major = 2.0)
9388 public void should_use_custom_codec_with_simple_statements(JsonStructure object) throws IOException {
9489 session.execute(insertQuery, notAJsonString, object);
9590 ResultSet rows = session.execute(selectQuery, notAJsonString, object);
@@ -100,12 +95,12 @@
10095 @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
10196 public void should_use_custom_codec_with_built_statements_1(JsonStructure object) throws IOException {
10297 BuiltStatement insertStmt = insertInto("t1")
103- .value("c1", bindMarker())
104- .value("c2", bindMarker());
98+ .value("c1", bindMarker())
99+ .value("c2", bindMarker());
105100 BuiltStatement selectStmt = select("c1", "c2")
106- .from("t1")
107- .where(eq("c1", bindMarker()))
108- .and(eq("c2", bindMarker()));
101+ .from("t1")
102+ .where(eq("c1", bindMarker()))
103+ .and(eq("c2", bindMarker()));
109104 session.execute(session.prepare(insertStmt).bind(notAJsonString, object));
110105 ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, object));
111106 Row row = rows.one();
@@ -115,13 +110,13 @@
115110 @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
116111 public void should_use_custom_codec_with_built_statements_2(JsonStructure object) throws IOException {
117112 BuiltStatement insertStmt = insertInto("t1")
118- .value("c1", notAJsonString)
119- .value("c2", object);
113+ .value("c1", notAJsonString)
114+ .value("c2", object);
120115 BuiltStatement selectStmt =
121- select("c1", "c2")
122- .from("t1")
123- .where(eq("c1", notAJsonString))
124- .and(eq("c2", object));
116+ select("c1", "c2")
117+ .from("t1")
118+ .where(eq("c1", notAJsonString))
119+ .and(eq("c2", object));
125120 session.execute(insertStmt);
126121 ResultSet rows = session.execute(selectStmt);
127122 Row row = rows.one();
@@ -140,13 +135,13 @@
140135 @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
141136 public void should_use_custom_codec_with_prepared_statements_2(JsonStructure object) throws IOException {
142137 session.execute(session.prepare(insertQuery).bind()
143- .setString(0, notAJsonString)
144- .set(1, object, JsonStructure.class)
138+ .setString(0, notAJsonString)
139+ .set(1, object, JsonStructure.class)
145140 );
146141 PreparedStatement ps = session.prepare(selectQuery);
147142 ResultSet rows = session.execute(ps.bind()
148- .setString(0, notAJsonString)
149- .set(1, object, JsonStructure.class)
143+ .setString(0, notAJsonString)
144+ .set(1, object, JsonStructure.class)
150145 );
151146 Row row = rows.one();
152147 assertRow(row, object);
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AccessorInvocationHandler.java +3 −1
@@ -17,7 +17,8 @@
1717
1818 import java.lang.reflect.InvocationHandler;
1919 import java.lang.reflect.Method;
20-import java.util.*;
20+import java.util.HashMap;
21+import java.util.Map;
2122
2223 class AccessorInvocationHandler<T> implements InvocationHandler {
2324
@@ -26,6 +27,7 @@
2627 private static final Method TO_STRING;
2728 private static final Method EQUALS;
2829 private static final Method HASH_CODE;
30+
2931 static {
3032 try {
3133 TO_STRING = Object.class.getMethod("toString");
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AccessorMapper.java +3 −3
@@ -15,12 +15,12 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.PreparedStatement;
2019 import com.google.common.util.concurrent.Futures;
2120 import com.google.common.util.concurrent.ListenableFuture;
2221
23-import com.datastax.driver.core.*;
22+import java.util.ArrayList;
23+import java.util.List;
2424
2525 abstract class AccessorMapper<T> {
2626
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AccessorReflectionMapper.java +2 −2
@@ -16,7 +16,7 @@
1616 package com.datastax.driver.mapping;
1717
1818 import java.lang.reflect.Proxy;
19-import java.util.*;
19+import java.util.List;
2020
2121 class AccessorReflectionMapper<T> extends AccessorMapper<T> {
2222
@@ -28,7 +28,7 @@
2828 @SuppressWarnings({"unchecked", "rawtypes"})
2929 private AccessorReflectionMapper(Class<T> daoClass, List<MethodMapper> methods) {
3030 super(daoClass, methods);
31- this.proxyClasses = (Class<T>[])new Class[]{ daoClass };
31+ this.proxyClasses = (Class<T>[]) new Class[]{daoClass};
3232 this.handler = new AccessorInvocationHandler<T>(this);
3333 }
3434
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationChecks.java +10 −11
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18+import com.datastax.driver.mapping.annotations.Computed;
19+import com.datastax.driver.mapping.annotations.Table;
20+
1821 import java.lang.annotation.Annotation;
19-import java.lang.reflect.*;
2022 import java.lang.reflect.Field;
21-import java.util.*;
22-
23-import com.datastax.driver.mapping.annotations.*;
2423
2524 /**
2625 * Various checks on mapping annotations.
@@ -38,7 +37,7 @@
3837 T instance = annotatedClass.getAnnotation(annotation);
3938 if (instance == null)
4039 throw new IllegalArgumentException(String.format("@%s annotation was not found on type %s",
41- annotation.getSimpleName(), annotatedClass.getName()));
40+ annotation.getSimpleName(), annotatedClass.getName()));
4241
4342 // Check that no other mapping annotations are present
4443 validateAnnotations(annotatedClass, annotation);
@@ -51,8 +50,8 @@
5150 Class<? extends Annotation> invalid = validateAnnotations(clazz.getAnnotations(), allowed);
5251 if (invalid != null)
5352 throw new IllegalArgumentException(String.format("Cannot have both @%s and @%s on type %s",
54- allowed.getSimpleName(), invalid.getSimpleName(),
55- clazz.getName()));
53+ allowed.getSimpleName(), invalid.getSimpleName(),
54+ clazz.getName()));
5655 }
5756
5857 /**
@@ -62,9 +61,9 @@
6261 Class<? extends Annotation> invalid = validateAnnotations(field.getAnnotations(), allowed);
6362 if (invalid != null)
6463 throw new IllegalArgumentException(String.format("Annotation @%s is not allowed on field %s of %s %s",
65- invalid.getSimpleName(),
66- field.getName(), classDescription,
67- field.getDeclaringClass().getName()));
64+ invalid.getSimpleName(),
65+ field.getName(), classDescription,
66+ field.getDeclaringClass().getName()));
6867
6968 checkValidComputed(field);
7069 }
@@ -88,7 +87,7 @@
8887
8988 static void checkValidComputed(Field field) {
9089 Computed computed = field.getAnnotation(Computed.class);
91- if (computed != null && computed.value().isEmpty()){
90+ if (computed != null && computed.value().isEmpty()) {
9291 throw new IllegalArgumentException(String.format("Field %s: attribute 'value' of annotation @Computed is mandatory for computed fields", field.getName()));
9392 }
9493 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +32 −32
@@ -15,21 +15,20 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.lang.annotation.Annotation;
19-import java.lang.reflect.Field;
20-import java.lang.reflect.*;
21-import java.util.*;
22-import java.util.concurrent.atomic.AtomicInteger;
23-
24-import com.google.common.base.Strings;
25-import com.google.common.collect.Maps;
26-import com.google.common.reflect.TypeToken;
27-
2818 import com.datastax.driver.core.ConsistencyLevel;
2919 import com.datastax.driver.core.TypeCodec;
3020 import com.datastax.driver.core.UserType;
3121 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
3222 import com.datastax.driver.mapping.annotations.*;
23+import com.google.common.base.Strings;
24+import com.google.common.collect.Maps;
25+import com.google.common.reflect.TypeToken;
26+
27+import java.lang.annotation.Annotation;
28+import java.lang.reflect.Field;
29+import java.lang.reflect.*;
30+import java.util.*;
31+import java.util.concurrent.atomic.AtomicInteger;
3332
3433 /**
3534 * Static metods that facilitates parsing class annotations into the corresponding {@link EntityMapper}.
@@ -42,7 +41,8 @@
4241 }
4342 };
4443
45- private AnnotationParser() {}
44+ private AnnotationParser() {
45+ }
4646
4747 public static <T> EntityMapper<T> parseEntity(Class<T> entityClass, EntityMapper.Factory factory, MappingManager mappingManager) {
4848 Table table = AnnotationChecks.getTypeAnnotation(Table.class, entityClass);
@@ -57,9 +57,9 @@
5757 ksName = mappingManager.getSession().getLoggedKeyspace();
5858 if (Strings.isNullOrEmpty(ksName))
5959 throw new IllegalArgumentException(String.format(
60- "Error creating mapper for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
61- entityClass.getSimpleName(),
62- Table.class.getSimpleName()
60+ "Error creating mapper for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
61+ entityClass.getSimpleName(),
62+ Table.class.getSimpleName()
6363 ));
6464 }
6565
@@ -70,15 +70,15 @@
7070 List<Field> rgs = new ArrayList<Field>();
7171
7272 for (Field field : entityClass.getDeclaredFields()) {
73- if(field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
73+ if (field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
7474 continue;
7575
7676 if (mappingManager.isCassandraV1 && field.getAnnotation(Computed.class) != null)
7777 throw new UnsupportedOperationException("Computed fields are not supported with native protocol v1");
7878
7979 AnnotationChecks.validateAnnotations(field, "entity",
80- Column.class, ClusteringColumn.class, Frozen.class, FrozenKey.class,
81- FrozenValue.class, PartitionKey.class, Transient.class, Computed.class);
80+ Column.class, ClusteringColumn.class, Frozen.class, FrozenKey.class,
81+ FrozenValue.class, PartitionKey.class, Transient.class, Computed.class);
8282
8383 if (field.getAnnotation(Transient.class) != null)
8484 continue;
@@ -105,8 +105,8 @@
105105 validateOrder(ccs, "@ClusteringColumn");
106106
107107 mapper.addColumns(createColumnMappers(pks, factory, mapper.entityClass, mappingManager, columnCounter),
108- createColumnMappers(ccs, factory, mapper.entityClass, mappingManager, columnCounter),
109- createColumnMappers(rgs, factory, mapper.entityClass, mappingManager, columnCounter));
108+ createColumnMappers(ccs, factory, mapper.entityClass, mappingManager, columnCounter),
109+ createColumnMappers(rgs, factory, mapper.entityClass, mappingManager, columnCounter));
110110 return mapper;
111111 }
112112
@@ -130,9 +130,9 @@
130130 ksName = mappingManager.getSession().getLoggedKeyspace();
131131 if (Strings.isNullOrEmpty(ksName))
132132 throw new IllegalArgumentException(String.format(
133- "Error creating UDT codec for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
134- udtClass.getSimpleName(),
135- UDT.class.getSimpleName()
133+ "Error creating UDT codec for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
134+ udtClass.getSimpleName(),
135+ UDT.class.getSimpleName()
136136 ));
137137 }
138138
@@ -141,12 +141,12 @@
141141 List<Field> columns = new ArrayList<Field>();
142142
143143 for (Field field : udtClass.getDeclaredFields()) {
144- if(field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
144+ if (field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
145145 continue;
146146
147147 AnnotationChecks.validateAnnotations(field, "UDT",
148- com.datastax.driver.mapping.annotations.Field.class, Frozen.class, FrozenKey.class,
149- FrozenValue.class, Transient.class);
148+ com.datastax.driver.mapping.annotations.Field.class, Frozen.class, FrozenKey.class,
149+ FrozenValue.class, Transient.class);
150150
151151 if (field.getAnnotation(Transient.class) != null)
152152 continue;
@@ -182,7 +182,7 @@
182182 int pos = position(field);
183183 if (pos != i)
184184 throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of column %s, was expecting %d",
185- pos, annotation, field.getName(), i));
185+ pos, annotation, field.getName(), i));
186186 }
187187 }
188188
@@ -220,7 +220,7 @@
220220 Column column = field.getAnnotation(Column.class);
221221 Computed computedField = field.getAnnotation(Computed.class);
222222 if (column != null && !column.name().isEmpty()) {
223- if (computedField != null){
223+ if (computedField != null) {
224224 throw new IllegalArgumentException("Cannot use @Column and @Computed on the same field");
225225 }
226226 return column.caseSensitive() ? column.name() : column.name().toLowerCase();
@@ -251,12 +251,12 @@
251251
252252 try {
253253 @SuppressWarnings("unchecked")
254- TypeCodec<Object> instance = (TypeCodec<Object>)codecClass.newInstance();
254+ TypeCodec<Object> instance = (TypeCodec<Object>) codecClass.newInstance();
255255 return instance;
256256 } catch (Exception e) {
257257 throw new IllegalArgumentException(String.format(
258- "Cannot create an instance of custom codec %s for field %s",
259- codecClass, field
258+ "Cannot create an instance of custom codec %s for field %s",
259+ codecClass, field
260260 ), e);
261261 }
262262 }
@@ -296,7 +296,7 @@
296296 Class<? extends TypeCodec<?>> codecClass = null;
297297 for (Annotation a : paramAnnotations[i]) {
298298 if (a.annotationType().equals(Param.class)) {
299- Param param = (Param)a;
299+ Param param = (Param) a;
300300 paramName = param.value();
301301 if (paramName.isEmpty())
302302 paramName = null;
@@ -332,7 +332,7 @@
332332 return factory.create(accClass, methods);
333333 }
334334
335- @SuppressWarnings({ "unchecked", "rawtypes" })
335+ @SuppressWarnings({"unchecked", "rawtypes"})
336336 private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Class<? extends TypeCodec<?>> codecClass, Type paramType, Annotation[] paramAnnotations, MappingManager mappingManager) {
337337 if (paramType instanceof Class) {
338338 Class<?> paramClass = (Class<?>) paramType;
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +15 −12
@@ -15,22 +15,25 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.lang.reflect.Field;
19-import java.util.concurrent.atomic.AtomicInteger;
20-
21-import com.google.common.reflect.TypeToken;
22-
2318 import com.datastax.driver.core.Metadata;
2419 import com.datastax.driver.core.TypeCodec;
20+import com.google.common.reflect.TypeToken;
21+
22+import java.lang.reflect.Field;
23+import java.util.concurrent.atomic.AtomicInteger;
2524
2625 abstract class ColumnMapper<T> {
2726
28- public enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED};
27+ public enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED}
28+
29+ ;
2930
3031 private final String columnName;
3132 private final String alias;
3233 protected final String fieldName;
33- /** The type of the Java field in the mapped class */
34+ /**
35+ * The type of the Java field in the mapped class
36+ */
3437 protected final TypeToken<Object> fieldType;
3538 protected final Kind kind;
3639 protected final int position;
@@ -40,10 +43,10 @@
4043 protected ColumnMapper(Field field, int position, AtomicInteger columnCounter) {
4144 this.columnName = AnnotationParser.columnName(field);
4245 this.alias = (columnCounter != null)
43- ? AnnotationParser.newAlias(field, columnCounter.incrementAndGet())
44- : null;
46+ ? AnnotationParser.newAlias(field, columnCounter.incrementAndGet())
47+ : null;
4548 this.fieldName = field.getName();
46- this.fieldType = (TypeToken<Object>)TypeToken.of(field.getGenericType());
49+ this.fieldType = (TypeToken<Object>) TypeToken.of(field.getGenericType());
4750 this.kind = AnnotationParser.kind(field);
4851 this.position = position;
4952 this.customCodec = AnnotationParser.customCodec(field);
@@ -55,8 +58,8 @@
5558
5659 public String getColumnName() {
5760 return kind == Kind.COMPUTED
58- ? columnName
59- : Metadata.quote(columnName);
61+ ? columnName
62+ : Metadata.quote(columnName);
6063 }
6164
6265 public String getAlias() {
modified driver-mapping/src/main/java/com/datastax/driver/mapping/EntityMapper.java +5 −2
@@ -15,11 +15,13 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18+import com.datastax.driver.core.ConsistencyLevel;
19+
1820 import java.lang.reflect.Field;
19-import java.util.*;
21+import java.util.ArrayList;
22+import java.util.List;
2023 import java.util.concurrent.atomic.AtomicInteger;
2124
22-import com.datastax.driver.core.ConsistencyLevel;
2325 import static com.datastax.driver.core.querybuilder.QueryBuilder.quote;
2426
2527 abstract class EntityMapper<T> {
@@ -84,6 +86,7 @@
8486
8587 interface Factory {
8688 public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency);
89+
8790 public <T> ColumnMapper<T> createColumnMapper(Class<T> componentClass, Field field, int position, MappingManager mappingManager, AtomicInteger columnCounter);
8891 }
8992 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +2 −6
@@ -15,15 +15,11 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18+import com.datastax.driver.core.*;
19+
1820 import java.nio.ByteBuffer;
19-import java.util.List;
2021 import java.util.Map;
2122
22-import com.google.common.collect.Lists;
23-
24-import com.datastax.driver.core.*;
25-import com.datastax.driver.core.exceptions.InvalidTypeException;
26-
2723 /**
2824 * Serializes a class annotated with {@code @UDT} to the corresponding CQL user-defined type.
2925 */
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +69 −59
@@ -15,8 +15,13 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.querybuilder.Delete;
20+import com.datastax.driver.core.querybuilder.Insert;
21+import com.datastax.driver.core.querybuilder.QueryBuilder;
22+import com.datastax.driver.mapping.Mapper.Option.SaveNullFields;
23+import com.datastax.driver.mapping.annotations.Accessor;
24+import com.datastax.driver.mapping.annotations.Computed;
2025 import com.google.common.base.Function;
2126 import com.google.common.base.Functions;
2227 import com.google.common.base.Objects;
@@ -26,21 +31,14 @@
2631 import org.slf4j.Logger;
2732 import org.slf4j.LoggerFactory;
2833
29-import static com.google.common.base.Preconditions.checkArgument;
30-
31-import com.datastax.driver.core.*;
32-import com.datastax.driver.core.querybuilder.Delete;
33-import com.datastax.driver.core.querybuilder.Insert;
34-import com.datastax.driver.core.querybuilder.QueryBuilder;
35-import com.datastax.driver.mapping.Mapper.Option.SaveNullFields;
36-import com.datastax.driver.mapping.annotations.Accessor;
37-import com.datastax.driver.mapping.annotations.Computed;
34+import java.util.*;
3835
3936 import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS;
37+import static com.google.common.base.Preconditions.checkArgument;
4038
4139 /**
4240 * An object handling the mapping of a particular class.
43- * <p>
41+ * <p/>
4442 * A {@code Mapper} object is obtained from a {@code MappingManager} using the
4543 * {@link MappingManager#mapper} method.
4644 */
@@ -148,7 +146,7 @@
148146
149147 /**
150148 * Creates a query that can be used to save the provided entity.
151- * <p>
149+ * <p/>
152150 * This method is useful if you want to setup a number of options (tracing,
153151 * conistency level, ...) of the returned statement before executing it manually
154152 * or need access to the {@code ResultSet} object after execution (to get the
@@ -164,7 +162,7 @@
164162
165163 /**
166164 * Creates a query that can be used to save the provided entity.
167- * <p>
165+ * <p/>
168166 * This method is useful if you want to setup a number of options (tracing,
169167 * conistency level, ...) of the returned statement before executing it manually
170168 * or need access to the {@code ResultSet} object after execution (to get the
@@ -217,7 +215,7 @@
217215 }
218216
219217 private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) {
220- SaveNullFields option = (SaveNullFields)options.get(SAVE_NULL_FIELDS);
218+ SaveNullFields option = (SaveNullFields) options.get(SAVE_NULL_FIELDS);
221219 return option == null || option.saveNullFields;
222220 }
223221
@@ -231,7 +229,7 @@
231229
232230 /**
233231 * Save an entity mapped by this mapper.
234- * <p>
232+ * <p/>
235233 * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}.
236234 *
237235 * @param entity the entity to save.
@@ -260,7 +258,7 @@
260258
261259 /**
262260 * Save an entity mapped by this mapper asynchronously.
263- * <p>
261+ * <p/>
264262 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}.
265263 *
266264 * @param entity the entity to save.
@@ -272,7 +270,7 @@
272270
273271 /**
274272 * Save an entity mapped by this mapper asynchronously using special options for save.
275- * <p>
273+ * <p/>
276274 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity, options))}.
277275 *
278276 * @param entity the entity to save.
@@ -285,14 +283,14 @@
285283
286284 /**
287285 * Creates a query to fetch entity given its PRIMARY KEY.
288- * <p>
286+ * <p/>
289287 * The values provided must correspond to the columns composing the PRIMARY
290288 * KEY (in the order of said primary key).
291- * <p>
289+ * <p/>
292290 * This method is useful if you want to setup a number of options (tracing,
293291 * conistency level, ...) of the returned statement before executing it manually,
294292 * but in other cases, calling {@link #get} or {@link #getAsync} is shorter.
295- * <p>
293+ * <p/>
296294 * This method allows you to provide a suite of {@link Option} to include in
297295 * the GET query. Options currently supported for GET are :
298296 * <ul>
@@ -315,7 +313,7 @@
315313
316314 for (Object o : objects) {
317315 if (o instanceof Option) {
318- Option option = (Option)o;
316+ Option option = (Option) o;
319317 options.put(option.type, option);
320318 } else {
321319 pks.add(o);
@@ -354,7 +352,7 @@
354352
355353 /**
356354 * Fetch an entity based on its primary key.
357- * <p>
355+ * <p/>
358356 * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(objects))).one()}.
359357 *
360358 * @param objects the primary key of the entity to fetch, or more precisely
@@ -371,7 +369,7 @@
371369
372370 /**
373371 * Fetch an entity based on its primary key asynchronously.
374- * <p>
372+ * <p/>
375373 * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(objects))}.
376374 *
377375 * @param objects the primary key of the entity to fetch, or more precisely
@@ -389,19 +387,19 @@
389387
390388 /**
391389 * Creates a query that can be used to delete the provided entity.
392- * <p>
390+ * <p/>
393391 * This method is a shortcut that extract the PRIMARY KEY from the
394392 * provided entity and call {@link #deleteQuery(Object...)} with it.
395393 * This method allows you to provide a suite of {@link Option} to include in
396394 * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
397395 * is supported for DELETE queries.
398- * <p>
396+ * <p/>
399397 * This method is useful if you want to setup a number of options (tracing,
400398 * conistency level, ...) of the returned statement before executing it manually
401399 * or need access to the {@code ResultSet} object after execution (to get the
402400 * trace, the execution info, ...), but in other cases, calling {@link #delete}
403401 * or {@link #deleteAsync} is shorter.
404- * <p>
402+ * <p/>
405403 * This method allows you to provide a suite of {@link Option} to include in
406404 * the DELETE query. Options currently supported for DELETE are :
407405 * <ul>
@@ -426,10 +424,10 @@
426424
427425 /**
428426 * Creates a query that can be used to delete the provided entity.
429- * <p>
427+ * <p/>
430428 * This method is a shortcut that extract the PRIMARY KEY from the
431429 * provided entity and call {@link #deleteQuery(Object...)} with it.
432- * <p>
430+ * <p/>
433431 * This method is useful if you want to setup a number of options (tracing,
434432 * conistency level, ...) of the returned statement before executing it manually
435433 * or need access to the {@code ResultSet} object after execution (to get the
@@ -450,13 +448,13 @@
450448
451449 /**
452450 * Creates a query that can be used to delete an entity given its PRIMARY KEY.
453- * <p>
451+ * <p/>
454452 * The values provided must correspond to the columns composing the PRIMARY
455453 * KEY (in the order of said primary key). The values can also contain, after
456454 * specifying the primary keys columns, a suite of {@link Option} to include in
457455 * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
458456 * is supported for DELETE queries.
459- * <p>
457+ * <p/>
460458 * This method is useful if you want to setup a number of options (tracing,
461459 * conistency level, ...) of the returned statement before executing it manually
462460 * or need access to the {@code ResultSet} object after execution (to get the
@@ -486,7 +484,7 @@
486484
487485 for (Object o : objects) {
488486 if (o instanceof Option) {
489- Option option = (Option)o;
487+ Option option = (Option) o;
490488 options.put(option.type, option);
491489 } else {
492490 pks.add(o);
@@ -526,7 +524,7 @@
526524
527525 /**
528526 * Deletes an entity mapped by this mapper.
529- * <p>
527+ * <p/>
530528 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity))}.
531529 *
532530 * @param entity the entity to delete.
@@ -537,7 +535,7 @@
537535
538536 /**
539537 * Deletes an entity mapped by this mapper using provided options.
540- * <p>
538+ * <p/>
541539 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity, options))}.
542540 *
543541 * @param entity the entity to delete.
@@ -549,7 +547,7 @@
549547
550548 /**
551549 * Deletes an entity mapped by this mapper asynchronously.
552- * <p>
550+ * <p/>
553551 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity))}.
554552 *
555553 * @param entity the entity to delete.
@@ -561,7 +559,7 @@
561559
562560 /**
563561 * Deletes an entity mapped by this mapper asynchronously using provided options.
564- * <p>
562+ * <p/>
565563 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity, options))}.
566564 *
567565 * @param entity the entity to delete.
@@ -574,7 +572,7 @@
574572
575573 /**
576574 * Deletes an entity based on its primary key.
577- * <p>
575+ * <p/>
578576 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(objects))}.
579577 *
580578 * @param objects the primary key of the entity to delete, or more precisely
@@ -591,7 +589,7 @@
591589
592590 /**
593591 * Deletes an entity based on its primary key asynchronously.
594- * <p>
592+ * <p/>
595593 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(objects))}.
596594 *
597595 * @param objects the primary key of the entity to delete, or more precisely
@@ -608,7 +606,7 @@
608606
609607 /**
610608 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
611- * <p>
609+ * <p/>
612610 * Use this method to map a result set that was not generated by the mapper (e.g. a result set coming from a
613611 * manual query or an {@link Accessor method}.
614612 * It expects that the result set contains all column mapped in the target class,
@@ -619,7 +617,6 @@
619617 * will encapsulate {@code resultSet} and so consuming results from this
620618 * returned mapped result set will consume results from {@code resultSet}
621619 * and vice-versa.
622- *
623620 * @see #mapAliased(ResultSet)
624621 */
625622 public Result<T> map(ResultSet resultSet) {
@@ -628,7 +625,7 @@
628625
629626 /**
630627 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
631- * <p>
628+ * <p/>
632629 * Use this method to map a result set coming from the execution of the {@code Statement} returned by
633630 * {@link #getQuery(Object...)}. {@link Computed} fields will be filled in the mapped object.
634631 *
@@ -637,13 +634,12 @@
637634 * will encapsulate {@code resultSet} and so consuming results from this
638635 * returned mapped result set will consume results from {@code resultSet}
639636 * and vice-versa.
640- *
641637 * @see #map(ResultSet)
642638 */
643639 public Result<T> mapAliased(ResultSet resultSet) {
644640 return (manager.isCassandraV1)
645- ? map(resultSet) // no aliases
646- : new Result<T>(resultSet, mapper, protocolVersion, true);
641+ ? map(resultSet) // no aliases
642+ : new Result<T>(resultSet, mapper, protocolVersion, true);
647643 }
648644
649645 /**
@@ -719,20 +715,20 @@
719715
720716 /**
721717 * An option for a mapper operation.
722- * <p>
718+ * <p/>
723719 * Options can be passed to individual operations:
724720 * <pre>
725721 * mapper.save(myObject, Option.ttl(3600));
726722 * </pre>
727- *
723+ * <p/>
728724 * The mapper can also have defaults, that will apply to all operations that do not
729725 * override these particular option:
730726 * <pre>
731727 * mapper.setDefaultSaveOptions(Option.ttl(3600));
732728 * mapper.save(myObject);
733729 * </pre>
734- *
735- * <p>
730+ * <p/>
731+ * <p/>
736732 * See the static methods in this class for available options.
737733 */
738734 public static abstract class Option {
@@ -748,7 +744,7 @@
748744 /**
749745 * Creates a new Option object to add time-to-live to a mapper operation. This is
750746 * only valid for save operations.
751- * <p>
747+ * <p/>
752748 * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
753749 *
754750 * @param ttl the TTL (in seconds).
@@ -761,7 +757,7 @@
761757 /**
762758 * Creates a new Option object to add a timestamp to a mapper operation. This is
763759 * only valid for save and delete operations.
764- * <p>
760+ * <p/>
765761 * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
766762 *
767763 * @param timestamp the timestamp (in microseconds).
@@ -774,7 +770,7 @@
774770 /**
775771 * Creates a new Option object to add a consistency level value to a mapper operation. This
776772 * is valid for save, delete and get operations.
777- * <p>
773+ * <p/>
778774 * Note that the consistency level can also be defined at the mapper level, as a parameter
779775 * of the {@link com.datastax.driver.mapping.annotations.Table} annotation (this is redundant
780776 * for backward compatibility). This option, whether defined on a specific call or as the
@@ -801,17 +797,17 @@
801797 /**
802798 * Creates a new Option object to specify whether null entity fields should be included in
803799 * insert queries. This option is valid only for save operations.
804- *
800+ * <p/>
805801 * If this option is not specified, it defaults to {@code true} (null fields are saved).
806802 *
807803 * @param enabled whether to include null fields in queries.
808804 * @return the option.
809805 */
810- public static Option saveNullFields(boolean enabled){
806+ public static Option saveNullFields(boolean enabled) {
811807 return new SaveNullFields(enabled);
812808 }
813809
814- public Type getType(){
810+ public Type getType() {
815811 return this.type;
816812 }
817813
@@ -837,19 +833,23 @@
837833 void appendTo(Insert.Options usings) {
838834 usings.and(QueryBuilder.ttl(QueryBuilder.bindMarker()));
839835 }
836+
840837 @Override
841838 void appendTo(Delete.Options usings) {
842839 throw new UnsupportedOperationException("shouldn't be called");
843840 }
841+
844842 @Override
845843 void addToPreparedStatement(BoundStatement bs, int i) {
846844 bs.setInt(i, this.ttlValue);
847845 }
846+
848847 @Override
849848 void checkValidFor(QueryType qt, MappingManager manager) {
850849 checkArgument(!manager.isCassandraV1, "TTL option requires native protocol v2 or above");
851850 checkArgument(qt == QueryType.SAVE, "TTL option is only allowed in save queries");
852851 }
852+
853853 @Override
854854 boolean isIncludedInQuery() {
855855 return true;
@@ -864,23 +864,28 @@
864864 super(Type.TIMESTAMP);
865865 this.tsValue = value;
866866 }
867+
867868 @Override
868869 void appendTo(Insert.Options usings) {
869870 usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
870871 }
872+
871873 @Override
872874 void appendTo(Delete.Options usings) {
873875 usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
874876 }
877+
875878 @Override
876879 void checkValidFor(QueryType qt, MappingManager manager) {
877880 checkArgument(!manager.isCassandraV1, "Timestamp option requires native protocol v2 or above");
878881 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL, "Timestamp option is only allowed in save and delete queries");
879882 }
883+
880884 @Override
881885 void addToPreparedStatement(BoundStatement bs, int i) {
882886 bs.setLong(i, this.tsValue);
883887 }
888+
884889 @Override
885890 boolean isIncludedInQuery() {
886891 return true;
@@ -895,10 +900,12 @@
895900 super(Type.CL);
896901 this.cl = cl;
897902 }
903+
898904 @Override
899905 void appendTo(Insert.Options usings) {
900906 throw new UnsupportedOperationException("shouldn't be called");
901907 }
908+
902909 @Override
903910 void appendTo(Delete.Options usings) {
904911 throw new UnsupportedOperationException("shouldn't be called");
@@ -908,10 +915,11 @@
908915 void addToPreparedStatement(BoundStatement bs, int i) {
909916 bs.setConsistencyLevel(cl);
910917 }
918+
911919 @Override
912920 void checkValidFor(QueryType qt, MappingManager manager) {
913921 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
914- "Consistency level option is only allowed in save, delete and get queries");
922+ "Consistency level option is only allowed in save, delete and get queries");
915923 }
916924
917925 @Override
@@ -928,10 +936,12 @@
928936 super(Type.TRACING);
929937 this.tracing = tracing;
930938 }
939+
931940 @Override
932941 void appendTo(Insert.Options usings) {
933942 throw new UnsupportedOperationException("shouldn't be called");
934943 }
944+
935945 @Override
936946 void appendTo(Delete.Options usings) {
937947 throw new UnsupportedOperationException("shouldn't be called");
@@ -946,7 +956,7 @@
946956 @Override
947957 void checkValidFor(QueryType qt, MappingManager manager) {
948958 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
949- "Tracing option is only allowed in save, delete and get queries");
959+ "Tracing option is only allowed in save, delete and get queries");
950960 }
951961
952962 @Override
@@ -1015,10 +1025,10 @@
10151025 if (this == other)
10161026 return true;
10171027 if (other instanceof MapperQueryKey) {
1018- MapperQueryKey that = (MapperQueryKey)other;
1028+ MapperQueryKey that = (MapperQueryKey) other;
10191029 return this.queryType.equals(that.queryType)
1020- && this.optionTypes.equals(that.optionTypes)
1021- && this.columns.equals(that.columns);
1030+ && this.optionTypes.equals(that.optionTypes)
1031+ && this.columns.equals(that.columns);
10221032 }
10231033 return false;
10241034 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +23 −24
@@ -15,10 +15,6 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.Collections;
19-import java.util.HashMap;
20-import java.util.Map;
21-
2218 import com.datastax.driver.core.ProtocolVersion;
2319 import com.datastax.driver.core.Session;
2420 import com.datastax.driver.core.TypeCodec;
@@ -26,6 +22,10 @@
2622 import com.datastax.driver.mapping.annotations.Table;
2723 import com.datastax.driver.mapping.annotations.UDT;
2824
25+import java.util.Collections;
26+import java.util.HashMap;
27+import java.util.Map;
28+
2929 /**
3030 * Mapping manager from which to obtain entity mappers.
3131 */
@@ -40,7 +40,7 @@
4040
4141 /**
4242 * Creates a new {@code MappingManager} using the provided {@code Session}.
43- * <p>
43+ * <p/>
4444 * Note that this constructor forces the initialization of the session (see
4545 * {@link #MappingManager(Session, ProtocolVersion)} if that is a problem for you).
4646 *
@@ -57,15 +57,14 @@
5757
5858 /**
5959 * Creates a new {@code MappingManager} using the provided {@code Session}.
60- * <p>
60+ * <p/>
6161 * This constructor is only provided for backward compatibility: before 2.1.7, {@code MappingManager} could be
6262 * built from an uninitialized session; since 2.1.7, the mapper needs to know the active protocol version to
6363 * adapt its internal requests, so {@link #MappingManager(Session)} will now initialize the session if needed.
6464 * If you rely on the session not being initialized, use this constructor and provide the version manually.
6565 *
66- * @param session the {@code Session} to use.
66+ * @param session the {@code Session} to use.
6767 * @param protocolVersion the protocol version that will be used with this session.
68- *
6968 * @since 2.1.7
7069 */
7170 public MappingManager(Session session, ProtocolVersion protocolVersion) {
@@ -79,10 +78,10 @@
7978
8079 /**
8180 * The underlying {@code Session} used by this manager.
82- * <p>
81+ * <p/>
8382 * Note that you can get obtain the {@code Cluster} object corresponding
8483 * to that session using {@code getSession().getCluster()}.
85- * <p>
84+ * <p/>
8685 * It is inadvisable to close the returned Session while this manager and
8786 * its mappers are in use.
8887 *
@@ -95,15 +94,15 @@
9594 /**
9695 * Creates a {@code Mapper} for the provided class (that must be annotated by a
9796 * {@link Table} annotation).
98- * <p>
97+ * <p/>
9998 * The {@code MappingManager} only ever keeps one Mapper for each class, and so calling this
10099 * method multiple times on the same class will always return the same object.
101- * <p>
100+ * <p/>
102101 * If the type of any field in the class is an {@link UDT}-annotated classes, a codec for that
103102 * class will automatically be created and registered with the underlying {@code Cluster}.
104103 * This works recursively with UDTs nested in other UDTs or in collections.
105104 *
106- * @param <T> the type of the class to map.
105+ * @param <T> the type of the class to map.
107106 * @param klass the (annotated) class for which to return the mapper.
108107 * @return the {@code Mapper} object for class {@code klass}.
109108 */
@@ -114,15 +113,15 @@
114113 /**
115114 * Creates a {@code TypeCodec} for the provided class (that must be annotated by
116115 * a {@link UDT} annotation).
117- * <p>
116+ * <p/>
118117 * This method also registers the codec against the underlying {@code Cluster}.
119118 * In addition, the codecs for any nested UDTs will also be created and registered.
120- * <p>
119+ * <p/>
121120 * You don't need to call this method explicitly if you already call {@link #mapper(Class)}
122121 * for a class that references this UDT class (creating a mapper will automatically
123122 * process all UDTs that it uses).
124123 *
125- * @param <T> the type of the class to map.
124+ * @param <T> the type of the class to map.
126125 * @param klass the (annotated) class for which to return the codec.
127126 * @return the codec that maps the provided class to the corresponding user-defined type.
128127 */
@@ -133,11 +132,11 @@
133132 /**
134133 * Creates an accessor object based on the provided interface (that must be annotated by
135134 * a {@link Accessor} annotation).
136- * <p>
135+ * <p/>
137136 * The {@code MappingManager} only ever keep one Accessor for each class, and so calling this
138137 * method multiple time on the same class will always return the same object.
139138 *
140- * @param <T> the type of the accessor class.
139+ * @param <T> the type of the accessor class.
141140 * @param klass the (annotated) class for which to create an accessor object.
142141 * @return the accessor object for class {@code klass}.
143142 */
@@ -147,10 +146,10 @@
147146
148147 @SuppressWarnings("unchecked")
149148 private <T> Mapper<T> getMapper(Class<T> klass) {
150- Mapper<T> mapper = (Mapper<T>)mappers.get(klass);
149+ Mapper<T> mapper = (Mapper<T>) mappers.get(klass);
151150 if (mapper == null) {
152151 synchronized (mappers) {
153- mapper = (Mapper<T>)mappers.get(klass);
152+ mapper = (Mapper<T>) mappers.get(klass);
154153 if (mapper == null) {
155154 EntityMapper<T> entityMapper = AnnotationParser.parseEntity(klass, ReflectionMapper.factory(), this);
156155 mapper = new Mapper<T>(this, klass, entityMapper);
@@ -165,10 +164,10 @@
165164
166165 @SuppressWarnings("unchecked")
167166 <T> TypeCodec<T> getUDTCodec(Class<T> mappedClass) {
168- MappedUDTCodec<T> codec = (MappedUDTCodec<T>)udtCodecs.get(mappedClass);
167+ MappedUDTCodec<T> codec = (MappedUDTCodec<T>) udtCodecs.get(mappedClass);
169168 if (codec == null) {
170169 synchronized (udtCodecs) {
171- codec = (MappedUDTCodec<T>)udtCodecs.get(mappedClass);
170+ codec = (MappedUDTCodec<T>) udtCodecs.get(mappedClass);
172171 if (codec == null) {
173172 codec = AnnotationParser.parseUDT(mappedClass, ReflectionMapper.factory(), this);
174173 session.getCluster().getConfiguration().getCodecRegistry().register(codec);
@@ -184,10 +183,10 @@
184183
185184 @SuppressWarnings("unchecked")
186185 private <T> T getAccessor(Class<T> klass) {
187- T accessor = (T)accessors.get(klass);
186+ T accessor = (T) accessors.get(klass);
188187 if (accessor == null) {
189188 synchronized (accessors) {
190- accessor = (T)accessors.get(klass);
189+ accessor = (T) accessors.get(klass);
191190 if (accessor == null) {
192191 AccessorMapper<T> mapper = AnnotationParser.parseAccessor(klass, AccessorReflectionMapper.factory(), this);
193192 mapper.prepare(this);
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +20 −21
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.lang.reflect.Method;
19-import java.lang.reflect.ParameterizedType;
20-import java.lang.reflect.Type;
21-import java.util.Set;
22-
18+import com.datastax.driver.core.*;
2319 import com.google.common.collect.Sets;
2420 import com.google.common.reflect.TypeToken;
2521 import com.google.common.util.concurrent.Futures;
2622 import com.google.common.util.concurrent.ListenableFuture;
2723
28-import com.datastax.driver.core.*;
24+import java.lang.reflect.Method;
25+import java.lang.reflect.ParameterizedType;
26+import java.lang.reflect.Type;
27+import java.util.Set;
2928
3029 // TODO: we probably should make that an abstract class and move some bit in a "ReflexionMethodMapper"
3130 // subclass for consistency with the rest, but we can see to that later
@@ -78,8 +77,8 @@
7877
7978 if (ListenableFuture.class.isAssignableFrom(returnType)) {
8079 this.async = true;
81- Type k = ((ParameterizedType)method.getGenericReturnType()).getActualTypeArguments()[0];
82- if (k instanceof Class && ResultSet.class.isAssignableFrom((Class<?>)k))
80+ Type k = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0];
81+ if (k instanceof Class && ResultSet.class.isAssignableFrom((Class<?>) k))
8382 return;
8483
8584 mapType(manager, returnType, k);
@@ -101,13 +100,13 @@
101100
102101 if (method.getParameterTypes().length < names.size())
103102 throw new IllegalArgumentException(String.format("Not enough arguments for method %s, "
104- + "found %d but it should be at least the number of unique bind parameter names in the @Query (%d)",
105- method.getName(), method.getParameterTypes().length, names.size()));
103+ + "found %d but it should be at least the number of unique bind parameter names in the @Query (%d)",
104+ method.getName(), method.getParameterTypes().length, names.size()));
106105
107106 if (method.getParameterTypes().length > variables.size())
108107 throw new IllegalArgumentException(String.format("Too many arguments for method %s, "
109- + "found %d but it should be at most the number of bind parameters in the @Query (%d)",
110- method.getName(), method.getParameterTypes().length, variables.size()));
108+ + "found %d but it should be at most the number of bind parameters in the @Query (%d)",
109+ method.getName(), method.getParameterTypes().length, variables.size()));
111110
112111 // TODO could go further, e.g. check that the types match, inspect @Param annotations to check that all names are bound...
113112 }
@@ -116,9 +115,9 @@
116115 private void mapType(MappingManager manager, Class<?> fullReturnType, Type type) {
117116
118117 if (type instanceof ParameterizedType) {
119- ParameterizedType pt = (ParameterizedType)type;
118+ ParameterizedType pt = (ParameterizedType) type;
120119 Type raw = pt.getRawType();
121- if (raw instanceof Class && Result.class.isAssignableFrom((Class)raw)) {
120+ if (raw instanceof Class && Result.class.isAssignableFrom((Class) raw)) {
122121 type = pt.getActualTypeArguments()[0];
123122 } else {
124123 mapOne = true;
@@ -131,7 +130,7 @@
131130 throw new RuntimeException(String.format("Cannot map return of method %s to unsupported type %s", method, type));
132131
133132 try {
134- this.returnMapper = (Mapper<?>)manager.mapper((Class<?>)type);
133+ this.returnMapper = (Mapper<?>) manager.mapper((Class<?>) type);
135134 } catch (Exception e) {
136135 throw new RuntimeException("Cannot map return to class " + fullReturnType, e);
137136 }
@@ -162,8 +161,8 @@
162161 return future;
163162
164163 return mapOne
165- ? Futures.transform(future, returnMapper.mapOneFunctionWithoutAliases)
166- : Futures.transform(future, returnMapper.mapAllFunctionWithoutAliases);
164+ ? Futures.transform(future, returnMapper.mapOneFunctionWithoutAliases)
165+ : Futures.transform(future, returnMapper.mapAllFunctionWithoutAliases);
167166 } else {
168167 ResultSet rs = session.execute(bs);
169168 if (returnMapper == null)
@@ -185,13 +184,13 @@
185184 public ParamMapper(String paramName, int paramIdx, TypeToken<?> paramType, Class<? extends TypeCodec<?>> codecClass) {
186185 this.paramName = paramName;
187186 this.paramIdx = paramIdx;
188- this.paramType = (TypeToken<Object>)paramType;
187+ this.paramType = (TypeToken<Object>) paramType;
189188 try {
190- this.codec = (codecClass == null) ? null : (TypeCodec<Object>)codecClass.newInstance();
189+ this.codec = (codecClass == null) ? null : (TypeCodec<Object>) codecClass.newInstance();
191190 } catch (Exception e) {
192191 throw new IllegalArgumentException(String.format(
193- "Cannot create instance of codec %s for parameter %s",
194- codecClass, (paramName == null) ? paramIdx : paramName
192+ "Cannot create instance of codec %s for parameter %s",
193+ codecClass, (paramName == null) ? paramIdx : paramName
195194 ), e);
196195 }
197196 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +21 −22
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.ArrayList;
19-import java.util.Collection;
20-import java.util.List;
21-import java.util.Set;
22-
23-import com.google.common.base.Objects;
24-
2518 import com.datastax.driver.core.TableMetadata;
2619 import com.datastax.driver.core.querybuilder.Delete;
2720 import com.datastax.driver.core.querybuilder.Insert;
2821 import com.datastax.driver.core.querybuilder.Select;
22+import com.google.common.base.Objects;
23+
24+import java.util.ArrayList;
25+import java.util.Collection;
26+import java.util.List;
27+import java.util.Set;
2928
3029 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3130
@@ -61,12 +60,12 @@
6160 switch (kind) {
6261 case SAVE: {
6362 Insert insert = table == null
64- ? insertInto(mapper.getKeyspace(), mapper.getTable())
65- : insertInto(table);
63+ ? insertInto(mapper.getKeyspace(), mapper.getTable())
64+ : insertInto(table);
6665 for (ColumnMapper<?> cm : columns)
6766 if (cm.kind != ColumnMapper.Kind.COMPUTED)
6867 insert.value(cm.getColumnName(), bindMarker());
69-
68+
7069 Insert.Options usings = insert.using();
7170 for (Mapper.Option opt : options) {
7271 opt.checkValidFor(QueryType.SAVE, manager);
@@ -79,8 +78,8 @@
7978 Select.Selection selection = select();
8079 for (ColumnMapper cm : mapper.allColumns()) {
8180 Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED)
82- ? ((Select.SelectionOrAlias)selection).raw(cm.getColumnName())
83- : selection.column(cm.getColumnName());
81+ ? ((Select.SelectionOrAlias) selection).raw(cm.getColumnName())
82+ : selection.column(cm.getColumnName());
8483
8584 if (cm.getAlias() == null) {
8685 selection = column;
@@ -97,15 +96,15 @@
9796 Select.Where where = select.where();
9897 for (int i = 0; i < mapper.primaryKeySize(); i++)
9998 where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
100-
99+
101100 for (Mapper.Option opt : options)
102101 opt.checkValidFor(QueryType.GET, manager);
103102 return select.toString();
104103 }
105104 case DEL: {
106105 Delete delete = table == null
107- ? delete().all().from(mapper.getKeyspace(), mapper.getTable())
108- : delete().all().from(table);
106+ ? delete().all().from(mapper.getKeyspace(), mapper.getTable())
107+ : delete().all().from(table);
109108 Delete.Where where = delete.where();
110109 for (int i = 0; i < mapper.primaryKeySize(); i++)
111110 where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
@@ -120,8 +119,8 @@
120119 case SLICE:
121120 case REVERSED_SLICE: {
122121 Select select = table == null
123- ? select().all().from(mapper.getKeyspace(), mapper.getTable())
124- : select().all().from(table);
122+ ? select().all().from(mapper.getKeyspace(), mapper.getTable())
123+ : select().all().from(table);
125124 Select.Where where = select.where();
126125 for (int i = 0; i < mapper.partitionKeys.size(); i++)
127126 where.and(eq(mapper.partitionKeys.get(i).getColumnName(), bindMarker()));
@@ -174,12 +173,12 @@
174173 if (obj == null || this.getClass() != obj.getClass())
175174 return false;
176175
177- QueryType that = (QueryType)obj;
176+ QueryType that = (QueryType) obj;
178177 return kind == that.kind
179- && startBoundSize == that.startBoundSize
180- && startInclusive == that.startInclusive
181- && endBoundSize == that.endBoundSize
182- && endInclusive == that.endInclusive;
178+ && startBoundSize == that.startBoundSize
179+ && startInclusive == that.startInclusive
180+ && endBoundSize == that.endBoundSize
181+ && endInclusive == that.endInclusive;
183182 }
184183
185184 @Override
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +3 −3
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18+import com.datastax.driver.core.ConsistencyLevel;
19+
1820 import java.beans.IntrospectionException;
1921 import java.beans.PropertyDescriptor;
2022 import java.lang.reflect.Field;
2123 import java.lang.reflect.Method;
2224 import java.util.concurrent.atomic.AtomicInteger;
2325
24-import com.datastax.driver.core.ConsistencyLevel;
25-
2626 /**
2727 * An {@link EntityMapper} implementation that use reflection to read and write fields
2828 * of an entity.
@@ -88,7 +88,7 @@
8888 return new ReflectionMapper<T>(entityClass, keyspace, table, writeConsistency, readConsistency);
8989 }
9090
91- @SuppressWarnings({ "unchecked", "rawtypes" })
91+ @SuppressWarnings({"unchecked", "rawtypes"})
9292 public <T> ColumnMapper<T> createColumnMapper(Class<T> entityClass, Field field, int position, MappingManager mappingManager, AtomicInteger columnCounter) {
9393 String fieldName = field.getName();
9494 try {
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionUtils.java +3 −3
@@ -26,8 +26,8 @@
2626 /**
2727 * Gets a type argument from a parameterized type.
2828 *
29- * @param pt the parameterized type.
30- * @param arg the index of the argument to retrieve.
29+ * @param pt the parameterized type.
30+ * @param arg the index of the argument to retrieve.
3131 * @param name the name of the element (field or method argument).
3232 * @return the type argument.
3333 */
@@ -35,6 +35,6 @@
3535 Type ft = pt.getActualTypeArguments()[arg];
3636 if (!(ft instanceof Class))
3737 throw new IllegalArgumentException(String.format("Cannot map parameter of class %s for %s", pt, name));
38- return (Class<?>)ft;
38+ return (Class<?>) ft;
3939 }
4040 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +9 −9
@@ -15,10 +15,10 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.*;
19-
2018 import com.datastax.driver.core.*;
2119
20+import java.util.*;
21+
2222 /**
2323 * A {@code ResultSet} mapped to an entity class.
2424 */
@@ -64,10 +64,10 @@
6464 private static boolean shouldSetValue(Object value) {
6565 if (value == null)
6666 return false;
67- if(value instanceof Collection)
68- return !((Collection)value).isEmpty();
69- if(value instanceof Map)
70- return !((Map)value).isEmpty();
67+ if (value instanceof Collection)
68+ return !((Collection) value).isEmpty();
69+ if (value instanceof Map)
70+ return !((Map) value).isEmpty();
7171 return true;
7272 }
7373
@@ -109,11 +109,11 @@
109109
110110 /**
111111 * An iterator over the entities of this mapped result set.
112- *
112+ * <p/>
113113 * The {@link Iterator#next} method is equivalent to calling {@link #one}.
114114 * So this iterator will consume results and after a full iteration, the
115115 * mapped result set (and underlying {@code ResultSet}) will be empty.
116- *
116+ * <p/>
117117 * The returned iterator does not support the {@link Iterator#remove} method.
118118 *
119119 * @return an iterator that will consume and return the remaining rows of
@@ -139,7 +139,7 @@
139139
140140 /**
141141 * Returns information on the execution of this query.
142- * <p>
142+ * <p/>
143143 * The returned object includes basic information such as the queried hosts,
144144 * but also the Cassandra query trace if tracing was enabled for the query.
145145 *
modified driver-mapping/src/main/java/com/datastax/driver/mapping/TypeMappings.java +8 −9
@@ -15,6 +15,9 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18+import com.datastax.driver.mapping.annotations.UDT;
19+import com.google.common.collect.Sets;
20+
1821 import java.lang.reflect.ParameterizedType;
1922 import java.lang.reflect.Type;
2023 import java.util.Collections;
@@ -22,10 +25,6 @@
2225 import java.util.Map;
2326 import java.util.Set;
2427
25-import com.google.common.collect.Sets;
26-
27-import com.datastax.driver.mapping.annotations.UDT;
28-
2928 /**
3029 * Utility methods to determine which CQL type we expect for a given Java field type.
3130 */
@@ -58,16 +57,16 @@
5857 static Set<Class<?>> findUDTs(Type type) {
5958 Set<Class<?>> udts = findUDTs(type, null);
6059 return (udts == null)
61- ? Collections.<Class<?>>emptySet()
62- : udts;
60+ ? Collections.<Class<?>>emptySet()
61+ : udts;
6362 }
6463
6564 private static Set<Class<?>> findUDTs(Type type, Set<Class<?>> udts) {
6665 if (type instanceof ParameterizedType) {
67- ParameterizedType pt = (ParameterizedType)type;
66+ ParameterizedType pt = (ParameterizedType) type;
6867 Type raw = pt.getRawType();
6968 if ((raw instanceof Class)) {
70- Class<?> klass = (Class<?>)raw;
69+ Class<?> klass = (Class<?>) raw;
7170 if (mapsToCollection(klass)) {
7271 Type[] childTypes = pt.getActualTypeArguments();
7372 udts = findUDTs(childTypes[0], udts);
@@ -77,7 +76,7 @@
7776 }
7877 }
7978 } else if (type instanceof Class) {
80- Class<?> klass = (Class<?>)type;
79+ Class<?> klass = (Class<?>) type;
8180 if (isMappedUDT(klass)) {
8281 if (udts == null)
8382 udts = Sets.newHashSet();
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Accessor.java +3 −2
@@ -23,10 +23,11 @@
2323 /**
2424 * An accessor is an interface that defines a set of method to read and write
2525 * from Cassandra.
26- * <p>
26+ * <p/>
2727 * Each method declaration of an interface with the annotation {@link Accessor} must
2828 * have a {@link Query} annotation that defines the query the method executes.
2929 */
3030 @Target(ElementType.TYPE)
3131 @Retention(RetentionPolicy.RUNTIME)
32-public @interface Accessor {}
32+public @interface Accessor {
33+}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/ClusteringColumn.java +1 −1
@@ -22,7 +22,7 @@
2222
2323 /**
2424 * Annotation for fields that map to a CQL clustering column.
25- * <p>
25+ * <p/>
2626 * If the mapped table has multiple clustering columns, it is mandatory
2727 * to specify the ordinal parameter to avoid ordering ambiguity.
2828 */
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Column.java +3 −3
@@ -15,17 +15,17 @@
1515 */
1616 package com.datastax.driver.mapping.annotations;
1717
18+import com.datastax.driver.core.TypeCodec;
19+
1820 import java.lang.annotation.ElementType;
1921 import java.lang.annotation.Retention;
2022 import java.lang.annotation.RetentionPolicy;
2123 import java.lang.annotation.Target;
2224
23-import com.datastax.driver.core.TypeCodec;
24-
2525 /**
2626 * Annotation that allows to specify the name of the CQL column to which the
2727 * field should be mapped.
28- * <p>
28+ * <p/>
2929 * Note that this annotation is generally optional in the sense that any field
3030 * of a class annotated by {@link Table} will be mapped by default to a column
3131 * having the same name than this field unless that field has the
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Computed.java +5 −4
@@ -16,8 +16,9 @@
1616 package com.datastax.driver.mapping.annotations;
1717
1818
19-import java.lang.annotation.ElementType;
2019 import com.datastax.driver.mapping.Mapper;
20+
21+import java.lang.annotation.ElementType;
2122 import java.lang.annotation.Retention;
2223 import java.lang.annotation.RetentionPolicy;
2324 import java.lang.annotation.Target;
@@ -25,10 +26,10 @@
2526 /**
2627 * Annotates a "computed" field, which gets filled from a CQL expression in the SELECT query
2728 * used to retrieve an entity.
28- * <p>
29+ * <p/>
2930 * Note that such fields are only filled by default mapper operations ({@link Mapper#get(Object...)}),
3031 * they will be ignored in accessor queries and save operations.
31- * <p>
32+ * <p/>
3233 * As opposed to other mapper annotation, this one doesn't handle case sensitivity. If your expression
3334 * contains case-sensitive names, you'll need to quote them explicitly:
3435 * <pre>
@@ -40,7 +41,7 @@
4041 public @interface Computed {
4142 /**
4243 * The formula used to compute the field.
43- * <p>
44+ * <p/>
4445 * This is a CQL expression like you would use directly in a query, for instance
4546 * "writetime(v)".
4647 *
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Field.java +3 −3
@@ -15,17 +15,17 @@
1515 */
1616 package com.datastax.driver.mapping.annotations;
1717
18+import com.datastax.driver.core.TypeCodec;
19+
1820 import java.lang.annotation.ElementType;
1921 import java.lang.annotation.Retention;
2022 import java.lang.annotation.RetentionPolicy;
2123 import java.lang.annotation.Target;
2224
23-import com.datastax.driver.core.TypeCodec;
24-
2525 /**
2626 * Annotation that allows to specify the name of the CQL UDT field to which the
2727 * Java field should be mapped.
28- * <p>
28+ * <p/>
2929 * Note that this annotation is generally optional in the sense that any field
3030 * of a class annotated by {@link UDT} will be mapped by default to a UDT field
3131 * having the same name than this Java field unless that Java field has the
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Frozen.java +5 −5
@@ -15,17 +15,17 @@
1515 */
1616 package com.datastax.driver.mapping.annotations;
1717
18+import com.datastax.driver.core.DataType;
19+
1820 import java.lang.annotation.ElementType;
1921 import java.lang.annotation.Retention;
2022 import java.lang.annotation.RetentionPolicy;
2123 import java.lang.annotation.Target;
2224
23-import com.datastax.driver.core.DataType;
24-
2525 /**
2626 * Specifies that the field decorated with this annotation maps to a CQL type that is {@link DataType#isFrozen() frozen},
2727 * or contains frozen subtypes.
28- * <p>
28+ * <p/>
2929 * This annotation is purely informational at this stage, the validity of the declaration is not checked.
3030 * But will become useful when a schema generation feature is added to the mapper. Therefore it is a good idea to keep
3131 * frozen declarations up-to-date.
@@ -42,7 +42,7 @@
4242 /**
4343 * Contains the full CQL type of the target column. As a convenience, this can be left out when only the top-level
4444 * type is frozen.
45- * <p>
45+ * <p/>
4646 * Examples:
4747 * <pre>
4848 * // Will map to frozen&lt;user&gt;
@@ -52,7 +52,7 @@
5252 * &#64;Frozen("map&lt;text, map&lt;text, frozen&lt;user&gt;&gt;&gt;")
5353 * private Map&lt;String, Map&lt;String, User&gt;&gt; m;
5454 * </pre>
55- * <p>
55+ * <p/>
5656 * Also consider the {@link FrozenKey @FrozenKey} and {@link FrozenValue @FrozenValue} shortcuts for simple collections.
5757 *
5858 * @return the full CQL type of the target column.
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/FrozenKey.java +5 −2
@@ -15,11 +15,14 @@
1515 */
1616 package com.datastax.driver.mapping.annotations;
1717
18-import java.lang.annotation.*;
18+import java.lang.annotation.ElementType;
19+import java.lang.annotation.Retention;
20+import java.lang.annotation.RetentionPolicy;
21+import java.lang.annotation.Target;
1922
2023 /**
2124 * Shorthand to specify that the key type of a MAP field is frozen.
22- * <p>
25+ * <p/>
2326 * This is equivalent to {@code @Frozen("map<frozen<foo>, bar>")}.
2427 *
2528 * @see Frozen
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/FrozenValue.java +5 −2
@@ -15,11 +15,14 @@
1515 */
1616 package com.datastax.driver.mapping.annotations;
1717
18-import java.lang.annotation.*;
18+import java.lang.annotation.ElementType;
19+import java.lang.annotation.Retention;
20+import java.lang.annotation.RetentionPolicy;
21+import java.lang.annotation.Target;
1922
2023 /**
2124 * Shorthand to specify that the value type of a collection field is frozen.
22- * <p>
25+ * <p/>
2326 * This is equivalent to any of the following:
2427 * <ul>
2528 * <li>{@code @Frozen("list<frozen<foo>>")}</li>
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Param.java +2 −2
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.mapping.annotations;
1717
18+import com.datastax.driver.core.TypeCodec;
19+
1820 import java.lang.annotation.ElementType;
1921 import java.lang.annotation.Retention;
2022 import java.lang.annotation.RetentionPolicy;
2123 import java.lang.annotation.Target;
2224
23-import com.datastax.driver.core.TypeCodec;
24-
2525 /**
2626 * Provides a name for a parameter of a method in an {@link Accessor} interface that
2727 * can be used to reference to that parameter in method {@link Query}.
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/PartitionKey.java +1 −1
@@ -23,7 +23,7 @@
2323 /**
2424 * Annotation for fields that map to a CQL partition key (or one of it's
2525 * component if the partition key is composite).
26- * <p>
26+ * <p/>
2727 * If the partition key of the mapped table is composite, it is mandatory
2828 * to specify the ordinal parameter to avoid ordering ambiguity.
2929 */
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Query.java +1 −1
@@ -28,7 +28,7 @@
2828 public @interface Query {
2929 /**
3030 * The CQL query to use.
31- * <p>
31+ * <p/>
3232 * In that query string, the parameter of the annotated method can be referenced using
3333 * name bind markers. For instance, the first parameter can be refered by {@code :arg0},
3434 * the second one by {@code :arg1}, ... Alternatively, if a parameter of the annonated
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/QueryParameters.java +3 −3
@@ -15,17 +15,17 @@
1515 */
1616 package com.datastax.driver.mapping.annotations;
1717
18+import com.datastax.driver.core.Configuration;
19+
1820 import java.lang.annotation.ElementType;
1921 import java.lang.annotation.Retention;
2022 import java.lang.annotation.RetentionPolicy;
2123 import java.lang.annotation.Target;
2224
23-import com.datastax.driver.core.Configuration;
24-
2525 /**
2626 * Query parameters to use in the (generated) implementation of a method of an {@link Accessor}
2727 * interface.
28- * <p>
28+ * <p/>
2929 * All the parameters of this annotation are optional, and when not provided default to whatever
3030 * default the {@code Cluster} instance used underneath are (those set in
3131 * {@link Configuration#getQueryOptions}).
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Table.java +4 −2
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.mapping.annotations;
1717
18+import com.datastax.driver.mapping.Mapper;
19+
1820 import java.lang.annotation.ElementType;
1921 import java.lang.annotation.Retention;
2022 import java.lang.annotation.RetentionPolicy;
2123 import java.lang.annotation.Target;
2224
23-import com.datastax.driver.mapping.Mapper;
24-
2525 /**
2626 * Defines to which table a class must be mapped to.
2727 */
@@ -34,6 +34,7 @@
3434 * @return the name of the keyspace.
3535 */
3636 String keyspace() default "";
37+
3738 /**
3839 * The name of the table.
3940 *
@@ -47,6 +48,7 @@
4748 * @return whether the keyspace name is a case sensitive one.
4849 */
4950 boolean caseSensitiveKeyspace() default false;
51+
5052 /**
5153 * Whether the table name is a case sensitive one.
5254 *
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Transient.java +1 −1
@@ -23,7 +23,7 @@
2323 /**
2424 * Whenever this annotation is added on a field, the field will not be mapped
2525 * to any column (neither during reads nor writes).
26- * <p>
26+ * <p/>
2727 * Please note that it is thus illegal to have a field that has both the
2828 * {@code Transcient} annotation and one of the {@link Column}, {@link PartitionKey}
2929 * or {@link ClusteringColumn} annotation.
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/UDT.java +2 −0
@@ -32,6 +32,7 @@
3232 * @return the name of the keyspace.
3333 */
3434 String keyspace() default "";
35+
3536 /**
3637 * The name of the type.
3738 *
@@ -45,6 +46,7 @@
4546 * @return whether the keyspace name is a case sensitive one.
4647 */
4748 boolean caseSensitiveKeyspace() default false;
49+
4850 /**
4951 * Whether the type name is a case sensitive one.
5052 *
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +31 −20
@@ -15,26 +15,25 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.Collection;
19-
20-import com.google.common.collect.Lists;
21-import org.testng.annotations.Test;
22-
23-import static org.assertj.core.api.Assertions.assertThat;
24-
2518 import com.datastax.driver.core.CCMBridge;
2619 import com.datastax.driver.core.Row;
2720 import com.datastax.driver.core.utils.CassandraVersion;
2821 import com.datastax.driver.mapping.annotations.*;
22+import com.google.common.collect.Lists;
23+import org.testng.annotations.Test;
24+
25+import java.util.Collection;
26+
27+import static org.assertj.core.api.Assertions.assertThat;
2928
3029 public class MapperAccessorParamsTest extends CCMBridge.PerClassSingleNodeCluster {
3130 @Override
3231 protected Collection<String> getTableDefinitions() {
3332 return Lists.newArrayList(
34- "CREATE TABLE user ( key int primary key, gender int, home_phone text, work_phone text)",
35- "CREATE INDEX on user(gender)",
36- "CREATE TABLE user_str ( key int primary key, gender text)",
37- "CREATE INDEX on user_str(gender)"
33+ "CREATE TABLE user ( key int primary key, gender int, home_phone text, work_phone text)",
34+ "CREATE INDEX on user(gender)",
35+ "CREATE TABLE user_str ( key int primary key, gender text)",
36+ "CREATE INDEX on user_str(gender)"
3837 );
3938 }
4039
@@ -42,7 +41,7 @@
4241 @CassandraVersion(major = 2.0, description = "Uses named parameters")
4342 public void should_allow_less_parameters_than_bind_markers_if_there_are_repeated_names() {
4443 UserPhoneAccessor accessor = new MappingManager(session)
45- .createAccessor(UserPhoneAccessor.class);
44+ .createAccessor(UserPhoneAccessor.class);
4645
4746 session.execute("delete from user where key = 0");
4847 accessor.updatePhones_positional("1111", "2222", 0);
@@ -68,13 +67,13 @@
6867 @Test(groups = "short", expectedExceptions = RuntimeException.class)
6968 public void should_fail_if_not_enough_parameters() {
7069 new MappingManager(session)
71- .createAccessor(UserPhoneAccessor_NotEnoughParams.class);
70+ .createAccessor(UserPhoneAccessor_NotEnoughParams.class);
7271 }
7372
7473 @Test(groups = "short", expectedExceptions = RuntimeException.class)
7574 public void should_fail_if_too_many_parameters() {
7675 new MappingManager(session)
77- .createAccessor(UserPhoneAccessor_TooManyParams.class);
76+ .createAccessor(UserPhoneAccessor_TooManyParams.class);
7877 }
7978
8079 private void assertPhonesEqual(int key, String home, String work) {
@@ -87,26 +86,38 @@
8786 MALE, FEMALE
8887 }
8988
90- /** Tests various ways to match method parameters to query bind markers. */
89+ /**
90+ * Tests various ways to match method parameters to query bind markers.
91+ */
9192 @Accessor
9293 public interface UserPhoneAccessor {
93- /** Standard positional markers */
94+ /**
95+ * Standard positional markers
96+ */
9497 @Query("update user set home_phone = ?, work_phone = ? where key = ?")
9598 void updatePhones_positional(String homePhone, String workPhone, int key);
9699
97- /** Standard named markers */
100+ /**
101+ * Standard named markers
102+ */
98103 @Query("update user set home_phone = :home, work_phone = :work where key = :key")
99104 void updatePhones_named(@Param("key") int key, @Param("home") String homePhone, @Param("work") String workPhone);
100105
101- /** Named markers with no @Param. Should fallback to positional matching */
106+ /**
107+ * Named markers with no @Param. Should fallback to positional matching
108+ */
102109 @Query("update user set home_phone = :home, work_phone = :work where key = :key")
103110 void updatePhones_fallback(String homePhone, String workPhone, int key);
104111
105- /** Named markers with repeated names */
112+ /**
113+ * Named markers with repeated names
114+ */
106115 @Query("update user set home_phone = :phone, work_phone = :phone where key = :key")
107116 void updateBothPhones(@Param("key") int key, @Param("phone") String uniquePhone);
108117
109- /** Named markers with repeated names, but no @Param. Should fallback to positional matching */
118+ /**
119+ * Named markers with repeated names, but no @Param. Should fallback to positional matching
120+ */
110121 @Query("update user set home_phone = :phone, work_phone = :phone where key = :key")
111122 void updatePhones_fallback2(String homePhone, String workPhone, int key);
112123 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorTest.java +12 −13
@@ -15,13 +15,6 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.Collection;
19-
20-import com.google.common.collect.Lists;
21-import org.testng.annotations.Test;
22-
23-import static org.assertj.core.api.Assertions.assertThat;
24-
2518 import com.datastax.driver.core.CCMBridge;
2619 import com.datastax.driver.core.ResultSet;
2720 import com.datastax.driver.core.Row;
@@ -29,6 +22,12 @@
2922 import com.datastax.driver.mapping.annotations.Accessor;
3023 import com.datastax.driver.mapping.annotations.Param;
3124 import com.datastax.driver.mapping.annotations.Query;
25+import com.google.common.collect.Lists;
26+import org.testng.annotations.Test;
27+
28+import java.util.Collection;
29+
30+import static org.assertj.core.api.Assertions.assertThat;
3231
3332 public class MapperAccessorTest extends CCMBridge.PerClassSingleNodeCluster {
3433
@@ -40,26 +39,26 @@
4039 @Test(groups = "short")
4140 public void should_implement_toString() {
4241 SystemAccessor accessor = new MappingManager(session)
43- .createAccessor(SystemAccessor.class);
42+ .createAccessor(SystemAccessor.class);
4443
4544 assertThat(accessor.toString())
46- .isEqualTo("SystemAccessor implementation generated by the Cassandra driver mapper");
45+ .isEqualTo("SystemAccessor implementation generated by the Cassandra driver mapper");
4746 }
4847
4948 @Test(groups = "short")
5049 public void should_implement_equals_and_hashCode() {
5150 SystemAccessor accessor = new MappingManager(session)
52- .createAccessor(SystemAccessor.class);
51+ .createAccessor(SystemAccessor.class);
5352
5453 assertThat(accessor).isNotEqualTo(new Object());
5554 assertThat(accessor.hashCode()).isEqualTo(System.identityHashCode(accessor));
5655 }
5756
5857 @Test(groups = "short")
59- @CassandraVersion(major=2.0)
58+ @CassandraVersion(major = 2.0)
6059 public void should_allow_null_argument_in_accessor_when_set_by_name() {
6160 FooAccessor accessor = new MappingManager(session)
62- .createAccessor(FooAccessor.class);
61+ .createAccessor(FooAccessor.class);
6362
6463 accessor.insert(1, null);
6564 Row row = session.execute("select * from foo where k = 1").one();
@@ -70,7 +69,7 @@
7069 @Test(groups = "short")
7170 public void should_allow_null_argument_in_accessor_when_set_by_index() {
7271 FooBindMarkerAccessor accessor = new MappingManager(session)
73- .createAccessor(FooBindMarkerAccessor.class);
72+ .createAccessor(FooBindMarkerAccessor.class);
7473
7574 accessor.insert(1, null);
7675
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCompositeKeyTest.java +6 −5
@@ -15,13 +15,14 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.Arrays;
19-import java.util.Collection;
20-
21-import com.datastax.driver.mapping.annotations.*;
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.mapping.annotations.ClusteringColumn;
20+import com.datastax.driver.mapping.annotations.PartitionKey;
21+import com.datastax.driver.mapping.annotations.Table;
2222 import org.testng.annotations.Test;
2323
24-import com.datastax.driver.core.CCMBridge;
24+import java.util.Arrays;
25+import java.util.Collection;
2526
2627 /**
2728 * Tests for the mapper with composite partition keys and multiple clustering columns.
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +13 −15
@@ -15,23 +15,21 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.Collection;
19-
20-import com.google.common.collect.Lists;
21-import org.testng.SkipException;
22-import org.testng.annotations.BeforeMethod;
23-import org.testng.annotations.Test;
24-
25-import static com.datastax.driver.core.ProtocolVersion.V1;
26-import static org.assertj.core.api.Assertions.fail;
27-
2818 import com.datastax.driver.core.*;
2919 import com.datastax.driver.core.exceptions.CodecNotFoundException;
3020 import com.datastax.driver.core.exceptions.InvalidQueryException;
3121 import com.datastax.driver.core.utils.CassandraVersion;
3222 import com.datastax.driver.mapping.annotations.*;
23+import com.google.common.collect.Lists;
24+import org.testng.SkipException;
25+import org.testng.annotations.BeforeMethod;
26+import org.testng.annotations.Test;
27+
28+import java.util.Collection;
3329
3430 import static com.datastax.driver.core.Assertions.assertThat;
31+import static com.datastax.driver.core.ProtocolVersion.V1;
32+import static org.assertj.core.api.Assertions.fail;
3533
3634 /**
3735 * Tests to ensure validity of {@link com.datastax.driver.mapping.annotations.Computed}
@@ -43,8 +41,8 @@
4341 @Override
4442 protected Collection<String> getTableDefinitions() {
4543 return Lists.newArrayList(
46- "CREATE TABLE user (login text primary key, name text)",
47- "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')");
44+ "CREATE TABLE user (login text primary key, name text)",
45+ "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')");
4846 }
4947
5048 ProtocolVersion protocolVersion;
@@ -59,7 +57,7 @@
5957 userMapper = mappingManager.mapper(User.class);
6058 }
6159
62- @Test(groups = "short", expectedExceptions = { UnsupportedOperationException.class })
60+ @Test(groups = "short", expectedExceptions = {UnsupportedOperationException.class})
6361 void should_get_unsupported_operation_exception_on_v1() {
6462 if (protocolVersion.compareTo(V1) > 0)
6563 throw new SkipException("Skipped when protocol version > V1");
@@ -96,9 +94,9 @@
9694 @Test(groups = "short")
9795 @CassandraVersion(major = 2.0)
9896 void should_add_aliases_for_fields_in_select_queries() {
99- BoundStatement bs = (BoundStatement)userMapper.getQuery("test");
97+ BoundStatement bs = (BoundStatement) userMapper.getQuery("test");
10098 assertThat(bs.preparedStatement().getQueryString())
101- .contains("SELECT", "\"login\" AS col1", "\"name\" AS col2", "writetime(\"name\") AS col3");
99+ .contains("SELECT", "\"login\" AS col1", "\"name\" AS col2", "writetime(\"name\") AS col3");
102100 }
103101
104102 @Test(groups = "short")
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCustomCodecTest.java +36 −35
@@ -15,10 +15,10 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Collection;
20-import java.util.Map;
21-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.InvalidTypeException;
20+import com.datastax.driver.core.utils.CassandraVersion;
21+import com.datastax.driver.mapping.annotations.*;
2222 import com.google.common.base.Optional;
2323 import com.google.common.base.Predicate;
2424 import com.google.common.collect.ImmutableMap;
@@ -27,40 +27,39 @@
2727 import com.google.common.reflect.TypeToken;
2828 import org.testng.annotations.Test;
2929
30+import java.nio.ByteBuffer;
31+import java.util.Collection;
32+import java.util.Map;
33+
3034 import static org.assertj.core.api.Assertions.assertThat;
3135 import static org.assertj.core.api.Assertions.fail;
3236
33-import com.datastax.driver.core.*;
34-import com.datastax.driver.core.exceptions.InvalidTypeException;
35-import com.datastax.driver.core.utils.CassandraVersion;
36-import com.datastax.driver.mapping.annotations.*;
37-
38-@CassandraVersion(major=2.1)
37+@CassandraVersion(major = 2.1)
3938 public class MapperCustomCodecTest extends CCMBridge.PerClassSingleNodeCluster {
4039
4140 @Override
4241 protected Collection<String> getTableDefinitions() {
4342 return Lists.newArrayList(
44- // Columns mapped to custom types
45- "CREATE TABLE data1 (i int PRIMARY KEY, l bigint)",
46- "INSERT INTO data1 (i, l) VALUES (1, 11)",
47-
48- // UDT fields mapped to custom types
49- "CREATE TYPE holder(i int, l bigint)",
50- "CREATE TABLE data2(i int primary key, data frozen<holder>)",
51- "INSERT INTO data2 (i, data) values (1, {i: 1, l: 11})",
52-
53- // nested UDT
54- // both UDT fields and non-UDT elements in the collection are mapped to custom types
55- "CREATE TABLE data3(i int primary key, data map<int, frozen<holder>>)",
56- "INSERT INTO data3 (i, data) values (1, {1: {i: 1, l: 11}})"
43+ // Columns mapped to custom types
44+ "CREATE TABLE data1 (i int PRIMARY KEY, l bigint)",
45+ "INSERT INTO data1 (i, l) VALUES (1, 11)",
46+
47+ // UDT fields mapped to custom types
48+ "CREATE TYPE holder(i int, l bigint)",
49+ "CREATE TABLE data2(i int primary key, data frozen<holder>)",
50+ "INSERT INTO data2 (i, data) values (1, {i: 1, l: 11})",
51+
52+ // nested UDT
53+ // both UDT fields and non-UDT elements in the collection are mapped to custom types
54+ "CREATE TABLE data3(i int primary key, data map<int, frozen<holder>>)",
55+ "INSERT INTO data3 (i, data) values (1, {1: {i: 1, l: 11}})"
5756 );
5857 }
5958
6059 @Override
6160 protected Cluster.Builder configure(Cluster.Builder builder) {
6261 return builder.withCodecRegistry(new CodecRegistry()
63- .register(new CustomInt.Codec()));
62+ .register(new CustomInt.Codec()));
6463 }
6564
6665 @Test(groups = "short")
@@ -150,12 +149,12 @@
150149 mapper.delete(2);
151150 }
152151
153- @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
152+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
154153 public void should_fail_when_invalid_codec_with_no_default_ctor_provided() {
155154 new MappingManager(session).mapper(Data1InvalidCodecNoDefaultConstructor.class);
156155 }
157156
158- @Test(groups="short", expectedExceptions = InvalidTypeException.class)
157+ @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
159158 public void should_fail_when_invalid_codec_type_mapping() {
160159 Mapper<Data1InvalidCodecTypeMapping> mapper = new MappingManager(session).mapper(Data1InvalidCodecTypeMapping.class);
161160
@@ -174,12 +173,12 @@
174173 mapper.save(data12);
175174 }
176175
177- @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
176+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
178177 public void should_fail_when_invalid_codec_with_no_default_ctor_provided_in_accessor() {
179178 new MappingManager(session).createAccessor(Data1AccessorNoDefaultConstructor.class);
180179 }
181180
182- @Test(groups="short", expectedExceptions = InvalidTypeException.class)
181+ @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
183182 public void should_fail_when_invalid_codec_type_mapping_in_accessor() {
184183 Data1AccessorInvalidCodecTypeMapping accessor = new MappingManager(session).createAccessor(Data1AccessorInvalidCodecTypeMapping.class);
185184
@@ -194,7 +193,7 @@
194193 accessor.setL(1, Optional.of(2L));
195194 }
196195
197- @Test(groups="short")
196+ @Test(groups = "short")
198197 public void should_be_able_to_use_parameterized_type() {
199198 Mapper<Data1ParameterizedType> mapper = new MappingManager(session).mapper(Data1ParameterizedType.class);
200199
@@ -454,7 +453,7 @@
454453 @Override
455454 public boolean equals(Object other) {
456455 if (other instanceof CustomInt) {
457- CustomInt that = (CustomInt)other;
456+ CustomInt that = (CustomInt) other;
458457 return this.value == that.value;
459458 }
460459 return false;
@@ -503,7 +502,7 @@
503502 @Override
504503 public boolean equals(Object other) {
505504 if (other instanceof CustomLong) {
506- CustomLong that = (CustomLong)other;
505+ CustomLong that = (CustomLong) other;
507506 return this.value == that.value;
508507 }
509508 return false;
@@ -511,7 +510,7 @@
511510
512511 @Override
513512 public int hashCode() {
514- return (int)(value ^ (value >>> 32));
513+ return (int) (value ^ (value >>> 32));
515514 }
516515
517516 public static class Codec extends TypeCodec<CustomLong> {
@@ -568,13 +567,15 @@
568567 private final Predicate<T> isAbsent;
569568
570569 public OptionalCodec(TypeCodec<T> codec) {
571- super(codec, new TypeToken<Optional<T>>(){}.where(new TypeParameter<T>(){}, codec.getJavaType()));
570+ super(codec, new TypeToken<Optional<T>>() {
571+ }.where(new TypeParameter<T>() {
572+ }, codec.getJavaType()));
572573 this.isAbsent = new Predicate<T>() {
573574 @Override
574575 public boolean apply(T input) {
575576 return input == null
576- || input instanceof Collection && ((Collection)input).isEmpty()
577- || input instanceof Map && ((Map)input).isEmpty();
577+ || input instanceof Collection && ((Collection) input).isEmpty()
578+ || input instanceof Map && ((Map) input).isEmpty();
578579 }
579580 };
580581 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java +25 −24
@@ -15,36 +15,35 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.Session;
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 org.testng.annotations.Test;
25+
1826 import java.util.Arrays;
1927 import java.util.Collection;
2028 import java.util.UUID;
2129
22-import com.google.common.base.Objects;
23-import org.testng.annotations.Test;
24-
2530 import static org.testng.Assert.assertEquals;
2631 import static org.testng.Assert.assertNull;
2732
28-import com.datastax.driver.core.CCMBridge;
29-import com.datastax.driver.core.Session;
30-import com.datastax.driver.core.utils.CassandraVersion;
31-import com.datastax.driver.core.utils.UUIDs;
32-import com.datastax.driver.mapping.annotations.*;
33-
3433 /**
3534 * Tests usage of mapping annotations without specifying a keyspace.
3635 */
37-@CassandraVersion(major=2.1)
36+@CassandraVersion(major = 2.1)
3837 public class MapperDefaultKeyspaceTest extends CCMBridge.PerClassSingleNodeCluster {
3938
4039 private static final String KEYSPACE = "mapper_default_keyspace_test_ks";
4140
4241 protected Collection<String> getTableDefinitions() {
4342 return Arrays.asList(
44- String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }", KEYSPACE),
45- String.format("CREATE TYPE IF NOT EXISTS %s.group_name (name text)", KEYSPACE),
46- String.format("CREATE TABLE IF NOT EXISTS %s.groups (group_id uuid PRIMARY KEY, name text)", KEYSPACE),
47- String.format("CREATE TABLE IF NOT EXISTS %s.groups2 (group_id uuid PRIMARY KEY, name frozen<group_name>)", KEYSPACE));
43+ String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }", KEYSPACE),
44+ String.format("CREATE TYPE IF NOT EXISTS %s.group_name (name text)", KEYSPACE),
45+ String.format("CREATE TABLE IF NOT EXISTS %s.groups (group_id uuid PRIMARY KEY, name text)", KEYSPACE),
46+ String.format("CREATE TABLE IF NOT EXISTS %s.groups2 (group_id uuid PRIMARY KEY, name frozen<group_name>)", KEYSPACE));
4847 }
4948
5049 @Test(groups = "short")
@@ -92,8 +91,8 @@
9291 }
9392
9493 @Test(groups = "short",
95- expectedExceptions = IllegalArgumentException.class,
96- expectedExceptionsMessageRegExp = "Error creating mapper for class Group, the @Table annotation declares no default keyspace, and the session is not currently logged to any keyspace")
94+ expectedExceptions = IllegalArgumentException.class,
95+ expectedExceptionsMessageRegExp = "Error creating mapper for class Group, the @Table annotation declares no default keyspace, and the session is not currently logged to any keyspace")
9796 public void should_throw_a_meaningful_error_message_when_no_default_table_keyspace_and_session_not_logged() {
9897 Session session2 = cluster.connect();
9998 MappingManager manager = new MappingManager(session2);
@@ -101,8 +100,8 @@
101100 }
102101
103102 @Test(groups = "short",
104- expectedExceptions = IllegalArgumentException.class,
105- expectedExceptionsMessageRegExp = "Error creating UDT codec for class GroupName, the @UDT annotation declares no default keyspace, and the session is not currently logged to any keyspace")
103+ expectedExceptions = IllegalArgumentException.class,
104+ expectedExceptionsMessageRegExp = "Error creating UDT codec for class GroupName, the @UDT annotation declares no default keyspace, and the session is not currently logged to any keyspace")
106105 public void should_throw_a_meaningful_error_message_when_no_default_udt_keyspace_and_session_not_logged() {
107106 Session session2 = cluster.connect();
108107 MappingManager manager = new MappingManager(session2);
@@ -123,7 +122,8 @@
123122
124123 private String name;
125124
126- public Group() {}
125+ public Group() {
126+ }
127127
128128 public Group(String name) {
129129 this.name = name;
@@ -151,9 +151,9 @@
151151 if (other == null || other.getClass() != this.getClass())
152152 return false;
153153
154- Group that = (Group)other;
154+ Group that = (Group) other;
155155 return Objects.equal(groupId, that.groupId)
156- && Objects.equal(name, that.name);
156+ && Objects.equal(name, that.name);
157157 }
158158
159159 @Override
@@ -172,7 +172,8 @@
172172 @Frozen
173173 private GroupName name;
174174
175- public Group2() {}
175+ public Group2() {
176+ }
176177
177178 public Group2(GroupName name) {
178179 this.name = name;
@@ -200,9 +201,9 @@
200201 if (other == null || other.getClass() != this.getClass())
201202 return false;
202203
203- Group that = (Group)other;
204+ Group that = (Group) other;
204205 return Objects.equal(groupId, that.groupId)
205- && Objects.equal(name, that.name);
206+ && Objects.equal(name, that.name);
206207 }
207208
208209 @Override
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperMaterializedViewTest.java +63 −63
@@ -15,68 +15,67 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.Collection;
19-import java.util.Iterator;
20-
21-import org.testng.annotations.BeforeMethod;
22-import org.testng.annotations.Test;
23-
24-import static com.google.common.collect.Lists.newArrayList;
25-import static org.assertj.core.api.Assertions.assertThat;
26-
2718 import com.datastax.driver.core.CCMBridge;
2819 import com.datastax.driver.core.utils.CassandraVersion;
2920 import com.datastax.driver.mapping.annotations.Accessor;
3021 import com.datastax.driver.mapping.annotations.Param;
3122 import com.datastax.driver.mapping.annotations.Query;
3223 import com.datastax.driver.mapping.annotations.Table;
24+import org.testng.annotations.BeforeMethod;
25+import org.testng.annotations.Test;
26+
27+import java.util.Collection;
28+import java.util.Iterator;
29+
30+import static com.google.common.collect.Lists.newArrayList;
31+import static org.assertj.core.api.Assertions.assertThat;
3332
34-@CassandraVersion(major=3.0)
35-public class MapperMaterializedViewTest extends CCMBridge.PerClassSingleNodeCluster{
33+@CassandraVersion(major = 3.0)
34+public class MapperMaterializedViewTest extends CCMBridge.PerClassSingleNodeCluster {
3635
3736 @Override
3837 protected Collection<String> getTableDefinitions() {
3938 // Example schema taken from: http://www.datastax.com/dev/blog/new-in-cassandra-3-0-materialized-views
4039 return newArrayList(
41- "CREATE TABLE scores (user TEXT, game TEXT, year INT, month INT, day INT, score INT, PRIMARY KEY(user, game, year, month, day))",
42- "CREATE MATERIALIZED VIEW alltimehigh AS\n"
43- + " SELECT * FROM scores\n"
44- + " WHERE game IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL\n"
45- + " PRIMARY KEY (game, score, user, year, month, day)\n"
46- + " WITH CLUSTERING ORDER BY (score desc)",
47- "CREATE MATERIALIZED VIEW dailyhigh AS\n"
48- + " SELECT * FROM scores\n"
49- + " WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL\n"
50- + " PRIMARY KEY ((game, year, month, day), score, user)\n"
51- + " WITH CLUSTERING ORDER BY (score DESC)",
52- "CREATE MATERIALIZED VIEW monthlyhigh AS\n"
53- + " SELECT * FROM scores\n"
54- + " WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL\n"
55- + " PRIMARY KEY ((game, year, month), score, user, day)\n"
56- + " WITH CLUSTERING ORDER BY (score DESC)",
57- "CREATE MATERIALIZED VIEW filtereduserhigh AS\n"
58- + " SELECT * FROM scores\n"
59- + " WHERE user in ('jbellis', 'pcmanus') AND game IS NOT NULL AND score IS NOT NULL AND year is NOT NULL AND day is not NULL and month IS NOT NULL\n"
60- + " PRIMARY KEY (game, score, user, year, month, day)\n"
61- + " WITH CLUSTERING ORDER BY (score DESC)",
62- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('pcmanus', 'Coup', 2015, 5, 1, 4000)",
63- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Coup', 2015, 5, 3, 1750)",
64- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('yukim', 'Coup', 2015, 5, 3, 2250)",
65- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('tjake', 'Coup', 2015, 5, 3, 500)",
66- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('iamaleksey', 'Coup', 2015, 6, 1, 2500)",
67- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('tjake', 'Coup', 2015, 6, 2, 1000)",
68- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('pcmanus', 'Coup', 2015, 6, 2, 2000)",
69- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jmckenzie', 'Coup', 2015, 6, 9, 2700)",
70- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Coup', 2015, 6, 20, 3500)",
71- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Checkers', 2015, 6, 20, 1200)",
72- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Chess', 2015, 6, 21, 3500)",
73- "INSERT INTO scores (user, game, year, month, day, score) VALUES ('pcmanus', 'Chess', 2015, 1, 25, 3200)"
40+ "CREATE TABLE scores (user TEXT, game TEXT, year INT, month INT, day INT, score INT, PRIMARY KEY(user, game, year, month, day))",
41+ "CREATE MATERIALIZED VIEW alltimehigh AS\n"
42+ + " SELECT * FROM scores\n"
43+ + " WHERE game IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL\n"
44+ + " PRIMARY KEY (game, score, user, year, month, day)\n"
45+ + " WITH CLUSTERING ORDER BY (score desc)",
46+ "CREATE MATERIALIZED VIEW dailyhigh AS\n"
47+ + " SELECT * FROM scores\n"
48+ + " WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL\n"
49+ + " PRIMARY KEY ((game, year, month, day), score, user)\n"
50+ + " WITH CLUSTERING ORDER BY (score DESC)",
51+ "CREATE MATERIALIZED VIEW monthlyhigh AS\n"
52+ + " SELECT * FROM scores\n"
53+ + " WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL\n"
54+ + " PRIMARY KEY ((game, year, month), score, user, day)\n"
55+ + " WITH CLUSTERING ORDER BY (score DESC)",
56+ "CREATE MATERIALIZED VIEW filtereduserhigh AS\n"
57+ + " SELECT * FROM scores\n"
58+ + " WHERE user in ('jbellis', 'pcmanus') AND game IS NOT NULL AND score IS NOT NULL AND year is NOT NULL AND day is not NULL and month IS NOT NULL\n"
59+ + " PRIMARY KEY (game, score, user, year, month, day)\n"
60+ + " WITH CLUSTERING ORDER BY (score DESC)",
61+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('pcmanus', 'Coup', 2015, 5, 1, 4000)",
62+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Coup', 2015, 5, 3, 1750)",
63+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('yukim', 'Coup', 2015, 5, 3, 2250)",
64+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('tjake', 'Coup', 2015, 5, 3, 500)",
65+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('iamaleksey', 'Coup', 2015, 6, 1, 2500)",
66+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('tjake', 'Coup', 2015, 6, 2, 1000)",
67+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('pcmanus', 'Coup', 2015, 6, 2, 2000)",
68+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jmckenzie', 'Coup', 2015, 6, 9, 2700)",
69+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Coup', 2015, 6, 20, 3500)",
70+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Checkers', 2015, 6, 20, 1200)",
71+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Chess', 2015, 6, 21, 3500)",
72+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('pcmanus', 'Chess', 2015, 1, 25, 3200)"
7473 );
7574 }
7675
7776 private ScoreAccessor accessor;
7877
79- @BeforeMethod(groups="short")
78+ @BeforeMethod(groups = "short")
8079 public void setUp() {
8180 accessor = new MappingManager(session).createAccessor(ScoreAccessor.class);
8281 }
@@ -85,9 +84,9 @@
8584 * Validates that an accessor properly maps a single entity over a result from a materialized
8685 * view.
8786 *
88- * @test_category materialized_view,mapper
87+ * @test_category materialized_view, mapper
8988 */
90- @Test(groups="short")
89+ @Test(groups = "short")
9190 public void should_access_single_entity() {
9291 Score score = accessor.allTimeHigh("Coup");
9392
@@ -98,9 +97,9 @@
9897 * Validates that an accessor properly maps to a Result from a materialized
9998 * view.
10099 *
101- * @test_category materialized_view,mapper
100+ * @test_category materialized_view, mapper
102101 */
103- @Test(groups="short")
102+ @Test(groups = "short")
104103 public void should_access_mapped_result() {
105104 Result<Score> scores = accessor.dailyHigh("Coup", 2015, 6, 2);
106105
@@ -114,9 +113,9 @@
114113 * Validates that an accessor properly maps to a Result from a materialized
115114 * view given a range criteria query.
116115 *
117- * @test_category materialized_view,mapper
116+ * @test_category materialized_view, mapper
118117 */
119- @Test(groups="short")
118+ @Test(groups = "short")
120119 public void should_access_mapped_result_range() {
121120 Result<Score> scores = accessor.monthlyHighRange("Coup", 2015, 6, 2500, 3500);
122121
@@ -131,9 +130,9 @@
131130 * Validates that an accessor properly maps to a Result from a materialized
132131 * view that is filtered on a primary key.
133132 *
134- * @test_category materialized_view,mapper
133+ * @test_category materialized_view, mapper
135134 */
136- @Test(groups="short")
135+ @Test(groups = "short")
137136 public void should_access_filtered_user_high() {
138137 Result<Score> scores = accessor.filteredUserHigh("Chess");
139138
@@ -158,7 +157,7 @@
158157 Result<Score> filteredUserHigh(String game);
159158 }
160159
161- @Table(name="scores")
160+ @Table(name = "scores")
162161 public static class Score {
163162 String user;
164163
@@ -172,7 +171,8 @@
172171
173172 int score;
174173
175- public Score() {}
174+ public Score() {
175+ }
176176
177177 public Score(String user, String game, int year, int month, int day, int score) {
178178 this.user = user;
@@ -234,13 +234,13 @@
234234 @Override
235235 public String toString() {
236236 return "Score{" +
237- "user='" + user + '\'' +
238- ", game='" + game + '\'' +
239- ", year=" + year +
240- ", month=" + month +
241- ", day=" + day +
242- ", score=" + score +
243- '}';
237+ "user='" + user + '\'' +
238+ ", game='" + game + '\'' +
239+ ", year=" + year +
240+ ", month=" + month +
241+ ", day=" + day +
242+ ", score=" + score +
243+ '}';
244244 }
245245
246246 @Override
@@ -250,7 +250,7 @@
250250 if (!(o instanceof Score))
251251 return false;
252252
253- Score score1 = (Score)o;
253+ Score score1 = (Score) o;
254254
255255 if (year != score1.year)
256256 return false;
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperNestedCollectionsTest.java +13 −14
@@ -15,30 +15,29 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.ResultSet;
20+import com.datastax.driver.core.utils.CassandraVersion;
21+import com.datastax.driver.mapping.annotations.*;
2022 import com.google.common.collect.ImmutableMap;
2123 import com.google.common.collect.Lists;
2224 import com.google.common.collect.Sets;
2325 import org.testng.annotations.Test;
2426
25-import com.datastax.driver.core.CCMBridge;
26-import com.datastax.driver.core.ResultSet;
27-import com.datastax.driver.core.utils.CassandraVersion;
28-import com.datastax.driver.mapping.annotations.*;
27+import java.util.*;
2928
3029 import static com.datastax.driver.core.Assertions.assertThat;
3130
32-@CassandraVersion(major=2.1, minor=3)
31+@CassandraVersion(major = 2.1, minor = 3)
3332 public class MapperNestedCollectionsTest extends CCMBridge.PerClassSingleNodeCluster {
3433
3534 @Override
3635 protected Collection<String> getTableDefinitions() {
3736 return Lists.newArrayList(
38- "CREATE TYPE testType(i int, ls list<frozen<set<int>>>)",
39- "CREATE TABLE testTable (k int primary key, "
40- + "m1 map<text, frozen<map<int, int>>>, " // nested collection
41- + "m2 map<text, frozen<map<int, frozen<testType>>>>)" // nested collection with UDT
37+ "CREATE TYPE testType(i int, ls list<frozen<set<int>>>)",
38+ "CREATE TABLE testTable (k int primary key, "
39+ + "m1 map<text, frozen<map<int, int>>>, " // nested collection
40+ + "m2 map<text, frozen<map<int, frozen<testType>>>>)" // nested collection with UDT
4241 );
4342 }
4443
@@ -50,8 +49,8 @@
5049 testTable.setK(1);
5150 testTable.setM1(ImmutableMap.<String, Map<Integer, Integer>>of("bar", ImmutableMap.of(1, 2)));
5251
53- Set<Integer> s1 = Sets.newHashSet(1,2,3);
54- Set<Integer> s2 = Sets.newHashSet(4,5,6);
52+ Set<Integer> s1 = Sets.newHashSet(1, 2, 3);
53+ Set<Integer> s2 = Sets.newHashSet(4, 5, 6);
5554 List<Set<Integer>> ls = new ArrayList<Set<Integer>>();
5655 ls.add(s1);
5756 ls.add(s2);
@@ -129,7 +128,7 @@
129128 if (!(o instanceof TestType))
130129 return false;
131130
132- TestType testType = (TestType)o;
131+ TestType testType = (TestType) o;
133132
134133 if (i != testType.i)
135134 return false;
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java +25 −25
@@ -15,27 +15,25 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.Collection;
19-import java.util.concurrent.ExecutionException;
20-
21-import com.google.common.collect.Lists;
22-import org.testng.SkipException;
23-import org.testng.annotations.BeforeMethod;
24-import org.testng.annotations.Test;
25-
26-import static com.datastax.driver.core.ConsistencyLevel.*;
27-import static org.assertj.core.api.Assertions.assertThat;
28-import static org.assertj.core.api.Assertions.fail;
29-
3018 import com.datastax.driver.core.*;
3119 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3220 import com.datastax.driver.core.exceptions.UnavailableException;
3321 import com.datastax.driver.core.utils.CassandraVersion;
3422 import com.datastax.driver.mapping.annotations.PartitionKey;
3523 import com.datastax.driver.mapping.annotations.Table;
24+import com.google.common.collect.Lists;
25+import org.testng.SkipException;
26+import org.testng.annotations.BeforeMethod;
27+import org.testng.annotations.Test;
3628
29+import java.util.Collection;
30+import java.util.concurrent.ExecutionException;
31+
32+import static com.datastax.driver.core.ConsistencyLevel.*;
3733 import static com.datastax.driver.core.ProtocolVersion.V1;
3834 import static com.datastax.driver.mapping.Mapper.Option;
35+import static org.assertj.core.api.Assertions.assertThat;
36+import static org.assertj.core.api.Assertions.fail;
3937
4038 public class MapperOptionTest extends CCMBridge.PerClassSingleNodeCluster {
4139
@@ -69,7 +67,7 @@
6967 User todelete = new User(45, "todelete");
7068 mapper.save(todelete);
7169 Option opt = Option.timestamp(35);
72- BoundStatement bs = (BoundStatement)mapper.deleteQuery(45, opt, Option.consistencyLevel(QUORUM));
70+ BoundStatement bs = (BoundStatement) mapper.deleteQuery(45, opt, Option.consistencyLevel(QUORUM));
7371 assertThat(bs.preparedStatement().getQueryString()).contains("USING TIMESTAMP");
7472 assertThat(bs.getConsistencyLevel()).isEqualTo(QUORUM);
7573 }
@@ -80,7 +78,7 @@
8078 User user = new User(45, "toget");
8179 mapper.save(user);
8280
83- BoundStatement bs = (BoundStatement)mapper.getQuery(45, Option.tracing(true), Option.consistencyLevel(ALL));
81+ BoundStatement bs = (BoundStatement) mapper.getQuery(45, Option.tracing(true), Option.consistencyLevel(ALL));
8482 assertThat(bs.isTracing()).isTrue();
8583 assertThat(bs.getConsistencyLevel()).isEqualTo(ALL);
8684
@@ -107,32 +105,32 @@
107105 @CassandraVersion(major = 2.0)
108106 void should_use_default_options() {
109107 mapper.setDefaultSaveOptions(Option.timestamp(644746L), Option.ttl(76324));
110- BoundStatement bs = (BoundStatement)mapper.saveQuery(new User(46, "rjhrgce"));
108+ BoundStatement bs = (BoundStatement) mapper.saveQuery(new User(46, "rjhrgce"));
111109 assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP").contains("TTL");
112110
113111 mapper.resetDefaultSaveOptions();
114- bs = (BoundStatement)mapper.saveQuery(new User(47, "rjhrgce"));
112+ bs = (BoundStatement) mapper.saveQuery(new User(47, "rjhrgce"));
115113 assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP").doesNotContain("TTL");
116114
117115 mapper.setDefaultDeleteOptions(Option.timestamp(3245L), Option.tracing(true));
118- bs = (BoundStatement)mapper.deleteQuery(47);
116+ bs = (BoundStatement) mapper.deleteQuery(47);
119117 assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP");
120118 assertThat(bs.isTracing()).isTrue();
121119
122120 mapper.resetDefaultDeleteOptions();
123- bs = (BoundStatement)mapper.deleteQuery(47);
121+ bs = (BoundStatement) mapper.deleteQuery(47);
124122 assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP");
125123 assertThat(bs.isTracing()).isFalse();
126124
127- bs = (BoundStatement)mapper.saveQuery(new User(46, "rjhrgce"), Option.timestamp(23), Option.consistencyLevel(ConsistencyLevel.ANY));
125+ bs = (BoundStatement) mapper.saveQuery(new User(46, "rjhrgce"), Option.timestamp(23), Option.consistencyLevel(ConsistencyLevel.ANY));
128126 assertThat(bs.getConsistencyLevel()).isEqualTo(ConsistencyLevel.ANY);
129127
130128 mapper.setDefaultGetOptions(Option.tracing(true));
131- bs = (BoundStatement)mapper.getQuery(46);
129+ bs = (BoundStatement) mapper.getQuery(46);
132130 assertThat(bs.isTracing()).isTrue();
133131
134132 mapper.resetDefaultGetOptions();
135- bs = (BoundStatement)mapper.getQuery(46);
133+ bs = (BoundStatement) mapper.getQuery(46);
136134 assertThat(bs.isTracing()).isFalse();
137135 }
138136
@@ -170,7 +168,9 @@
170168 assertThat(savedTimestamp).isEqualTo(explicitTimestamp);
171169 }
172170
173- /** Cover all versions of save() to check that methods that call each other properly propagate the options */
171+ /**
172+ * Cover all versions of save() to check that methods that call each other properly propagate the options
173+ */
174174 @Test(groups = "short")
175175 @CassandraVersion(major = 2.0)
176176 void should_use_save_options_for_all_variants() throws ExecutionException, InterruptedException {
@@ -328,12 +328,12 @@
328328 assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
329329 }
330330
331- @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
331+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
332332 void should_fail_if_option_does_not_apply_to_query() {
333333 mapper.get(42, Option.ttl(1));
334334 }
335335
336- @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
336+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
337337 void should_fail_when_using_ttl_with_protocol_v1() {
338338 if (protocolVersion.compareTo(V1) > 0)
339339 throw new SkipException("Skipped when protocol version > V1");
@@ -341,7 +341,7 @@
341341 mapper.saveQuery(new User(42, "helloworld"), Option.ttl(15));
342342 }
343343
344- @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
344+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
345345 void should_fail_when_using_timestamp_with_protocol_v1() {
346346 if (protocolVersion.compareTo(V1) > 0)
347347 throw new SkipException("Skipped when protocol version > V1");
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperPrimitiveTypes22Test.java +6 −6
@@ -29,16 +29,16 @@
2929
3030 import static org.testng.Assert.assertEquals;
3131
32-@CassandraVersion(major=2.2)
32+@CassandraVersion(major = 2.2)
3333 public class MapperPrimitiveTypes22Test extends CCMBridge.PerClassSingleNodeCluster {
3434
3535 protected Collection<String> getTableDefinitions() {
3636 return Arrays.asList("CREATE TABLE primitiveTypes22 ("
37- + "byteBufferCol blob primary key,"
38- + "localDateCol date,"
39- + "timeCol time, timeWrapperCol time,"
40- + "byteCol tinyint, byteWrapperCol tinyint,"
41- + "shortCol smallint, shortWrapperCol smallint)");
37+ + "byteBufferCol blob primary key,"
38+ + "localDateCol date,"
39+ + "timeCol time, timeWrapperCol time,"
40+ + "byteCol tinyint, byteWrapperCol tinyint,"
41+ + "shortCol smallint, shortWrapperCol smallint)");
4242 }
4343
4444 @Test(groups = "short")
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperPrimitiveTypesTest.java +13 −13
@@ -40,19 +40,19 @@
4040
4141 protected Collection<String> getTableDefinitions() {
4242 return Arrays.asList("CREATE TABLE primitiveTypes ("
43- + "byteBufferCol blob primary key,"
44- + "intCol int, intWrapperCol int,"
45- + "longCol bigint, longWrapperCol bigint,"
46- + "floatCol float, floatWrapperCol float,"
47- + "doubleCol double, doubleWrapperCol double,"
48- + "booleanCol boolean, booleanWrapperCol boolean,"
49- + "bigDecimalCol decimal,"
50- + "bigIntegerCol varint,"
51- + "stringCol text,"
52- + "inetCol inet,"
53- + "dateCol timestamp,"
54- + "uuidCol uuid,"
55- + "timeUuidCol timeuuid)");
43+ + "byteBufferCol blob primary key,"
44+ + "intCol int, intWrapperCol int,"
45+ + "longCol bigint, longWrapperCol bigint,"
46+ + "floatCol float, floatWrapperCol float,"
47+ + "doubleCol double, doubleWrapperCol double,"
48+ + "booleanCol boolean, booleanWrapperCol boolean,"
49+ + "bigDecimalCol decimal,"
50+ + "bigIntegerCol varint,"
51+ + "stringCol text,"
52+ + "inetCol inet,"
53+ + "dateCol timestamp,"
54+ + "uuidCol uuid,"
55+ + "timeUuidCol timeuuid)");
5656 }
5757
5858 @Test(groups = "short")
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperSaveNullFieldsTest.java +13 −14
@@ -15,19 +15,18 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.Collection;
19-
20-import com.google.common.collect.Lists;
21-import org.testng.annotations.BeforeMethod;
22-import org.testng.annotations.Test;
23-
24-import static org.assertj.core.api.Assertions.assertThat;
25-
2618 import com.datastax.driver.core.BoundStatement;
2719 import com.datastax.driver.core.CCMBridge;
2820 import com.datastax.driver.mapping.Mapper.Option;
2921 import com.datastax.driver.mapping.annotations.PartitionKey;
3022 import com.datastax.driver.mapping.annotations.Table;
23+import com.google.common.collect.Lists;
24+import org.testng.annotations.BeforeMethod;
25+import org.testng.annotations.Test;
26+
27+import java.util.Collection;
28+
29+import static org.assertj.core.api.Assertions.assertThat;
3130
3231 public class MapperSaveNullFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
3332
@@ -75,7 +74,7 @@
7574 private void should_save_null_fields(boolean nullName, boolean nullPhone, boolean saveExpected, Option... options) {
7675 // Start with clean data
7776 session.execute("insert into user(login, name, phone) "
78- + "values ('test_login', 'previous_name', 'previous_phone')");
77+ + "values ('test_login', 'previous_name', 'previous_phone')");
7978
8079 String newName = nullName ? null : "new_name";
8180 String newPhone = nullPhone ? null : "new_phone";
@@ -83,7 +82,7 @@
8382 User newUser = new User("test_login", newName, newPhone);
8483
8584 // Check if null fields are included in generated statement:
86- BoundStatement bs = (BoundStatement)mapper.saveQuery(newUser, options);
85+ BoundStatement bs = (BoundStatement) mapper.saveQuery(newUser, options);
8786 String queryString = bs.preparedStatement().getQueryString();
8887 if (nullName && !saveExpected)
8988 assertThat(queryString).as(description).doesNotContain("\"name\"");
@@ -99,11 +98,11 @@
9998 mapper.save(newUser, options);
10099 User savedUser = mapper.get("test_login");
101100 String expectedName = nullName
102- ? (saveExpected ? null : "previous_name")
103- : "new_name";
101+ ? (saveExpected ? null : "previous_name")
102+ : "new_name";
104103 String expectedPhone = nullPhone
105- ? (saveExpected ? null : "previous_phone")
106- : "new_phone";
104+ ? (saveExpected ? null : "previous_phone")
105+ : "new_phone";
107106 assertThat(savedUser.getName()).as(description).isEqualTo(expectedName);
108107 assertThat(savedUser.getPhone()).as(description).isEqualTo(expectedPhone);
109108 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +31 −31
@@ -15,22 +15,20 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.net.InetAddress;
19-
18+import com.datastax.driver.core.*;
2019 import com.datastax.driver.core.utils.CassandraVersion;
21-import com.datastax.driver.mapping.annotations.Table;
22-import java.util.*;
23-
20+import com.datastax.driver.core.utils.UUIDs;
21+import com.datastax.driver.mapping.annotations.*;
2422 import com.google.common.base.Objects;
2523 import com.google.common.util.concurrent.ListenableFuture;
2624 import org.testng.annotations.Test;
2725
28-import static org.assertj.core.api.Assertions.assertThat;
29-import static org.testng.Assert.*;
26+import java.net.InetAddress;
27+import java.util.*;
3028
31-import com.datastax.driver.mapping.annotations.*;
32-import com.datastax.driver.core.*;
33-import com.datastax.driver.core.utils.UUIDs;
29+import static org.assertj.core.api.Assertions.assertThat;
30+import static org.testng.Assert.assertEquals;
31+import static org.testng.Assert.assertTrue;
3432
3533 /**
3634 * Basic tests for the mapping module.
@@ -42,7 +40,7 @@
4240 // We'll allow to generate those create statement from the annotated entities later, but it's currently
4341 // a TODO
4442 return Arrays.asList("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)",
45- "CREATE TABLE posts (user_id uuid, post_id timeuuid, title text, content text, device inet, tags set<text>, PRIMARY KEY(user_id, post_id))");
43+ "CREATE TABLE posts (user_id uuid, post_id timeuuid, title text, content text, device inet, tags set<text>, PRIMARY KEY(user_id, post_id))");
4644 }
4745
4846 /*
@@ -58,8 +56,8 @@
5856 */
5957 @SuppressWarnings("unused")
6058 @Table(name = "users",
61- readConsistency="QUORUM",
62- writeConsistency="QUORUM")
59+ readConsistency = "QUORUM",
60+ writeConsistency = "QUORUM")
6361 public static class User {
6462
6563 // Dummy constant to test that static fields are properly ignored
@@ -74,7 +72,8 @@
7472 @Column // not strictly required, but we want to check that the annotation works without a name
7573 private int year;
7674
77- public User() {}
75+ public User() {
76+ }
7877
7978 public User(String name, String email) {
8079 this.userId = UUIDs.random();
@@ -119,11 +118,11 @@
119118 if (other == null || other.getClass() != this.getClass())
120119 return false;
121120
122- User that = (User)other;
121+ User that = (User) other;
123122 return Objects.equal(userId, that.userId)
124- && Objects.equal(name, that.name)
125- && Objects.equal(email, that.email)
126- && Objects.equal(year, that.year);
123+ && Objects.equal(name, that.name)
124+ && Objects.equal(email, that.email)
125+ && Objects.equal(year, that.year);
127126 }
128127
129128 @Override
@@ -156,7 +155,8 @@
156155
157156 private Set<String> tags;
158157
159- public Post() {}
158+ public Post() {
159+ }
160160
161161 public Post(User user, String title) {
162162 this.userId = user.getUserId();
@@ -217,13 +217,13 @@
217217 if (other == null || other.getClass() != this.getClass())
218218 return false;
219219
220- Post that = (Post)other;
220+ Post that = (Post) other;
221221 return Objects.equal(userId, that.userId)
222- && Objects.equal(postId, that.postId)
223- && Objects.equal(title, that.title)
224- && Objects.equal(content, that.content)
225- && Objects.equal(device, that.device)
226- && Objects.equal(tags, that.tags);
222+ && Objects.equal(postId, that.postId)
223+ && Objects.equal(title, that.title)
224+ && Objects.equal(content, that.content)
225+ && Objects.equal(device, that.device)
226+ && Objects.equal(tags, that.tags);
227227 }
228228
229229 @Override
@@ -257,13 +257,13 @@
257257 // somehow, but well, not a huge deal.
258258 @Query("SELECT * FROM posts WHERE user_id=:userId AND post_id=:postId")
259259 Post getOne(@Param("userId") UUID userId,
260- @Param("postId") UUID postId);
260+ @Param("postId") UUID postId);
261261
262262 // Note that the following method will be asynchronous (it will use executeAsync
263263 // underneath) because it's return type is a ListenableFuture. Similarly, we know
264264 // that we need to map the result to the Post entity thanks to the return type.
265265 @Query("SELECT * FROM posts WHERE user_id=?")
266- @QueryParameters(consistency="QUORUM")
266+ @QueryParameters(consistency = "QUORUM")
267267 ListenableFuture<Result<Post>> getAllAsync(UUID userId);
268268
269269 // The method above actually query stuff, but if a method is declared to return
@@ -295,7 +295,7 @@
295295 }
296296
297297 @Test(groups = "short")
298- @CassandraVersion(major=2.0)
298+ @CassandraVersion(major = 2.0)
299299 public void testDynamicEntity() throws Exception {
300300 MappingManager manager = new MappingManager(session);
301301
@@ -355,7 +355,7 @@
355355
356356 }
357357
358- @Test(groups="short")
358+ @Test(groups = "short")
359359 public void should_map_objects_from_partial_queries() throws Exception {
360360 MappingManager manager = new MappingManager(session);
361361
@@ -392,7 +392,7 @@
392392 }
393393
394394
395- @Test(groups="short")
395+ @Test(groups = "short")
396396 public void should_return_table_metadata() throws Exception {
397397 MappingManager manager = new MappingManager(session);
398398
@@ -403,7 +403,7 @@
403403 assertThat(m.getTableMetadata().getPartitionKey()).hasSize(1);
404404 }
405405
406- @Test(groups="short")
406+ @Test(groups = "short")
407407 public void should_not_initialize_session_when_protocol_version_provided() {
408408 Session newSession = cluster.newSession();
409409
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTCollectionsTest.java +11 −12
@@ -15,8 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.CCMBridge;
2019 import com.datastax.driver.mapping.annotations.*;
2120 import com.google.common.base.Objects;
2221 import com.google.common.collect.ImmutableMap;
@@ -24,9 +23,9 @@
2423 import org.testng.annotations.Test;
2524 import org.testng.collections.Lists;
2625
27-import static org.testng.Assert.assertEquals;
26+import java.util.*;
2827
29-import com.datastax.driver.core.CCMBridge;
28+import static org.testng.Assert.assertEquals;
3029
3130 /**
3231 * Tests mapping of collections of UDTs.
@@ -35,7 +34,7 @@
3534
3635 protected Collection<String> getTableDefinitions() {
3736 return Arrays.asList("CREATE TYPE sub(i int)",
38- "CREATE TABLE collection_examples (id int PRIMARY KEY, l list<frozen<sub>>, s set<frozen<sub>>, m1 map<int,frozen<sub>>, m2 map<frozen<sub>,int>, m3 map<frozen<sub>,frozen<sub>>)");
37+ "CREATE TABLE collection_examples (id int PRIMARY KEY, l list<frozen<sub>>, s set<frozen<sub>>, m1 map<int,frozen<sub>>, m2 map<frozen<sub>,int>, m3 map<frozen<sub>,frozen<sub>>)");
3938 }
4039
4140 @UDT(name = "sub")
@@ -60,7 +59,7 @@
6059 @Override
6160 public boolean equals(Object other) {
6261 if (other instanceof Sub) {
63- Sub that = (Sub)other;
62+ Sub that = (Sub) other;
6463 return this.i == that.i;
6564 }
6665 return false;
@@ -159,13 +158,13 @@
159158 @Override
160159 public boolean equals(Object other) {
161160 if (other instanceof CollectionExamples) {
162- CollectionExamples that = (CollectionExamples)other;
161+ CollectionExamples that = (CollectionExamples) other;
163162 return Objects.equal(this.id, that.id) &&
164- Objects.equal(this.l, that.l) &&
165- Objects.equal(this.s, that.s) &&
166- Objects.equal(this.m1, that.m1) &&
167- Objects.equal(this.m2, that.m2) &&
168- Objects.equal(this.m3, that.m3);
163+ Objects.equal(this.l, that.l) &&
164+ Objects.equal(this.s, that.s) &&
165+ Objects.equal(this.m1, that.m1) &&
166+ Objects.equal(this.m2, that.m2) &&
167+ Objects.equal(this.m3, that.m3);
169168 }
170169 return false;
171170 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +25 −30
@@ -15,32 +15,27 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.*;
19-
2018 import com.datastax.driver.core.*;
2119 import com.datastax.driver.core.exceptions.CodecNotFoundException;
20+import com.datastax.driver.core.utils.UUIDs;
21+import com.datastax.driver.mapping.annotations.*;
22+import com.google.common.base.Objects;
2223 import com.google.common.collect.Maps;
2324 import org.assertj.core.data.MapEntry;
2425 import org.testng.annotations.BeforeMethod;
25-
26-import com.google.common.base.Objects;
2726 import org.testng.annotations.Test;
2827
28+import java.util.*;
29+
2930 import static org.assertj.core.api.Assertions.assertThat;
3031 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.*;
32+import static org.testng.Assert.*;
3833
3934 public class MapperUDTTest extends CCMBridge.PerClassSingleNodeCluster {
4035
4136 protected Collection<String> getTableDefinitions() {
4237 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>>)");
38+ "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
4439 }
4540
4641 @BeforeMethod(groups = "short")
@@ -49,8 +44,8 @@
4944 }
5045
5146 @Table(name = "users",
52- readConsistency = "QUORUM",
53- writeConsistency = "QUORUM")
47+ readConsistency = "QUORUM",
48+ writeConsistency = "QUORUM")
5449 public static class User {
5550 @PartitionKey
5651 @Column(name = "user_id")
@@ -118,9 +113,9 @@
118113 if (other instanceof User) {
119114 User that = (User) other;
120115 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);
116+ Objects.equal(this.name, that.name) &&
117+ Objects.equal(this.mainAddress, that.mainAddress) &&
118+ Objects.equal(this.otherAddresses, that.otherAddresses);
124119 }
125120 return false;
126121 }
@@ -133,11 +128,11 @@
133128 @Override
134129 public String toString() {
135130 return Objects.toStringHelper(User.class)
136- .add("userId", userId)
137- .add("name", name)
138- .add("mainAddress", mainAddress)
139- .add("otherAddresses", otherAddresses)
140- .toString();
131+ .add("userId", userId)
132+ .add("name", name)
133+ .add("mainAddress", mainAddress)
134+ .add("otherAddresses", otherAddresses)
135+ .toString();
141136 }
142137 }
143138
@@ -210,9 +205,9 @@
210205 if (other instanceof Address) {
211206 Address that = (Address) other;
212207 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);
208+ Objects.equal(this.city, that.city) &&
209+ Objects.equal(this.zipCode, that.zipCode) &&
210+ Objects.equal(this.phones, that.phones);
216211 }
217212 return false;
218213 }
@@ -225,11 +220,11 @@
225220 @Override
226221 public String toString() {
227222 return Objects.toStringHelper(Address.class)
228- .add("street", street)
229- .add("city", city)
230- .add("zip", zipCode)
231- .add("phones", phones)
232- .toString();
223+ .add("street", street)
224+ .add("city", city)
225+ .add("zip", zipCode)
226+ .add("phones", phones)
227+ .toString();
233228 }
234229 }
235230
modified driver-mapping/src/test/java/com/datastax/driver/mapping/UDTFieldMapperTest.java +36 −38
@@ -15,20 +15,18 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.HashMap;
19-import java.util.Map;
20-
21-import com.google.common.collect.ImmutableMap;
22-import org.testng.annotations.Test;
23-
2418 import com.datastax.driver.core.CCMBridge;
2519 import com.datastax.driver.core.Cluster;
2620 import com.datastax.driver.core.Session;
27-import com.datastax.driver.core.TestUtils;
2821 import com.datastax.driver.core.utils.CassandraVersion;
2922 import com.datastax.driver.mapping.annotations.*;
23+import com.google.common.collect.ImmutableMap;
24+import org.testng.annotations.Test;
25+
26+import java.util.HashMap;
27+import java.util.Map;
3028
31-@CassandraVersion(major=2.1)
29+@CassandraVersion(major = 2.1)
3230 public class UDTFieldMapperTest {
3331
3432 @Test(groups = "short")
@@ -42,13 +40,13 @@
4240 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
4341 Session session1 = cluster.connect();
4442 session1.execute("create schema if not exists java_509 " +
45- "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
43+ "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
4644 session1.execute("create type java_509.my_tuple (" +
47- "type text, " +
48- "value text);");
45+ "type text, " +
46+ "value text);");
4947 session1.execute("create table java_509.my_hash (" +
50- "key int primary key, " +
51- "properties map<text, frozen<java_509.my_tuple>>);");
48+ "key int primary key, " +
49+ "properties map<text, frozen<java_509.my_tuple>>);");
5250 cluster.close();
5351
5452 // Create entities with another connection
@@ -56,20 +54,20 @@
5654 Session session2 = cluster.newSession();
5755 Mapper<MyHashWithKeyspace> hashMapper = new MappingManager(session2).mapper(MyHashWithKeyspace.class);
5856 hashMapper.save(new MyHashWithKeyspace(
59- 1,
60- ImmutableMap.of("key-1", new MyTupleWithKeyspace("first-half-1", "second-half-1"))));
57+ 1,
58+ ImmutableMap.of("key-1", new MyTupleWithKeyspace("first-half-1", "second-half-1"))));
6159 hashMapper.save(new MyHashWithKeyspace(
62- 2,
63- ImmutableMap.of("key-2", new MyTupleWithKeyspace("first-half-2", null))));
60+ 2,
61+ ImmutableMap.of("key-2", new MyTupleWithKeyspace("first-half-2", null))));
6462 hashMapper.save(new MyHashWithKeyspace(
65- 3,
66- ImmutableMap.of("key-3", new MyTupleWithKeyspace(null, "second-half-3"))));
63+ 3,
64+ ImmutableMap.of("key-3", new MyTupleWithKeyspace(null, "second-half-3"))));
6765 hashMapper.save(new MyHashWithKeyspace(
68- 4,
69- new HashMap<String, MyTupleWithKeyspace>()));
66+ 4,
67+ new HashMap<String, MyTupleWithKeyspace>()));
7068 hashMapper.save(new MyHashWithKeyspace(
71- 5,
72- null));
69+ 5,
70+ null));
7371 } finally {
7472 if (cluster != null)
7573 cluster.close();
@@ -89,14 +87,14 @@
8987 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
9088 Session session1 = cluster.connect();
9189 session1.execute("create schema if not exists java_509 " +
92- "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
90+ "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
9391 session1.execute("use java_509");
9492 session1.execute("create type my_tuple (" +
95- "type text, " +
96- "value text);");
93+ "type text, " +
94+ "value text);");
9795 session1.execute("create table my_hash (" +
98- "key int primary key, " +
99- "properties map<text, frozen<my_tuple>>);");
96+ "key int primary key, " +
97+ "properties map<text, frozen<my_tuple>>);");
10098 cluster.close();
10199
102100 // Create entities with another connection
@@ -106,20 +104,20 @@
106104 session2.execute("use java_509");
107105 Mapper<MyHash> hashMapper = new MappingManager(session2).mapper(MyHash.class);
108106 hashMapper.save(new MyHash(
109- 1,
110- ImmutableMap.of("key-1", new MyTuple("first-half-1", "second-half-1"))));
107+ 1,
108+ ImmutableMap.of("key-1", new MyTuple("first-half-1", "second-half-1"))));
111109 hashMapper.save(new MyHash(
112- 2,
113- ImmutableMap.of("key-2", new MyTuple("first-half-2", null))));
110+ 2,
111+ ImmutableMap.of("key-2", new MyTuple("first-half-2", null))));
114112 hashMapper.save(new MyHash(
115- 3,
116- ImmutableMap.of("key-3", new MyTuple(null, "second-half-3"))));
113+ 3,
114+ ImmutableMap.of("key-3", new MyTuple(null, "second-half-3"))));
117115 hashMapper.save(new MyHash(
118- 4,
119- new HashMap<String, MyTuple>()));
116+ 4,
117+ new HashMap<String, MyTuple>()));
120118 hashMapper.save(new MyHash(
121- 5,
122- null));
119+ 5,
120+ null));
123121 } finally {
124122 if (cluster != null)
125123 cluster.close();

Previous files