Elffuss BraidHub

kikocis/java-driver public

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

Browse the files at this changeset

More than 300 files changed

modified driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java +6 −6
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+
1820 import java.math.BigDecimal;
1921 import java.math.BigInteger;
2022 import java.net.InetAddress;
2123 import java.nio.ByteBuffer;
2224 import java.util.*;
2325
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
25-
2626 abstract class AbstractAddressableByIndexData<T extends SettableByIndexData<T>> extends AbstractGettableByIndexData implements SettableByIndexData<T> {
2727
2828 final ByteBuffer[] values;
@@ -35,7 +35,7 @@
3535 @SuppressWarnings("unchecked")
3636 protected T setValue(int i, ByteBuffer value) {
3737 values[i] = value;
38- return (T)this;
38+ return (T) this;
3939 }
4040
4141 protected ByteBuffer getValue(int i) {
@@ -114,8 +114,8 @@
114114 throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", v));
115115
116116 return type == DataType.Name.UUID
117- ? setValue(i, TypeCodec.uuidCodec.serialize(v))
118- : setValue(i, TypeCodec.timeUuidCodec.serialize(v));
117+ ? setValue(i, TypeCodec.uuidCodec.serialize(v))
118+ : setValue(i, TypeCodec.timeUuidCodec.serialize(v));
119119 }
120120
121121 public T setInet(int i, InetAddress v) {
@@ -217,7 +217,7 @@
217217 if (!(o instanceof AbstractAddressableByIndexData))
218218 return false;
219219
220- AbstractAddressableByIndexData<?> that = (AbstractAddressableByIndexData<?>)o;
220+ AbstractAddressableByIndexData<?> that = (AbstractAddressableByIndexData<?>) o;
221221 if (values.length != that.values.length)
222222 return false;
223223
modified driver-core/src/main/java/com/datastax/driver/core/AbstractData.java +6 −6
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+
1820 import java.math.BigDecimal;
1921 import java.math.BigInteger;
2022 import java.net.InetAddress;
2123 import java.nio.ByteBuffer;
2224 import java.util.*;
2325
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
25-
2626 // We don't want to expose this one: it's less useful externally and it's a bit ugly to expose anyway (but it's convenient).
2727 abstract class AbstractData<T extends SettableData<T>> extends AbstractGettableData implements SettableData<T> {
2828
@@ -34,7 +34,7 @@
3434 @SuppressWarnings("unchecked")
3535 protected AbstractData(ProtocolVersion protocolVersion, int size) {
3636 super(protocolVersion);
37- this.wrapped = (T)this;
37+ this.wrapped = (T) this;
3838 this.values = new ByteBuffer[size];
3939 }
4040
@@ -240,8 +240,8 @@
240240 throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", v));
241241
242242 return type == DataType.Name.UUID
243- ? setValue(i, TypeCodec.uuidCodec.serialize(v))
244- : setValue(i, TypeCodec.timeUuidCodec.serialize(v));
243+ ? setValue(i, TypeCodec.uuidCodec.serialize(v))
244+ : setValue(i, TypeCodec.timeUuidCodec.serialize(v));
245245 }
246246
247247 public T setUUID(String name, UUID v) {
@@ -426,7 +426,7 @@
426426 if (!(o instanceof AbstractData))
427427 return false;
428428
429- AbstractData<?> that = (AbstractData<?>)o;
429+ AbstractData<?> that = (AbstractData<?>) o;
430430 if (values.length != that.values.length)
431431 return false;
432432
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java +18 −27
@@ -15,20 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.google.common.reflect.TypeToken;
20+
1821 import java.math.BigDecimal;
1922 import java.math.BigInteger;
2023 import java.net.InetAddress;
2124 import java.nio.ByteBuffer;
22-import java.util.Collections;
23-import java.util.Date;
24-import java.util.List;
25-import java.util.Map;
26-import java.util.Set;
27-import java.util.UUID;
28-
29-import com.google.common.reflect.TypeToken;
30-
31-import com.datastax.driver.core.exceptions.InvalidTypeException;
25+import java.util.*;
3226
3327 abstract class AbstractGettableByIndexData implements GettableByIndexData {
3428
@@ -43,7 +37,6 @@
4337 *
4438 * @param i the index of the type to fetch.
4539 * @return the type of the value at index {@code i}.
46- *
4740 * @throws IndexOutOfBoundsException if {@code i} is not a valid index.
4841 */
4942 protected abstract DataType getType(int i);
@@ -53,7 +46,6 @@
5346 *
5447 * @param i the index of the name to fetch.
5548 * @return the name corresponding to the value at index {@code i}.
56- *
5749 * @throws IndexOutOfBoundsException if {@code i} is not a valid index.
5850 */
5951 protected abstract String getName(int i);
@@ -63,7 +55,6 @@
6355 *
6456 * @param i the index to fetch.
6557 * @return the value at index {@code i}.
66- *
6758 * @throws IndexOutOfBoundsException if {@code i} is not a valid index.
6859 */
6960 protected abstract ByteBuffer getValue(int i);
@@ -210,16 +201,16 @@
210201 @Override
211202 public String getString(int i) {
212203 DataType.Name type = checkType(i, DataType.Name.VARCHAR,
213- DataType.Name.TEXT,
214- DataType.Name.ASCII);
204+ DataType.Name.TEXT,
205+ DataType.Name.ASCII);
215206
216207 ByteBuffer value = getValue(i);
217208 if (value == null)
218209 return null;
219210
220211 return type == DataType.Name.ASCII
221- ? TypeCodec.asciiStringCodec.deserialize(value)
222- : TypeCodec.utf8StringCodec.deserialize(value);
212+ ? TypeCodec.asciiStringCodec.deserialize(value)
213+ : TypeCodec.utf8StringCodec.deserialize(value);
223214 }
224215
225216 /**
@@ -262,8 +253,8 @@
262253 return null;
263254
264255 return type == DataType.Name.UUID
265- ? TypeCodec.uuidCodec.deserialize(value)
266- : TypeCodec.timeUuidCodec.deserialize(value);
256+ ? TypeCodec.uuidCodec.deserialize(value)
257+ : TypeCodec.timeUuidCodec.deserialize(value);
267258 }
268259
269260 /**
@@ -298,7 +289,7 @@
298289 if (value == null)
299290 return Collections.<T>emptyList();
300291
301- return Collections.unmodifiableList((List<T>)type.codec(protocolVersion).deserialize(value));
292+ return Collections.unmodifiableList((List<T>) type.codec(protocolVersion).deserialize(value));
302293 }
303294
304295 /**
@@ -319,7 +310,7 @@
319310 if (value == null)
320311 return Collections.<T>emptyList();
321312
322- return Collections.unmodifiableList((List<T>)type.codec(protocolVersion).deserialize(value));
313+ return Collections.unmodifiableList((List<T>) type.codec(protocolVersion).deserialize(value));
323314 }
324315
325316 /**
@@ -340,7 +331,7 @@
340331 if (value == null)
341332 return Collections.<T>emptySet();
342333
343- return Collections.unmodifiableSet((Set<T>)type.codec(protocolVersion).deserialize(value));
334+ return Collections.unmodifiableSet((Set<T>) type.codec(protocolVersion).deserialize(value));
344335 }
345336
346337 /**
@@ -361,7 +352,7 @@
361352 if (value == null)
362353 return Collections.<T>emptySet();
363354
364- return Collections.unmodifiableSet((Set<T>)type.codec(protocolVersion).deserialize(value));
355+ return Collections.unmodifiableSet((Set<T>) type.codec(protocolVersion).deserialize(value));
365356 }
366357
367358 /**
@@ -383,7 +374,7 @@
383374 if (value == null)
384375 return Collections.<K, V>emptyMap();
385376
386- return Collections.unmodifiableMap((Map<K, V>)type.codec(protocolVersion).deserialize(value));
377+ return Collections.unmodifiableMap((Map<K, V>) type.codec(protocolVersion).deserialize(value));
387378 }
388379
389380 /**
@@ -405,7 +396,7 @@
405396 if (value == null)
406397 return Collections.<K, V>emptyMap();
407398
408- return Collections.unmodifiableMap((Map<K, V>)type.codec(protocolVersion).deserialize(value));
399+ return Collections.unmodifiableMap((Map<K, V>) type.codec(protocolVersion).deserialize(value));
409400 }
410401
411402 /**
@@ -423,7 +414,7 @@
423414 return null;
424415
425416 // UDT always use the protocol V3 to encode values
426- return (UDTValue)type.codec(ProtocolVersion.V3).deserialize(value);
417+ return (UDTValue) type.codec(ProtocolVersion.V3).deserialize(value);
427418 }
428419
429420 /**
@@ -441,7 +432,7 @@
441432 return null;
442433
443434 // tuples always use the protocol V3 to encode values
444- return (TupleValue)type.codec(ProtocolVersion.V3).deserialize(value);
435+ return (TupleValue) type.codec(ProtocolVersion.V3).deserialize(value);
445436 }
446437
447438 /**
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java +5 −8
@@ -15,24 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.reflect.TypeToken;
19+
1820 import java.math.BigDecimal;
1921 import java.math.BigInteger;
2022 import java.net.InetAddress;
2123 import java.nio.ByteBuffer;
2224 import java.util.*;
2325
24-import com.google.common.reflect.TypeToken;
25-
2626 public abstract class AbstractGettableData extends AbstractGettableByIndexData implements GettableData {
2727
2828 /**
2929 * Creates a new AbstractGettableData object.
3030 *
3131 * @param protocolVersion the protocol version in which values returned
32- * by {@link #getValue} will be returned. This must be a protocol version
33- * supported by this driver. In general, the correct value will be the
34- * value returned by {@link ProtocolOptions#getProtocolVersion}.
35- *
32+ * by {@link #getValue} will be returned. This must be a protocol version
33+ * supported by this driver. In general, the correct value will be the
34+ * value returned by {@link ProtocolOptions#getProtocolVersion}.
3635 * @throws IllegalArgumentException if {@code protocolVersion} is not a valid protocol version.
3736 */
3837 protected AbstractGettableData(ProtocolVersion protocolVersion) {
@@ -41,7 +40,6 @@
4140
4241 /**
4342 * @throws IllegalArgumentException if {@code protocolVersion} does not correspond to any known version.
44- *
4543 * @deprecated This constructor is provided for backward compatibility, use {@link #AbstractGettableData(ProtocolVersion)} instead.
4644 */
4745 @Deprecated
@@ -54,7 +52,6 @@
5452 *
5553 * @param name the name for which to return the index of.
5654 * @return the index for the value coressponding to {@code name}.
57- *
5855 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
5956 */
6057 protected abstract int getIndexOf(String name);
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +25 −13
@@ -15,25 +15,24 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.*;
19-import java.util.concurrent.atomic.AtomicReference;
20-
18+import com.datastax.driver.core.exceptions.AuthenticationException;
19+import com.datastax.driver.core.policies.ReconnectionPolicy;
2120 import com.google.common.annotations.VisibleForTesting;
22-import com.google.common.util.concurrent.ListenableFuture;
2321 import com.google.common.util.concurrent.AbstractFuture;
22+import com.google.common.util.concurrent.ListenableFuture;
2423 import org.slf4j.Logger;
2524 import org.slf4j.LoggerFactory;
2625
27-import com.datastax.driver.core.exceptions.AuthenticationException;
28-import com.datastax.driver.core.policies.ReconnectionPolicy;
26+import java.util.concurrent.*;
27+import java.util.concurrent.atomic.AtomicReference;
2928
3029 /**
3130 * Manages periodic reconnection attempts after a host has been marked down.
32- * <p>
31+ * <p/>
3332 * Concurrent attempts are handled via the {@link #currentAttempt} reference passed to the constructor.
3433 * For a given reference, only one handler will run at a given time. Additional handlers will cancel
3534 * themselves if they find a previous handler running.
36- * <p>
35+ * <p/>
3736 * This class is designed for concurrency, but instances must not be shared: each thread creates and
3837 * starts its own private handler, all interactions happen through {@link #currentAttempt}.
3938 */
@@ -68,18 +67,31 @@
6867 }
6968
7069 protected abstract Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException;
70+
7171 protected abstract void onReconnection(Connection connection);
7272
73- protected boolean onConnectionException(ConnectionException e, long nextDelayMs) { return true; }
74- protected boolean onUnknownException(Exception e, long nextDelayMs) { return true; }
73+ protected boolean onConnectionException(ConnectionException e, long nextDelayMs) {
74+ return true;
75+ }
76+
77+ protected boolean onUnknownException(Exception e, long nextDelayMs) {
78+ return true;
79+ }
7580
7681 // Retrying on authentication errors makes sense for applications that can update the credentials at runtime, we don't want to force them
7782 // to restart.
78- protected boolean onAuthenticationException(AuthenticationException e, long nextDelayMs) { return true; }
83+ protected boolean onAuthenticationException(AuthenticationException e, long nextDelayMs) {
84+ return true;
85+ }
7986
8087 // Retrying on these errors is unlikely to work
81- protected boolean onUnsupportedProtocolVersionException(UnsupportedProtocolVersionException e, long nextDelayMs) { return false; }
82- protected boolean onClusterNameMismatchException(ClusterNameMismatchException e, long nextDelayMs) { return false; }
88+ protected boolean onUnsupportedProtocolVersionException(UnsupportedProtocolVersionException e, long nextDelayMs) {
89+ return false;
90+ }
91+
92+ protected boolean onClusterNameMismatchException(ClusterNameMismatchException e, long nextDelayMs) {
93+ return false;
94+ }
8395
8496 public void start() {
8597 long firstDelay = (initialDelayMs >= 0) ? initialDelayMs : schedule.nextDelayMs();
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +6 −4
@@ -15,15 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.base.Function;
19+import com.google.common.util.concurrent.Futures;
20+import com.google.common.util.concurrent.ListenableFuture;
21+import com.google.common.util.concurrent.Uninterruptibles;
22+
1823 import java.nio.ByteBuffer;
1924 import java.util.concurrent.ExecutionException;
2025
21-import com.google.common.base.Function;
22-import com.google.common.util.concurrent.*;
23-
2426 /**
2527 * Abstract implementation of the Session interface.
26- *
28+ * <p/>
2729 * This is primarly intended to make mocking easier.
2830 */
2931 public abstract class AbstractSession implements Session, AsyncInitSession {
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +16 −17
@@ -15,20 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.*;
20-import java.util.concurrent.ConcurrentLinkedQueue;
21-import java.util.concurrent.ExecutionException;
22-import java.util.concurrent.LinkedBlockingDeque;
23-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+import com.datastax.driver.core.utils.MoreFutures;
2420 import com.google.common.util.concurrent.ListenableFuture;
2521 import com.google.common.util.concurrent.SettableFuture;
2622 import com.google.common.util.concurrent.Uninterruptibles;
2723 import org.slf4j.Logger;
2824 import org.slf4j.LoggerFactory;
2925
30-import com.datastax.driver.core.exceptions.DriverInternalError;
31-import com.datastax.driver.core.utils.MoreFutures;
26+import java.nio.ByteBuffer;
27+import java.util.*;
28+import java.util.concurrent.ConcurrentLinkedQueue;
29+import java.util.concurrent.ExecutionException;
30+import java.util.concurrent.LinkedBlockingDeque;
3231
3332 /**
3433 * Default implementation of a result set, backed by an ArrayDeque of ArrayList.
@@ -59,26 +58,26 @@
5958 case VOID:
6059 return empty(info);
6160 case ROWS:
62- Responses.Result.Rows r = (Responses.Result.Rows)msg;
61+ Responses.Result.Rows r = (Responses.Result.Rows) msg;
6362
6463 ColumnDefinitions columnDefs;
6564 if (r.metadata.columns == null) {
6665 assert statement instanceof BoundStatement;
67- columnDefs = ((BoundStatement)statement).statement.getPreparedId().resultSetMetadata;
66+ columnDefs = ((BoundStatement) statement).statement.getPreparedId().resultSetMetadata;
6867 assert columnDefs != null;
6968 } else {
7069 columnDefs = r.metadata.columns;
7170 }
7271
7372 Token.Factory tokenFactory = (session == null) ? null
74- : session.getCluster().manager.metadata.tokenFactory();
73+ : session.getCluster().manager.metadata.tokenFactory();
7574
7675 // info can be null only for internal calls, but we don't page those. We assert
7776 // this explicitly because MultiPage implementation don't support info == null.
7877 assert r.metadata.pagingState == null || info != null;
7978 return r.metadata.pagingState == null
80- ? new SinglePage(columnDefs, tokenFactory, protocolVersion, r.data, info)
81- : new MultiPage(columnDefs, tokenFactory, protocolVersion, r.data, info, r.metadata.pagingState, session, statement);
79+ ? new SinglePage(columnDefs, tokenFactory, protocolVersion, r.data, info)
80+ : new MultiPage(columnDefs, tokenFactory, protocolVersion, r.data, info, r.metadata.pagingState, session, statement);
8281
8382 case SET_KEYSPACE:
8483 case SCHEMA_CHANGE:
@@ -98,7 +97,7 @@
9897
9998 private static ArrayBackedResultSet empty(ExecutionInfo info) {
10099 // We could pass the protocol version but we know we won't need it so passing a bogus value (null)
101- return new SinglePage(ColumnDefinitions.EMPTY, null, null, EMPTY_QUEUE, info);
100+ return new SinglePage(ColumnDefinitions.EMPTY, null, null, EMPTY_QUEUE, info);
102101 }
103102
104103 public ColumnDefinitions getColumnDefinitions() {
@@ -326,10 +325,10 @@
326325 try {
327326 switch (response.type) {
328327 case RESULT:
329- Responses.Result rm = (Responses.Result)response;
328+ Responses.Result rm = (Responses.Result) response;
330329 info = update(info, rm, MultiPage.this.session);
331330 if (rm.kind == Responses.Result.Kind.ROWS) {
332- Responses.Result.Rows rows = (Responses.Result.Rows)rm;
331+ Responses.Result.Rows rows = (Responses.Result.Rows) rm;
333332 if (rows.metadata.pagingState != null)
334333 info = info.withPagingState(rows.metadata.pagingState, protocolVersion).withStatement(statement);
335334 MultiPage.this.nextPages.offer(rows.data);
@@ -349,7 +348,7 @@
349348 future.set(null);
350349 break;
351350 case ERROR:
352- future.setException(((Responses.Error)response).asException(connection.address));
351+ future.setException(((Responses.Error) response).asException(connection.address));
353352 break;
354353 default:
355354 // This mean we have probably have a bad node, so defunct the connection
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java +3 −3
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.*;
20-
2118 import com.datastax.driver.core.exceptions.DriverInternalError;
2219
20+import java.nio.ByteBuffer;
21+import java.util.List;
22+
2323 /**
2424 * Implementation of a Row backed by an ArrayList.
2525 */
modified driver-core/src/main/java/com/datastax/driver/core/AsyncInitSession.java +2 −2
@@ -19,10 +19,10 @@
1919
2020 /**
2121 * A {@link Session} that can be initialized asynchronously.
22- *
22+ * <p/>
2323 * This interface exists only for backward compatibility reasons: {@link #initAsync()} should really be
2424 * defined by {@link Session}, but adding it after the fact would break binary compatibility.
25- *
25+ * <p/>
2626 * By default, all sessions returned by the driver implement this interface. The only way you would get
2727 * sessions that don't is if you use a custom {@link Cluster} subclass.
2828 */
modified driver-core/src/main/java/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.java +2 −2
@@ -20,11 +20,11 @@
2020 /**
2121 * A timestamp generator based on {@code System.currentTimeMillis()}, with an incrementing atomic counter
2222 * to generate the sub-millisecond part.
23- * <p>
23+ * <p/>
2424 * This implementation guarantees incrementing timestamps among all client threads, provided that no more than
2525 * 1000 are requested for a given clock tick (the exact granularity of of {@link System#currentTimeMillis()}
2626 * depends on the operating system).
27- * <p>
27+ * <p/>
2828 * If that rate is exceeded, a warning is logged and the timestamps don't increment anymore until the next clock
2929 * tick. If you consistently exceed that rate, consider using {@link ThreadLocalMonotonicTimestampGenerator}.
3030 */
modified driver-core/src/main/java/com/datastax/driver/core/AuthProvider.java +5 −5
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-
2018 import com.datastax.driver.core.exceptions.AuthenticationException;
2119
20+import java.net.InetSocketAddress;
21+
2222 /**
2323 * Provides {@link Authenticator} instances for use when connecting
2424 * to Cassandra nodes.
25- *
25+ * <p/>
2626 * See {@link PlainTextAuthProvider} for an implementation which uses SASL
2727 * PLAIN mechanism to authenticate using username/password strings
2828 */
@@ -30,13 +30,13 @@
3030
3131 /**
3232 * A provider that provides no authentication capability.
33- * <p>
33+ * <p/>
3434 * This is only useful as a placeholder when no authentication is to be used.
3535 */
3636 public static final AuthProvider NONE = new AuthProvider() {
3737 public Authenticator newAuthenticator(InetSocketAddress host) {
3838 throw new AuthenticationException(host,
39- String.format("Host %s requires authentication, but no authenticator found in Cluster configuration", host));
39+ String.format("Host %s requires authentication, but no authenticator found in Cluster configuration", host));
4040 }
4141 };
4242
modified driver-core/src/main/java/com/datastax/driver/core/Authenticator.java +17 −17
@@ -17,26 +17,26 @@
1717
1818 /**
1919 * Handles SASL authentication with Cassandra servers.
20- * <p>
20+ * <p/>
2121 * Each time a new connection is created and the server requires authentication,
2222 * a new instance of this class will be created by the corresponding
2323 * {@link AuthProvider} to handle that authentication. The lifecycle of that
2424 * new {@code Authenticator} will be:
2525 * <ol>
26- * <li>The {@code initialResponse} method will be called. The initial return
27- * value will be sent to the server to initiate the handshake.</li>
28- * <li>The server will respond to each client response by either issuing a
29- * challenge or indicating that the authentication is complete (successfully or not).
30- * If a new challenge is issued, the authenticator {@code evaluateChallenge}
31- * method will be called to produce a response that will be sent to the
32- * server. This challenge/response negotiation will continue until the server
33- * responds that authentication is successful (or an {@code AuthenticationException}
34- * is raised).
35- * </li>
36- * <li>When the server indicates that authentication is successful, the
37- * {@code onAuthenticationSuccess} method will be called with the last information
38- * that the server may optionally have sent.
39- * </li>
26+ * <li>The {@code initialResponse} method will be called. The initial return
27+ * value will be sent to the server to initiate the handshake.</li>
28+ * <li>The server will respond to each client response by either issuing a
29+ * challenge or indicating that the authentication is complete (successfully or not).
30+ * If a new challenge is issued, the authenticator {@code evaluateChallenge}
31+ * method will be called to produce a response that will be sent to the
32+ * server. This challenge/response negotiation will continue until the server
33+ * responds that authentication is successful (or an {@code AuthenticationException}
34+ * is raised).
35+ * </li>
36+ * <li>When the server indicates that authentication is successful, the
37+ * {@code onAuthenticationSuccess} method will be called with the last information
38+ * that the server may optionally have sent.
39+ * </li>
4040 * </ol>
4141 * The exact nature of the negotiation between client and server is specific
4242 * to the authentication mechanism configured server side.
@@ -66,8 +66,8 @@
6666 * optionally sent by the server.
6767 *
6868 * @param token the information sent by the server with the authentication
69- * successful message. This will be {@code null} if the server sends no
70- * particular information on authentication success.
69+ * successful message. This will be {@code null} if the server sends no
70+ * particular information on authentication success.
7171 */
7272 public void onAuthenticationSuccess(byte[] token);
7373 }
modified driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +19 −25
@@ -15,28 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.ArrayList;
20-import java.util.Arrays;
21-import java.util.Collection;
22-import java.util.Collections;
23-import java.util.List;
24-
18+import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
2519 import com.google.common.collect.ImmutableList;
2620
27-import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
21+import java.nio.ByteBuffer;
22+import java.util.*;
2823
2924 /**
3025 * A statement that groups a number of {@link Statement} so they get executed as
3126 * a batch.
32- * <p>
27+ * <p/>
3328 * Note: BatchStatement is not supported with the native protocol version 1: you
3429 * will get an {@link UnsupportedFeatureException} when submitting one if
3530 * version 1 of the protocol is in use (i.e. if you've force version 1 through
3631 * {@link Cluster.Builder#withProtocolVersion} or you use Cassandra 1.2). Note
3732 * however that you can still use <a href="http://cassandra.apache.org/doc/cql3/CQL.html#batchStmt">CQL Batch statements</a>
3833 * even with the protocol version 1.
39- * <p>
34+ * <p/>
4035 * Setting a BatchStatement's serial consistency level is only supported with the
4136 * native protocol version 3 or higher (see {@link #setSerialConsistencyLevel(ConsistencyLevel)}).
4237 */
@@ -64,7 +59,9 @@
6459 * operations and it can only contain these.
6560 */
6661 COUNTER
67- };
62+ }
63+
64+ ;
6865
6966 final Type batchType;
7067 private final List<Statement> statements = new ArrayList<Statement>();
@@ -89,14 +86,14 @@
8986 IdAndValues idAndVals = new IdAndValues(statements.size());
9087 for (Statement statement : statements) {
9188 if (statement instanceof RegularStatement) {
92- RegularStatement st = (RegularStatement)statement;
89+ RegularStatement st = (RegularStatement) statement;
9390 ByteBuffer[] vals = st.getValues(protocolVersion);
9491 idAndVals.ids.add(st.getQueryString());
9592 idAndVals.values.add(vals == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(vals));
9693 } else {
9794 // We handle BatchStatement in add() so ...
9895 assert statement instanceof BoundStatement;
99- BoundStatement st = (BoundStatement)statement;
96+ BoundStatement st = (BoundStatement) statement;
10097 idAndVals.ids.add(st.statement.getPreparedId().id);
10198 idAndVals.values.add(Arrays.asList(st.wrapper.values));
10299 }
@@ -106,18 +103,18 @@
106103
107104 /**
108105 * Adds a new statement to this batch.
109- * <p>
106+ * <p/>
110107 * Note that {@code statement} can be any {@code Statement}. It is allowed to mix
111108 * {@code RegularStatement} and {@code BoundStatement} in the same
112109 * {@code BatchStatement} in particular. Adding another {@code BatchStatement}
113110 * is also allowed for convenience and is equivalent to adding all the {@code Statement}
114111 * contained in that other {@code BatchStatement}.
115- * <p>
112+ * <p/>
116113 * When adding a {@code BoundStatement}, all of its values must be set, otherwise an
117114 * {@code IllegalStateException} will be thrown when submitting the batch statement.
118115 * See {@link BoundStatement} for more details, in particular how to handle {@code null}
119116 * values.
120- * <p>
117+ * <p/>
121118 * Please note that the options of the added Statement (all those defined directly by the
122119 * {@link Statement} class: consistency level, fetch size, tracing, ...) will be ignored
123120 * for the purpose of the execution of the Batch. Instead, the options used are the one
@@ -125,10 +122,9 @@
125122 *
126123 * @param statement the new statement to add.
127124 * @return this batch statement.
128- *
129125 * @throws IllegalStateException if adding the new statement means that this
130- * {@code BatchStatement} has more than 65536 statements (since this is the maximum number
131- * of statements for a BatchStatement allowed by the underlying protocol).
126+ * {@code BatchStatement} has more than 65536 statements (since this is the maximum number
127+ * of statements for a BatchStatement allowed by the underlying protocol).
132128 */
133129 public BatchStatement add(Statement statement) {
134130
@@ -136,7 +132,7 @@
136132 // easier to avoid endless loop if the use mistakenly pass a batch that depends on this
137133 // object (or this directly).
138134 if (statement instanceof BatchStatement) {
139- for (Statement subStatements : ((BatchStatement)statement).statements) {
135+ for (Statement subStatements : ((BatchStatement) statement).statements) {
140136 add(subStatements);
141137 }
142138 } else {
@@ -149,7 +145,7 @@
149145
150146 /**
151147 * Adds multiple statements to this batch.
152- * <p>
148+ * <p/>
153149 * This is a shortcut method that calls {@link #add} on all the statements
154150 * from {@code statements}.
155151 *
@@ -193,7 +189,7 @@
193189
194190 /**
195191 * Sets the serial consistency level for the query.
196- * <p>
192+ * <p/>
197193 * This is only supported with version 3 or higher of the native protocol. If you call
198194 * this method when version 2 is in use, you will get an {@link UnsupportedFeatureException}
199195 * when submitting the statement. With version 2, protocol batches with conditions
@@ -202,10 +198,8 @@
202198 *
203199 * @param serialConsistency the serial consistency level to set.
204200 * @return this {@code Statement} object.
205- *
206201 * @throws IllegalArgumentException if {@code serialConsistency} is not one of
207- * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
208- *
202+ * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
209203 * @see Statement#setSerialConsistencyLevel(ConsistencyLevel)
210204 */
211205 @Override
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +198 −242
@@ -15,29 +15,28 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.google.common.reflect.TypeToken;
20+
1821 import java.math.BigDecimal;
1922 import java.math.BigInteger;
2023 import java.net.InetAddress;
2124 import java.nio.ByteBuffer;
2225 import java.util.*;
2326
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
27-
2827 /**
2928 * A prepared statement with values bound to the bind variables.
30- * <p>
29+ * <p/>
3130 * Once values has been provided for the variables of the {@link PreparedStatement}
3231 * it has been created from, such BoundStatement can be executed (through
3332 * {@link Session#execute(Statement)}).
34- * <p>
33+ * <p/>
3534 * The values of a BoundStatement can be set by either index or name. When
3635 * setting them by name, names follow the case insensitivity rules explained in
3736 * {@link ColumnDefinitions} but with the difference that if multiple bind
3837 * variables have the same name, setting that name will set <b>all</b> the
3938 * variables for that name.
40- * <p>
39+ * <p/>
4140 * All the variables of the statement must be bound. If you don't explicitly
4241 * set a value for a variable, an {@code IllegalStateException} will be
4342 * thrown when submitting the statement. If you want to set a variable to
@@ -57,6 +56,7 @@
5756 /**
5857 * Creates a new {@code BoundStatement} from the provided prepared
5958 * statement.
59+ *
6060 * @param statement the prepared statement from which to create a {@code BoundStatement}.
6161 */
6262 public BoundStatement(PreparedStatement statement) {
@@ -96,7 +96,6 @@
9696 *
9797 * @param i the index of the variable to check.
9898 * @return whether the {@code i}th variable has been bound.
99- *
10099 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
101100 */
102101 public boolean isSet(int i) {
@@ -110,9 +109,8 @@
110109 * @param name the name of the variable to check.
111110 * @return whether the first occurrence of variable {@code name} has been
112111 * bound to a non-null value.
113- *
114112 * @throws IllegalArgumentException if {@code name} is not a prepared
115- * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
113+ * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
116114 */
117115 public boolean isSet(String name) {
118116 return wrapper.getValue(wrapper.getIndexOf(name)) != UNSET;
@@ -120,33 +118,31 @@
120118
121119 /**
122120 * Bound values to the variables of this statement.
123- *
121+ * <p/>
124122 * This is a convenience method to bind all the variables of the
125123 * {@code BoundStatement} in one call.
126124 *
127125 * @param values the values to bind to the variables of the newly created
128- * BoundStatement. The first element of {@code values} will be bound to the
129- * first bind variable, etc. It is legal to provide fewer values than the
130- * statement has bound variables. In that case, the remaining variable need
131- * to be bound before execution. If more values than variables are provided
132- * however, an IllegalArgumentException wil be raised.
126+ * BoundStatement. The first element of {@code values} will be bound to the
127+ * first bind variable, etc. It is legal to provide fewer values than the
128+ * statement has bound variables. In that case, the remaining variable need
129+ * to be bound before execution. If more values than variables are provided
130+ * however, an IllegalArgumentException wil be raised.
133131 * @return this bound statement.
134- *
135132 * @throws IllegalArgumentException if more {@code values} are provided
136- * than there is of bound variables in this statement.
137- * @throws InvalidTypeException if any of the provided value is not of
138- * correct type to be bound to the corresponding bind variable.
139- * @throws NullPointerException if one of {@code values} is a collection
140- * (List, Set or Map) containing a null value. Nulls are not supported in
141- * collections by CQL.
133+ * than there is of bound variables in this statement.
134+ * @throws InvalidTypeException if any of the provided value is not of
135+ * correct type to be bound to the corresponding bind variable.
136+ * @throws NullPointerException if one of {@code values} is a collection
137+ * (List, Set or Map) containing a null value. Nulls are not supported in
138+ * collections by CQL.
142139 */
143140 public BoundStatement bind(Object... values) {
144141
145142 if (values.length > statement.getVariables().size())
146143 throw new IllegalArgumentException(String.format("Prepared statement has only %d variables, %d values provided", statement.getVariables().size(), values.length));
147144
148- for (int i = 0; i < values.length; i++)
149- {
145+ for (int i = 0; i < values.length; i++) {
150146 Object toSet = values[i];
151147
152148 if (toSet == null) {
@@ -160,7 +156,7 @@
160156 if (!(toSet instanceof List))
161157 throw new InvalidTypeException(String.format("Invalid type for value %d, column is a list but %s provided", i, toSet.getClass()));
162158
163- List<?> l = (List<?>)toSet;
159+ List<?> l = (List<?>) toSet;
164160 // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
165161 if (!l.isEmpty()) {
166162 // Ugly? Yes
@@ -174,7 +170,7 @@
174170 if (!(toSet instanceof Set))
175171 throw new InvalidTypeException(String.format("Invalid type for value %d, column is a set but %s provided", i, toSet.getClass()));
176172
177- Set<?> s = (Set<?>)toSet;
173+ Set<?> s = (Set<?>) toSet;
178174 // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
179175 if (!s.isEmpty()) {
180176 // Ugly? Yes
@@ -188,7 +184,7 @@
188184 if (!(toSet instanceof Map))
189185 throw new InvalidTypeException(String.format("Invalid type for value %d, column is a map but %s provided", i, toSet.getClass()));
190186
191- Map<?, ?> m = (Map<?, ?>)toSet;
187+ Map<?, ?> m = (Map<?, ?>) toSet;
192188 // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
193189 if (!m.isEmpty()) {
194190 // Ugly? Yes
@@ -204,7 +200,7 @@
204200 break;
205201 default:
206202 if (toSet instanceof Token)
207- toSet = ((Token)toSet).getValue();
203+ toSet = ((Token) toSet).getValue();
208204
209205 Class<?> providedClass = toSet.getClass();
210206 Class<?> expectedClass = columnType.getName().javaType;
@@ -219,14 +215,13 @@
219215
220216 /**
221217 * Sets the routing key for this bound statement.
222- * <p>
218+ * <p/>
223219 * This is useful when the routing key can neither be set on the {@code PreparedStatement} this bound statement
224220 * was built from, nor automatically computed from bound variables. In particular, this is the case if the
225221 * partition key is composite and only some of its components are bound.
226222 *
227223 * @param routingKey the raw (binary) value to use as routing key.
228224 * @return this {@code BoundStatement} object.
229- *
230225 * @see BoundStatement#getRoutingKey
231226 */
232227 public BoundStatement setRoutingKey(ByteBuffer routingKey) {
@@ -236,7 +231,7 @@
236231
237232 /**
238233 * The routing key for this bound query.
239- * <p>
234+ * <p/>
240235 * This method will return a non-{@code null} value if either of the following occur:
241236 * <ul>
242237 * <li>The routing key has been set directly through {@link BoundStatement#setRoutingKey}.</li>
@@ -246,8 +241,8 @@
246241 * key will then be built using the values provided for these partition key columns.</li>
247242 * </ul>
248243 * Otherwise, {@code null} is returned.
249- * <p>
250- *
244+ * <p/>
245+ * <p/>
251246 * Note that if the routing key has been set through {@link BoundStatement#setRoutingKey}, then that takes
252247 * precedence. If the routing key has been set through {@link PreparedStatement#setRoutingKey} then that is used
253248 * next. If neither of those are set then it is computed.
@@ -284,7 +279,7 @@
284279
285280 /**
286281 * Returns the keyspace this query operates on.
287- * <p>
282+ * <p/>
288283 * This method will always return a non-{@code null} value (unless the statement
289284 * has no variables, but you should avoid prepared statement in the first in that
290285 * case). The keyspace returned will be the one corresponding to the first
@@ -306,9 +301,8 @@
306301 * @param i the index of the variable to set.
307302 * @param v the value to set.
308303 * @return this BoundStatement.
309- *
310304 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
311- * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
305+ * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
312306 */
313307 public BoundStatement setBool(int i, boolean v) {
314308 return wrapper.setBool(i, v);
@@ -319,13 +313,12 @@
319313 * provided boolean.
320314 *
321315 * @param name the name of the variable to set; if multiple variables
322- * {@code name} are prepared, all of them are set.
323- * @param v the value to set.
316+ * {@code name} are prepared, all of them are set.
317+ * @param v the value to set.
324318 * @return this BoundStatement.
325- *
326319 * @throws IllegalArgumentException if {@code name} is not a prepared
327- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
328- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type BOOLEAN.
320+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
321+ * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type BOOLEAN.
329322 */
330323 public BoundStatement setBool(String name, boolean v) {
331324 return wrapper.setBool(name, v);
@@ -337,9 +330,8 @@
337330 * @param i the index of the variable to set.
338331 * @param v the value to set.
339332 * @return this BoundStatement.
340- *
341333 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
342- * @throws InvalidTypeException if column {@code i} is not of type INT.
334+ * @throws InvalidTypeException if column {@code i} is not of type INT.
343335 */
344336 public BoundStatement setInt(int i, int v) {
345337 return wrapper.setInt(i, v);
@@ -350,13 +342,12 @@
350342 * provided integer.
351343 *
352344 * @param name the name of the variable to set; if multiple variables
353- * {@code name} are prepared, all of them are set.
354- * @param v the value to set.
345+ * {@code name} are prepared, all of them are set.
346+ * @param v the value to set.
355347 * @return this BoundStatement.
356- *
357348 * @throws IllegalArgumentException if {@code name} is not a prepared
358- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
359- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type INT.
349+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
350+ * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type INT.
360351 */
361352 public BoundStatement setInt(String name, int v) {
362353 return wrapper.setInt(name, v);
@@ -368,9 +359,8 @@
368359 * @param i the index of the variable to set.
369360 * @param v the value to set.
370361 * @return this BoundStatement.
371- *
372362 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
373- * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
363+ * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
374364 */
375365 public BoundStatement setLong(int i, long v) {
376366 return wrapper.setLong(i, v);
@@ -381,14 +371,13 @@
381371 * provided long.
382372 *
383373 * @param name the name of the variable to set; if multiple variables
384- * {@code name} are prepared, all of them are set.
385- * @param v the value to set.
374+ * {@code name} are prepared, all of them are set.
375+ * @param v the value to set.
386376 * @return this BoundStatement.
387- *
388377 * @throws IllegalArgumentException if {@code name} is not a prepared
389- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
390- * @throws InvalidTypeException if (any occurrence of) {@code name} is
391- * not of type BIGINT or COUNTER.
378+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
379+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
380+ * not of type BIGINT or COUNTER.
392381 */
393382 public BoundStatement setLong(String name, long v) {
394383 return wrapper.setLong(name, v);
@@ -400,9 +389,8 @@
400389 * @param i the index of the variable to set.
401390 * @param v the value to set.
402391 * @return this BoundStatement.
403- *
404392 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
405- * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
393+ * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
406394 */
407395 public BoundStatement setDate(int i, Date v) {
408396 return wrapper.setDate(i, v);
@@ -413,14 +401,13 @@
413401 * provided date.
414402 *
415403 * @param name the name of the variable to set; if multiple variables
416- * {@code name} are prepared, all of them are set.
417- * @param v the value to set.
404+ * {@code name} are prepared, all of them are set.
405+ * @param v the value to set.
418406 * @return this BoundStatement.
419- *
420407 * @throws IllegalArgumentException if {@code name} is not a prepared
421- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
422- * @throws InvalidTypeException if (any occurrence of) {@code name} is
423- * not of type TIMESTAMP.
408+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
409+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
410+ * not of type TIMESTAMP.
424411 */
425412 public BoundStatement setDate(String name, Date v) {
426413 return wrapper.setDate(name, v);
@@ -432,9 +419,8 @@
432419 * @param i the index of the variable to set.
433420 * @param v the value to set.
434421 * @return this BoundStatement.
435- *
436422 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
437- * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
423+ * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
438424 */
439425 public BoundStatement setFloat(int i, float v) {
440426 return wrapper.setFloat(i, v);
@@ -445,14 +431,13 @@
445431 * provided float.
446432 *
447433 * @param name the name of the variable to set; if multiple variables
448- * {@code name} are prepared, all of them are set.
449- * @param v the value to set.
434+ * {@code name} are prepared, all of them are set.
435+ * @param v the value to set.
450436 * @return this BoundStatement.
451- *
452437 * @throws IllegalArgumentException if {@code name} is not a prepared
453- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
454- * @throws InvalidTypeException if (any occurrence of) {@code name} is
455- * not of type FLOAT.
438+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
439+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
440+ * not of type FLOAT.
456441 */
457442 public BoundStatement setFloat(String name, float v) {
458443 return wrapper.setFloat(name, v);
@@ -464,9 +449,8 @@
464449 * @param i the index of the variable to set.
465450 * @param v the value to set.
466451 * @return this BoundStatement.
467- *
468452 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
469- * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
453+ * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
470454 */
471455 public BoundStatement setDouble(int i, double v) {
472456 return wrapper.setDouble(i, v);
@@ -477,14 +461,13 @@
477461 * provided double.
478462 *
479463 * @param name the name of the variable to set; if multiple variables
480- * {@code name} are prepared, all of them are set.
481- * @param v the value to set.
464+ * {@code name} are prepared, all of them are set.
465+ * @param v the value to set.
482466 * @return this BoundStatement.
483- *
484467 * @throws IllegalArgumentException if {@code name} is not a prepared
485- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
486- * @throws InvalidTypeException if (any occurrence of) {@code name} is
487- * not of type DOUBLE.
468+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
469+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
470+ * not of type DOUBLE.
488471 */
489472 public BoundStatement setDouble(String name, double v) {
490473 return wrapper.setDouble(name, v);
@@ -496,10 +479,9 @@
496479 * @param i the index of the variable to set.
497480 * @param v the value to set.
498481 * @return this BoundStatement.
499- *
500482 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
501- * @throws InvalidTypeException if column {@code i} is of neither of the
502- * following types: VARCHAR, TEXT or ASCII.
483+ * @throws InvalidTypeException if column {@code i} is of neither of the
484+ * following types: VARCHAR, TEXT or ASCII.
503485 */
504486 public BoundStatement setString(int i, String v) {
505487 return wrapper.setString(i, v);
@@ -510,14 +492,13 @@
510492 * provided string.
511493 *
512494 * @param name the name of the variable to set; if multiple variables
513- * {@code name} are prepared, all of them are set.
514- * @param v the value to set.
495+ * {@code name} are prepared, all of them are set.
496+ * @param v the value to set.
515497 * @return this BoundStatement.
516- *
517498 * @throws IllegalArgumentException if {@code name} is not a prepared
518- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
519- * @throws InvalidTypeException if (any occurrence of) {@code name} is
520- * of neither of the following types: VARCHAR, TEXT or ASCII.
499+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
500+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
501+ * of neither of the following types: VARCHAR, TEXT or ASCII.
521502 */
522503 public BoundStatement setString(String name, String v) {
523504 return wrapper.setString(name, v);
@@ -525,7 +506,7 @@
525506
526507 /**
527508 * Sets the {@code i}th value to the provided byte buffer.
528- *
509+ * <p/>
529510 * This method validate that the type of the column set is BLOB. If you
530511 * want to insert manually serialized data into columns of another type,
531512 * use {@link #setBytesUnsafe} instead.
@@ -533,9 +514,8 @@
533514 * @param i the index of the variable to set.
534515 * @param v the value to set.
535516 * @return this BoundStatement.
536- *
537517 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
538- * @throws InvalidTypeException if column {@code i} is not of type BLOB.
518+ * @throws InvalidTypeException if column {@code i} is not of type BLOB.
539519 */
540520 public BoundStatement setBytes(int i, ByteBuffer v) {
541521 return wrapper.setBytes(i, v);
@@ -544,19 +524,18 @@
544524 /**
545525 * Sets the value for (all occurrences of) variable {@code name} to the
546526 * provided byte buffer.
547- *
527+ * <p/>
548528 * This method validate that the type of the column set is BLOB. If you
549529 * want to insert manually serialized data into columns of another type,
550530 * use {@link #setBytesUnsafe} instead.
551531 *
552532 * @param name the name of the variable to set; if multiple variables
553- * {@code name} are prepared, all of them are set.
554- * @param v the value to set.
533+ * {@code name} are prepared, all of them are set.
534+ * @param v the value to set.
555535 * @return this BoundStatement.
556- *
557536 * @throws IllegalArgumentException if {@code name} is not a prepared
558- * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
559- * @throws InvalidTypeException if (any occurrence of) {@code name} is not of type BLOB.
537+ * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
538+ * @throws InvalidTypeException if (any occurrence of) {@code name} is not of type BLOB.
560539 */
561540 public BoundStatement setBytes(String name, ByteBuffer v) {
562541 return wrapper.setBytes(name, v);
@@ -564,7 +543,7 @@
564543
565544 /**
566545 * Sets the {@code i}th value to the provided byte buffer.
567- *
546+ * <p/>
568547 * Contrary to {@link #setBytes}, this method does not check the
569548 * type of the column set. If you insert data that is not compatible with
570549 * the type of the column, you will get an {@code InvalidQueryException} at
@@ -573,7 +552,6 @@
573552 * @param i the index of the variable to set.
574553 * @param v the value to set.
575554 * @return this BoundStatement.
576- *
577555 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
578556 */
579557 public BoundStatement setBytesUnsafe(int i, ByteBuffer v) {
@@ -583,19 +561,18 @@
583561 /**
584562 * Sets the value for (all occurrences of) variable {@code name} to the
585563 * provided byte buffer.
586- *
564+ * <p/>
587565 * Contrary to {@link #setBytes}, this method does not check the
588566 * type of the column set. If you insert data that is not compatible with
589567 * the type of the column, you will get an {@code InvalidQueryException} at
590568 * execute time.
591569 *
592570 * @param name the name of the variable to set; if multiple variables
593- * {@code name} are prepared, all of them are set.
594- * @param v the value to set.
571+ * {@code name} are prepared, all of them are set.
572+ * @param v the value to set.
595573 * @return this BoundStatement.
596- *
597574 * @throws IllegalArgumentException if {@code name} is not a prepared
598- * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
575+ * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
599576 */
600577 public BoundStatement setBytesUnsafe(String name, ByteBuffer v) {
601578 return wrapper.setBytesUnsafe(name, v);
@@ -607,9 +584,8 @@
607584 * @param i the index of the variable to set.
608585 * @param v the value to set.
609586 * @return this BoundStatement.
610- *
611587 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
612- * @throws InvalidTypeException if column {@code i} is not of type VARINT.
588+ * @throws InvalidTypeException if column {@code i} is not of type VARINT.
613589 */
614590 public BoundStatement setVarint(int i, BigInteger v) {
615591 return wrapper.setVarint(i, v);
@@ -620,14 +596,13 @@
620596 * provided big integer.
621597 *
622598 * @param name the name of the variable to set; if multiple variables
623- * {@code name} are prepared, all of them are set.
624- * @param v the value to set.
599+ * {@code name} are prepared, all of them are set.
600+ * @param v the value to set.
625601 * @return this BoundStatement.
626- *
627602 * @throws IllegalArgumentException if {@code name} is not a prepared
628- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
629- * @throws InvalidTypeException if (any occurrence of) {@code name} is
630- * not of type VARINT.
603+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
604+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
605+ * not of type VARINT.
631606 */
632607 public BoundStatement setVarint(String name, BigInteger v) {
633608 return wrapper.setVarint(name, v);
@@ -639,9 +614,8 @@
639614 * @param i the index of the variable to set.
640615 * @param v the value to set.
641616 * @return this BoundStatement.
642- *
643617 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
644- * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
618+ * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
645619 */
646620 public BoundStatement setDecimal(int i, BigDecimal v) {
647621 return wrapper.setDecimal(i, v);
@@ -652,14 +626,13 @@
652626 * provided big decimal.
653627 *
654628 * @param name the name of the variable to set; if multiple variables
655- * {@code name} are prepared, all of them are set.
656- * @param v the value to set.
629+ * {@code name} are prepared, all of them are set.
630+ * @param v the value to set.
657631 * @return this BoundStatement.
658- *
659632 * @throws IllegalArgumentException if {@code name} is not a prepared
660- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
661- * @throws InvalidTypeException if (any occurrence of) {@code name} is
662- * not of type DECIMAL.
633+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
634+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
635+ * not of type DECIMAL.
663636 */
664637 public BoundStatement setDecimal(String name, BigDecimal v) {
665638 return wrapper.setDecimal(name, v);
@@ -671,11 +644,10 @@
671644 * @param i the index of the variable to set.
672645 * @param v the value to set.
673646 * @return this BoundStatement.
674- *
675647 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
676- * @throws InvalidTypeException if column {@code i} is not of type UUID or
677- * TIMEUUID, or if column {@code i} is of type TIMEUUID but {@code v} is
678- * not a type 1 UUID.
648+ * @throws InvalidTypeException if column {@code i} is not of type UUID or
649+ * TIMEUUID, or if column {@code i} is of type TIMEUUID but {@code v} is
650+ * not a type 1 UUID.
679651 */
680652 public BoundStatement setUUID(int i, UUID v) {
681653 return wrapper.setUUID(i, v);
@@ -686,15 +658,14 @@
686658 * provided UUID.
687659 *
688660 * @param name the name of the variable to set; if multiple variables
689- * {@code name} are prepared, all of them are set.
690- * @param v the value to set.
661+ * {@code name} are prepared, all of them are set.
662+ * @param v the value to set.
691663 * @return this BoundStatement.
692- *
693664 * @throws IllegalArgumentException if {@code name} is not a prepared
694- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
695- * @throws InvalidTypeException if (any occurrence of) {@code name} is
696- * not of type UUID or TIMEUUID, or if column {@code name} is of type
697- * TIMEUUID but {@code v} is not a type 1 UUID.
665+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
666+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
667+ * not of type UUID or TIMEUUID, or if column {@code name} is of type
668+ * TIMEUUID but {@code v} is not a type 1 UUID.
698669 */
699670 public BoundStatement setUUID(String name, UUID v) {
700671 return wrapper.setUUID(name, v);
@@ -706,9 +677,8 @@
706677 * @param i the index of the variable to set.
707678 * @param v the value to set.
708679 * @return this BoundStatement.
709- *
710680 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
711- * @throws InvalidTypeException if column {@code i} is not of type INET.
681+ * @throws InvalidTypeException if column {@code i} is not of type INET.
712682 */
713683 public BoundStatement setInet(int i, InetAddress v) {
714684 return wrapper.setInet(i, v);
@@ -719,14 +689,13 @@
719689 * provided inet address.
720690 *
721691 * @param name the name of the variable to set; if multiple variables
722- * {@code name} are prepared, all of them are set.
723- * @param v the value to set.
692+ * {@code name} are prepared, all of them are set.
693+ * @param v the value to set.
724694 * @return this BoundStatement.
725- *
726695 * @throws IllegalArgumentException if {@code name} is not a prepared
727- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
728- * @throws InvalidTypeException if (any occurrence of) {@code name} is
729- * not of type INET.
696+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
697+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
698+ * not of type INET.
730699 */
731700 public BoundStatement setInet(String name, InetAddress v) {
732701 return wrapper.setInet(name, v);
@@ -734,16 +703,15 @@
734703
735704 /**
736705 * Sets the {@code i}th value to the provided {@link Token}.
737- * <p>
706+ * <p/>
738707 * {@link #setPartitionKeyToken(Token)} should generally be preferred if you
739708 * have a single token variable.
740709 *
741710 * @param i the index of the variable to set.
742711 * @param v the value to set.
743712 * @return this BoundStatement.
744- *
745713 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
746- * @throws InvalidTypeException if column {@code i} is not of the type of the token's value.
714+ * @throws InvalidTypeException if column {@code i} is not of the type of the token's value.
747715 */
748716 public BoundStatement setToken(int i, Token v) {
749717 return wrapper.setToken(i, v);
@@ -752,10 +720,10 @@
752720 /**
753721 * Sets the value for (all occurrences of) variable {@code name} to the
754722 * provided token.
755- * <p>
723+ * <p/>
756724 * {@link #setPartitionKeyToken(Token)} should generally be preferred if you
757725 * have a single token variable.
758- * <p>
726+ * <p/>
759727 * If you have multiple token variables, use positional binding ({@link #setToken(int, Token)},
760728 * or named bind markers:
761729 * <pre>
@@ -766,14 +734,13 @@
766734 * </pre>
767735 *
768736 * @param name the name of the variable to set; if multiple variables
769- * {@code name} are prepared, all of them are set.
770- * @param v the value to set.
737+ * {@code name} are prepared, all of them are set.
738+ * @param v the value to set.
771739 * @return this BoundStatement.
772- *
773740 * @throws IllegalArgumentException if {@code name} is not a prepared
774- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
775- * @throws InvalidTypeException if (any occurrence of) {@code name} is
776- * not of the type of the token's value.
741+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
742+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
743+ * not of the type of the token's value.
777744 */
778745 public BoundStatement setToken(String name, Token v) {
779746 return wrapper.setToken(name, v);
@@ -783,7 +750,7 @@
783750 * Sets the value for (all occurrences of) variable "{@code partition key token}"
784751 * to the provided token (this is the name generated by Cassandra for markers
785752 * corresponding to a {@code token(...)} call).
786- * <p>
753+ * <p/>
787754 * This method is a shorthand for statements with a single token variable:
788755 * <pre>
789756 * {@code
@@ -803,11 +770,10 @@
803770 *
804771 * @param v the value to set.
805772 * @return this BoundStatement.
806- *
807773 * @throws IllegalArgumentException if {@code name} is not a prepared
808- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
809- * @throws InvalidTypeException if (any occurrence of) {@code name} is
810- * not of the type of the token's value.
774+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
775+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
776+ * not of the type of the token's value.
811777 */
812778 public BoundStatement setPartitionKeyToken(Token v) {
813779 return setToken("partition key token", v);
@@ -815,20 +781,19 @@
815781
816782 /**
817783 * Sets the {@code i}th value to the provided list.
818- * <p>
784+ * <p/>
819785 * Please note that {@code null} values are not supported inside collection by CQL.
820786 *
821787 * @param <T> the type of the elements of the list to set.
822- * @param i the index of the variable to set.
823- * @param v the value to set.
788+ * @param i the index of the variable to set.
789+ * @param v the value to set.
824790 * @return this BoundStatement.
825- *
826791 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
827- * @throws InvalidTypeException if column {@code i} is not a list type or
828- * if the elements of {@code v} are not of the type of the elements of
829- * column {@code i}.
830- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
831- * by CQL.
792+ * @throws InvalidTypeException if column {@code i} is not a list type or
793+ * if the elements of {@code v} are not of the type of the elements of
794+ * column {@code i}.
795+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
796+ * by CQL.
832797 */
833798 public <T> BoundStatement setList(int i, List<T> v) {
834799 return wrapper.setList(i, v);
@@ -837,22 +802,21 @@
837802 /**
838803 * Sets the value for (all occurrences of) variable {@code name} to the
839804 * provided list.
840- * <p>
805+ * <p/>
841806 * Please note that {@code null} values are not supported inside collection by CQL.
842807 *
843- * @param <T> the type of the elements of the list to set.
808+ * @param <T> the type of the elements of the list to set.
844809 * @param name the name of the variable to set; if multiple variables
845- * {@code name} are prepared, all of them are set.
846- * @param v the value to set.
810+ * {@code name} are prepared, all of them are set.
811+ * @param v the value to set.
847812 * @return this BoundStatement.
848- *
849813 * @throws IllegalArgumentException if {@code name} is not a prepared
850- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
851- * @throws InvalidTypeException if (any occurrence of) {@code name} is
852- * not a list type or if the elements of {@code v} are not of the type of
853- * the elements of column {@code name}.
854- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
855- * by CQL.
814+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
815+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
816+ * not a list type or if the elements of {@code v} are not of the type of
817+ * the elements of column {@code name}.
818+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
819+ * by CQL.
856820 */
857821 public <T> BoundStatement setList(String name, List<T> v) {
858822 return wrapper.setList(name, v);
@@ -860,21 +824,20 @@
860824
861825 /**
862826 * Sets the {@code i}th value to the provided map.
863- * <p>
827+ * <p/>
864828 * Please note that {@code null} values are not supported inside collection by CQL.
865829 *
866830 * @param <K> the type of the keys for the map to set.
867831 * @param <V> the type of the values for the map to set.
868- * @param i the index of the variable to set.
869- * @param v the value to set.
832+ * @param i the index of the variable to set.
833+ * @param v the value to set.
870834 * @return this BoundStatement.
871- *
872835 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
873- * @throws InvalidTypeException if column {@code i} is not a map type or
874- * if the elements (keys or values) of {@code v} are not of the type of the
875- * elements of column {@code i}.
876- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
877- * by CQL.
836+ * @throws InvalidTypeException if column {@code i} is not a map type or
837+ * if the elements (keys or values) of {@code v} are not of the type of the
838+ * elements of column {@code i}.
839+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
840+ * by CQL.
878841 */
879842 public <K, V> BoundStatement setMap(int i, Map<K, V> v) {
880843 return wrapper.setMap(i, v);
@@ -883,23 +846,22 @@
883846 /**
884847 * Sets the value for (all occurrences of) variable {@code name} to the
885848 * provided map.
886- * <p>
849+ * <p/>
887850 * Please note that {@code null} values are not supported inside collection by CQL.
888851 *
889- * @param <K> the type of the keys for the map to set.
890- * @param <V> the type of the values for the map to set.
852+ * @param <K> the type of the keys for the map to set.
853+ * @param <V> the type of the values for the map to set.
891854 * @param name the name of the variable to set; if multiple variables
892- * {@code name} are prepared, all of them are set.
893- * @param v the value to set.
855+ * {@code name} are prepared, all of them are set.
856+ * @param v the value to set.
894857 * @return this BoundStatement.
895- *
896858 * @throws IllegalArgumentException if {@code name} is not a prepared
897- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
898- * @throws InvalidTypeException if (any occurrence of) {@code name} is
899- * not a map type or if the elements (keys or values) of {@code v} are not of
900- * the type of the elements of column {@code name}.
901- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
902- * by CQL.
859+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
860+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
861+ * not a map type or if the elements (keys or values) of {@code v} are not of
862+ * the type of the elements of column {@code name}.
863+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
864+ * by CQL.
903865 */
904866 public <K, V> BoundStatement setMap(String name, Map<K, V> v) {
905867 return wrapper.setMap(name, v);
@@ -907,20 +869,19 @@
907869
908870 /**
909871 * Sets the {@code i}th value to the provided set.
910- * <p>
872+ * <p/>
911873 * Please note that {@code null} values are not supported inside collection by CQL.
912874 *
913875 * @param <T> the type of the elements of the set to set.
914- * @param i the index of the variable to set.
915- * @param v the value to set.
876+ * @param i the index of the variable to set.
877+ * @param v the value to set.
916878 * @return this BoundStatement.
917- *
918879 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
919- * @throws InvalidTypeException if column {@code i} is not a set type or
920- * if the elements of {@code v} are not of the type of the elements of
921- * column {@code i}.
922- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
923- * by CQL.
880+ * @throws InvalidTypeException if column {@code i} is not a set type or
881+ * if the elements of {@code v} are not of the type of the elements of
882+ * column {@code i}.
883+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
884+ * by CQL.
924885 */
925886 public <T> BoundStatement setSet(int i, Set<T> v) {
926887 return wrapper.setSet(i, v);
@@ -929,22 +890,21 @@
929890 /**
930891 * Sets the value for (all occurrences of) variable {@code name} to the
931892 * provided set.
932- * <p>
893+ * <p/>
933894 * Please note that {@code null} values are not supported inside collection by CQL.
934895 *
935- * @param <T> the type of the elements of the set to set.
896+ * @param <T> the type of the elements of the set to set.
936897 * @param name the name of the variable to set; if multiple variables
937- * {@code name} are prepared, all of them are set.
938- * @param v the value to set.
898+ * {@code name} are prepared, all of them are set.
899+ * @param v the value to set.
939900 * @return this BoundStatement.
940- *
941901 * @throws IllegalArgumentException if {@code name} is not a prepared
942- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
943- * @throws InvalidTypeException if (any occurrence of) {@code name} is
944- * not a map type or if the elements of {@code v} are not of the type of
945- * the elements of column {@code name}.
946- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
947- * by CQL.
902+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
903+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
904+ * not a map type or if the elements of {@code v} are not of the type of
905+ * the elements of column {@code name}.
906+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
907+ * by CQL.
948908 */
949909 public <T> BoundStatement setSet(String name, Set<T> v) {
950910 return wrapper.setSet(name, v);
@@ -956,10 +916,9 @@
956916 * @param i the index of the value to set.
957917 * @param v the value to set.
958918 * @return this BoundStatement .
959- *
960919 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this BoundStatement.
961- * @throws InvalidTypeException if value {@code i} is not a UDT value or if its definition
962- * does not correspond to the one of {@code v}.
920+ * @throws InvalidTypeException if value {@code i} is not a UDT value or if its definition
921+ * does not correspond to the one of {@code v}.
963922 */
964923 public BoundStatement setUDTValue(int i, UDTValue v) {
965924 return wrapper.setUDTValue(i, v);
@@ -970,14 +929,13 @@
970929 * provided UDT value.
971930 *
972931 * @param name the name of the value to set; if {@code name} is present multiple
973- * times, all its values are set.
974- * @param v the value to set.
932+ * times, all its values are set.
933+ * @param v the value to set.
975934 * @return this BoundStatement.
976- *
977935 * @throws IllegalArgumentException if {@code name} is not a valid name for this BoundStatement.
978- * @throws InvalidTypeException if (any occurrence of) {@code name} is
979- * not a UDT value or if the definition of column {@code name} does not correspond to
980- * the one of {@code v}.
936+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
937+ * not a UDT value or if the definition of column {@code name} does not correspond to
938+ * the one of {@code v}.
981939 */
982940 public BoundStatement setUDTValue(String name, UDTValue v) {
983941 return wrapper.setUDTValue(name, v);
@@ -989,10 +947,9 @@
989947 * @param i the index of the value to set.
990948 * @param v the value to set.
991949 * @return this BoundStatement.
992- *
993950 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this BoundStatement.
994- * @throws InvalidTypeException if value {@code i} is not a tuple value or if its types
995- * do not correspond to the ones of {@code v}.
951+ * @throws InvalidTypeException if value {@code i} is not a tuple value or if its types
952+ * do not correspond to the ones of {@code v}.
996953 */
997954 public BoundStatement setTupleValue(int i, TupleValue v) {
998955 return wrapper.setTupleValue(i, v);
@@ -1003,14 +960,13 @@
1003960 * provided tuple value.
1004961 *
1005962 * @param name the name of the value to set; if {@code name} is present multiple
1006- * times, all its values are set.
1007- * @param v the value to set.
963+ * times, all its values are set.
964+ * @param v the value to set.
1008965 * @return this BoundStatement.
1009- *
1010966 * @throws IllegalArgumentException if {@code name} is not a valid name for this BoundStatement.
1011- * @throws InvalidTypeException if (any occurrence of) {@code name} is
1012- * not a tuple value or if the types of column {@code name} do not correspond to
1013- * the ones of {@code v}.
967+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
968+ * not a tuple value or if the types of column {@code name} do not correspond to
969+ * the ones of {@code v}.
1014970 */
1015971 public BoundStatement setTupleValue(String name, TupleValue v) {
1016972 return wrapper.setTupleValue(name, v);
@@ -1018,7 +974,7 @@
1018974
1019975 /**
1020976 * Sets the {@code i}th value to {@code null}.
1021- * <p>
977+ * <p/>
1022978 * This is mainly intended for CQL types which map to native Java types.
1023979 *
1024980 * @param i the index of the value to set.
@@ -1031,11 +987,11 @@
1031987
1032988 /**
1033989 * Sets the value for (all occurrences of) variable {@code name} to {@code null}.
1034- * <p>
990+ * <p/>
1035991 * This is mainly intended for CQL types which map to native Java types.
1036992 *
1037993 * @param name the name of the value to set; if {@code name} is present multiple
1038- * times, all its values are set.
994+ * times, all its values are set.
1039995 * @return this object.
1040996 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
1041997 */
@@ -1387,10 +1343,10 @@
13871343 void ensureAllSet() {
13881344 int index = 0;
13891345 for (ByteBuffer value : wrapper.values) {
1390- if (value == BoundStatement.UNSET)
1346+ if (value == BoundStatement.UNSET)
13911347 throw new IllegalStateException("Unset value at index " + index + ". "
1392- + "If you want this value to be null, please set it to null explicitly.");
1393- index += 1;
1348+ + "If you want this value to be null, please set it to null explicitly.");
1349+ index += 1;
13941350 }
13951351 }
13961352 }
modified driver-core/src/main/java/com/datastax/driver/core/BusyConnectionException.java +1 −2
@@ -15,8 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-class BusyConnectionException extends Exception
19-{
18+class BusyConnectionException extends Exception {
2019 private static final long serialVersionUID = 0;
2120
2221 public BusyConnectionException() {
modified driver-core/src/main/java/com/datastax/driver/core/CBUtil.java +6 −6
@@ -15,6 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+import io.netty.buffer.ByteBuf;
20+import io.netty.util.CharsetUtil;
21+
1822 import java.net.InetAddress;
1923 import java.net.InetSocketAddress;
2024 import java.net.UnknownHostException;
@@ -22,17 +26,13 @@
2226 import java.nio.charset.CharacterCodingException;
2327 import java.util.*;
2428
25-import io.netty.buffer.ByteBuf;
26-import io.netty.util.CharsetUtil;
27-
28-import com.datastax.driver.core.exceptions.DriverInternalError;
29-
3029 /**
3130 * ByteBuf utility methods.
3231 */
3332 abstract class CBUtil { // TODO rename
3433
35- private CBUtil() {}
34+ private CBUtil() {
35+ }
3636
3737 private static String readString(ByteBuf cb, int length) {
3838 try {
modified driver-core/src/main/java/com/datastax/driver/core/CassandraTypeParser.java +26 −27
@@ -15,14 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+import com.datastax.driver.core.utils.Bytes;
2020 import com.google.common.collect.ImmutableMap;
2121 import org.slf4j.Logger;
2222 import org.slf4j.LoggerFactory;
2323
24-import com.datastax.driver.core.exceptions.DriverInternalError;
25-import com.datastax.driver.core.utils.Bytes;
24+import java.util.*;
2625
2726 /*
2827 * Helps transforming Cassandra types (as read in the schema tables) to
@@ -50,24 +49,24 @@
5049 private static final String TUPLE_TYPE = "org.apache.cassandra.db.marshal.TupleType";
5150
5251 private static ImmutableMap<String, DataType> cassTypeToDataType =
53- new ImmutableMap.Builder<String, DataType>()
54- .put("org.apache.cassandra.db.marshal.AsciiType", DataType.ascii())
55- .put("org.apache.cassandra.db.marshal.LongType", DataType.bigint())
56- .put("org.apache.cassandra.db.marshal.BytesType", DataType.blob())
57- .put("org.apache.cassandra.db.marshal.BooleanType", DataType.cboolean())
58- .put("org.apache.cassandra.db.marshal.CounterColumnType", DataType.counter())
59- .put("org.apache.cassandra.db.marshal.DecimalType", DataType.decimal())
60- .put("org.apache.cassandra.db.marshal.DoubleType", DataType.cdouble())
61- .put("org.apache.cassandra.db.marshal.FloatType", DataType.cfloat())
62- .put("org.apache.cassandra.db.marshal.InetAddressType", DataType.inet())
63- .put("org.apache.cassandra.db.marshal.Int32Type", DataType.cint())
64- .put("org.apache.cassandra.db.marshal.UTF8Type", DataType.text())
65- .put("org.apache.cassandra.db.marshal.TimestampType", DataType.timestamp())
66- .put("org.apache.cassandra.db.marshal.DateType", DataType.timestamp())
67- .put("org.apache.cassandra.db.marshal.UUIDType", DataType.uuid())
68- .put("org.apache.cassandra.db.marshal.IntegerType", DataType.varint())
69- .put("org.apache.cassandra.db.marshal.TimeUUIDType", DataType.timeuuid())
70- .build();
52+ new ImmutableMap.Builder<String, DataType>()
53+ .put("org.apache.cassandra.db.marshal.AsciiType", DataType.ascii())
54+ .put("org.apache.cassandra.db.marshal.LongType", DataType.bigint())
55+ .put("org.apache.cassandra.db.marshal.BytesType", DataType.blob())
56+ .put("org.apache.cassandra.db.marshal.BooleanType", DataType.cboolean())
57+ .put("org.apache.cassandra.db.marshal.CounterColumnType", DataType.counter())
58+ .put("org.apache.cassandra.db.marshal.DecimalType", DataType.decimal())
59+ .put("org.apache.cassandra.db.marshal.DoubleType", DataType.cdouble())
60+ .put("org.apache.cassandra.db.marshal.FloatType", DataType.cfloat())
61+ .put("org.apache.cassandra.db.marshal.InetAddressType", DataType.inet())
62+ .put("org.apache.cassandra.db.marshal.Int32Type", DataType.cint())
63+ .put("org.apache.cassandra.db.marshal.UTF8Type", DataType.text())
64+ .put("org.apache.cassandra.db.marshal.TimestampType", DataType.timestamp())
65+ .put("org.apache.cassandra.db.marshal.DateType", DataType.timestamp())
66+ .put("org.apache.cassandra.db.marshal.UUIDType", DataType.uuid())
67+ .put("org.apache.cassandra.db.marshal.IntegerType", DataType.varint())
68+ .put("org.apache.cassandra.db.marshal.TimeUUIDType", DataType.timeuuid())
69+ .build();
7170
7271 static DataType parseOne(String className) {
7372 boolean frozen = false;
@@ -95,7 +94,7 @@
9594
9695 if (frozen)
9796 logger.warn("Got o.a.c.db.marshal.FrozenType for something else than a collection, "
98- + "this driver version might be too old for your version of Cassandra");
97+ + "this driver version might be too old for your version of Cassandra");
9998
10099 if (isUserType(next)) {
101100 ++parser.idx; // skipping '('
@@ -196,9 +195,9 @@
196195
197196 private ParseResult(DataType type, boolean reversed) {
198197 this(false,
199- Collections.<DataType>singletonList(type),
200- Collections.<Boolean>singletonList(reversed),
201- Collections.<String, DataType>emptyMap());
198+ Collections.<DataType>singletonList(type),
199+ Collections.<Boolean>singletonList(reversed),
200+ Collections.<String, DataType>emptyMap());
202201 }
203202
204203 private ParseResult(boolean isComposite, List<DataType> types, List<Boolean> reversed, Map<String, DataType> collections) {
@@ -395,7 +394,7 @@
395394
396395 @Override
397396 public String toString() {
398- return str.substring(0, idx) + "[" + (idx == str.length() ? "" : str.charAt(idx)) + "]" + str.substring(idx+1);
397+ return str.substring(0, idx) + "[" + (idx == str.length() ? "" : str.charAt(idx)) + "]" + str.substring(idx + 1);
399398 }
400399 }
401400 }
modified driver-core/src/main/java/com/datastax/driver/core/ChainedResultSetFuture.java +5 −5
@@ -15,15 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.ExecutionException;
19-import java.util.concurrent.TimeUnit;
20-import java.util.concurrent.TimeoutException;
21-
2218 import com.google.common.util.concurrent.AbstractFuture;
2319 import com.google.common.util.concurrent.FutureCallback;
2420 import com.google.common.util.concurrent.Futures;
2521 import com.google.common.util.concurrent.Uninterruptibles;
2622
23+import java.util.concurrent.ExecutionException;
24+import java.util.concurrent.TimeUnit;
25+import java.util.concurrent.TimeoutException;
26+
2727 /**
2828 * A {@code ResultSetFuture} that will complete when its source future completes.
2929 */
@@ -51,7 +51,7 @@
5151 @Override
5252 public boolean cancel(boolean mayInterruptIfRunning) {
5353 return (source == null || source.cancel(mayInterruptIfRunning))
54- && super.cancel(mayInterruptIfRunning);
54+ && super.cancel(mayInterruptIfRunning);
5555 }
5656
5757 @Override
modified driver-core/src/main/java/com/datastax/driver/core/CloseFuture.java +8 −7
@@ -15,25 +15,26 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-
2018 import com.google.common.util.concurrent.AbstractFuture;
2119 import com.google.common.util.concurrent.FutureCallback;
2220 import com.google.common.util.concurrent.Futures;
2321
22+import java.util.List;
23+
2424 /**
2525 * A future on the shutdown of a Cluster or Session instance.
26- * <p>
26+ * <p/>
2727 * This is a standard future except for the fact that this class has an
2828 * additional {@link #force} method that can be used to expedite the shutdown
2929 * process (see below).
30- * <p>
30+ * <p/>
3131 * Note that this class implements <a href="http://code.google.com/p/guava-libraries/">Guava</a>'s {@code
3232 * ListenableFuture} and can so be used with Guava's future utilities.
3333 */
3434 public abstract class CloseFuture extends AbstractFuture<Void> {
3535
36- CloseFuture() {}
36+ CloseFuture() {
37+ }
3738
3839 static CloseFuture immediateFuture() {
3940 CloseFuture future = new CloseFuture() {
@@ -48,11 +49,11 @@
4849
4950 /**
5051 * Try to force the completion of the shutdown this is a future of.
51- * <p>
52+ * <p/>
5253 * This method will do its best to expedite the shutdown process. In
5354 * particular, all connections will be closed right away, even if there is
5455 * ongoing queries at the time this method is called.
55- * <p>
56+ * <p/>
5657 * Note that this method does not block. The completion of this method does
5758 * not imply the shutdown process is done, you still need to wait on this
5859 * future to ensure that, but calling this method will ensure said
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +231 −253
@@ -15,16 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.io.Closeable;
19-import java.net.InetAddress;
20-import java.net.InetSocketAddress;
21-import java.net.UnknownHostException;
22-import java.util.*;
23-import java.util.Map.Entry;
24-import java.util.concurrent.*;
25-import java.util.concurrent.atomic.AtomicInteger;
26-import java.util.concurrent.atomic.AtomicReference;
27-
18+import com.datastax.driver.core.exceptions.AuthenticationException;
19+import com.datastax.driver.core.exceptions.DriverInternalError;
20+import com.datastax.driver.core.exceptions.InvalidQueryException;
21+import com.datastax.driver.core.exceptions.NoHostAvailableException;
22+import com.datastax.driver.core.policies.*;
23+import com.datastax.driver.core.utils.MoreFutures;
2824 import com.google.common.annotations.VisibleForTesting;
2925 import com.google.common.base.Functions;
3026 import com.google.common.base.Predicates;
@@ -34,18 +30,21 @@
3430 import org.slf4j.Logger;
3531 import org.slf4j.LoggerFactory;
3632
37-import com.datastax.driver.core.exceptions.AuthenticationException;
38-import com.datastax.driver.core.exceptions.DriverInternalError;
39-import com.datastax.driver.core.exceptions.InvalidQueryException;
40-import com.datastax.driver.core.exceptions.NoHostAvailableException;
41-import com.datastax.driver.core.policies.*;
42-import com.datastax.driver.core.utils.MoreFutures;
33+import java.io.Closeable;
34+import java.net.InetAddress;
35+import java.net.InetSocketAddress;
36+import java.net.UnknownHostException;
37+import java.util.*;
38+import java.util.Map.Entry;
39+import java.util.concurrent.*;
40+import java.util.concurrent.atomic.AtomicInteger;
41+import java.util.concurrent.atomic.AtomicReference;
4342
4443 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
4544
4645 /**
4746 * Information and known state of a Cassandra cluster.
48- * <p>
47+ * <p/>
4948 * This is the main entry point of the driver. A simple example of access to a
5049 * Cassandra cluster would be:
5150 * <pre>
@@ -55,7 +54,7 @@
5554 * for (Row row : session.execute("SELECT * FROM table1"))
5655 * // do something ...
5756 * </pre>
58- * <p>
57+ * <p/>
5958 * A cluster object maintains a permanent connection to one of the cluster nodes
6059 * which it uses solely to maintain information on the state and current
6160 * topology of the cluster. Using the connection, the driver will discover all
@@ -69,7 +68,7 @@
6968 @VisibleForTesting
7069 static final int NEW_NODE_DELAY_SECONDS = SystemProperties.getInt("com.datastax.driver.NEW_NODE_DELAY_SECONDS", 1);
7170 private static final int NON_BLOCKING_EXECUTOR_SIZE = SystemProperties.getInt("com.datastax.driver.NON_BLOCKING_EXECUTOR_SIZE",
72- Runtime.getRuntime().availableProcessors());
71+ Runtime.getRuntime().availableProcessors());
7372
7473 private static final ResourceBundle driverProperties = ResourceBundle.getBundle("com.datastax.driver.core.Driver");
7574
@@ -85,13 +84,13 @@
8584
8685 /**
8786 * Constructs a new Cluster instance.
88- * <p>
87+ * <p/>
8988 * This constructor is mainly exposed so Cluster can be sub-classed as a means to make testing/mocking
9089 * easier or to "intercept" its method call. Most users shouldn't extend this class however and
9190 * should prefer either using the {@link #builder} or calling {@link #buildFrom} with a custom
9291 * Initializer.
9392 *
94- * @param name the name to use for the cluster (this is not the Cassandra cluster name, see {@link #getClusterName}).
93+ * @param name the name to use for the cluster (this is not the Cassandra cluster name, see {@link #getClusterName}).
9594 * @param contactPoints the list of contact points to use for the new cluster.
9695 * @param configuration the configuration for the new cluster.
9796 */
@@ -101,7 +100,7 @@
101100
102101 /**
103102 * Constructs a new Cluster instance.
104- * <p>
103+ * <p/>
105104 * This constructor is mainly exposed so Cluster can be sub-classed as a means to make testing/mocking
106105 * easier or to "intercept" its method call. Most users shouldn't extend this class however and
107106 * should prefer using the {@link #builder}.
@@ -111,9 +110,9 @@
111110 */
112111 protected Cluster(Initializer initializer) {
113112 this(initializer.getClusterName(),
114- checkNotEmpty(initializer.getContactPoints()),
115- initializer.getConfiguration(),
116- initializer.getInitialListeners());
113+ checkNotEmpty(initializer.getContactPoints()),
114+ initializer.getConfiguration(),
115+ initializer.getInitialListeners());
117116 }
118117
119118 private static List<InetSocketAddress> checkNotEmpty(List<InetSocketAddress> contactPoints) {
@@ -128,35 +127,34 @@
128127
129128 /**
130129 * Initialize this Cluster instance.
131- *
130+ * <p/>
132131 * This method creates an initial connection to one of the contact points
133132 * used to construct the {@code Cluster} instance. That connection is then
134133 * used to populate the cluster {@link Metadata}.
135- * <p>
134+ * <p/>
136135 * Calling this method is optional in the sense that any call to one of the
137136 * {@code connect} methods of this object will automatically trigger a call
138137 * to this method beforehand. It is thus only useful to call this method if
139138 * for some reason you want to populate the metadata (or test that at least
140139 * one contact point can be reached) without creating a first {@code
141140 * Session}.
142- * <p>
141+ * <p/>
143142 * Please note that this method only creates one control connection for
144143 * gathering cluster metadata. In particular, it doesn't create any connection pools.
145144 * Those are created when a new {@code Session} is created through
146145 * {@code connect}.
147- * <p>
146+ * <p/>
148147 * This method has no effect if the cluster is already initialized.
149148 *
150149 * @return this {@code Cluster} object.
151- *
152150 * @throws NoHostAvailableException if no host amongst the contact points
153- * can be reached.
154- * @throws AuthenticationException if an authentication error occurs
155- * while contacting the initial contact points.
156- * @throws IllegalStateException if the Cluster was closed prior to calling
157- * this method. This can occur either directly (through {@link #close()} or
158- * {@link #closeAsync()}), or as a result of an error while initializing the
159- * Cluster.
151+ * can be reached.
152+ * @throws AuthenticationException if an authentication error occurs
153+ * while contacting the initial contact points.
154+ * @throws IllegalStateException if the Cluster was closed prior to calling
155+ * this method. This can occur either directly (through {@link #close()} or
156+ * {@link #closeAsync()}), or as a result of an error while initializing the
157+ * Cluster.
160158 */
161159 public Cluster init() {
162160 this.manager.init();
@@ -165,18 +163,17 @@
165163
166164 /**
167165 * Build a new cluster based on the provided initializer.
168- * <p>
166+ * <p/>
169167 * Note that for building a cluster pragmatically, Cluster.Builder
170168 * provides a slightly less verbose shortcut with {@link Builder#build}.
171- * <p>
169+ * <p/>
172170 * Also note that that all the contact points provided by {@code
173171 * initializer} must share the same port.
174172 *
175173 * @param initializer the Cluster.Initializer to use
176174 * @return the newly created Cluster instance
177- *
178175 * @throws IllegalArgumentException if the list of contact points provided
179- * by {@code initializer} is empty or if not all those contact points have the same port.
176+ * by {@code initializer} is empty or if not all those contact points have the same port.
180177 */
181178 public static Cluster buildFrom(Initializer initializer) {
182179 return new Cluster(initializer);
@@ -184,7 +181,7 @@
184181
185182 /**
186183 * Creates a new {@link Cluster.Builder} instance.
187- * <p>
184+ * <p/>
188185 * This is a convenience method for {@code new Cluster.Builder()}.
189186 *
190187 * @return the new cluster builder.
@@ -195,7 +192,7 @@
195192
196193 /**
197194 * Returns the current version of the driver.
198- * <p>
195+ * <p/>
199196 * This is intended for products that wrap or extend the driver, as a way to check
200197 * compatibility if end-users override the driver version in their application.
201198 *
@@ -207,16 +204,16 @@
207204
208205 /**
209206 * Creates a new session on this cluster but does not initialize it.
210- * <p>
207+ * <p/>
211208 * Because this method does not perform any initialization, it cannot fail.
212209 * The initialization of the session (the connection of the Session to the
213210 * Cassandra nodes) will occur if either the {@link Session#init} method is
214211 * called explicitly, or whenever the returned session object is used.
215- * <p>
212+ * <p/>
216213 * Once a session returned by this method gets initialized (see above), it
217214 * will be set to no keyspace. If you want to set such session to a
218215 * keyspace, you will have to explicitly execute a 'USE mykeyspace' query.
219- * <p>
216+ * <p/>
220217 * Note that if you do not particularly need to defer initialization, it is
221218 * simpler to use one of the {@code connect()} method of this class.
222219 *
@@ -229,23 +226,22 @@
229226
230227 /**
231228 * Creates a new session on this cluster and initialize it.
232- * <p>
229+ * <p/>
233230 * Note that this method will initialize the newly created session, trying
234231 * to connect to the Cassandra nodes before returning. If you only want to
235232 * create a Session object without initializing it right away, see
236233 * {@link #newSession}.
237234 *
238235 * @return a new session on this cluster sets to no keyspace.
239- *
240236 * @throws NoHostAvailableException if the Cluster has not been initialized
241- * yet ({@link #init} has not be called and this is the first connect call)
242- * and no host amongst the contact points can be reached.
243- * @throws AuthenticationException if an authentication error occurs while
244- * contacting the initial contact points.
245- * @throws IllegalStateException if the Cluster was closed prior to calling
246- * this method. This can occur either directly (through {@link #close()} or
247- * {@link #closeAsync()}), or as a result of an error while initializing the
248- * Cluster.
237+ * yet ({@link #init} has not be called and this is the first connect call)
238+ * and no host amongst the contact points can be reached.
239+ * @throws AuthenticationException if an authentication error occurs while
240+ * contacting the initial contact points.
241+ * @throws IllegalStateException if the Cluster was closed prior to calling
242+ * this method. This can occur either directly (through {@link #close()} or
243+ * {@link #closeAsync()}), or as a result of an error while initializing the
244+ * Cluster.
249245 */
250246 public Session connect() {
251247 try {
@@ -258,28 +254,27 @@
258254 /**
259255 * Creates a new session on this cluster, initialize it and sets the
260256 * keyspace to the provided one.
261- * <p>
257+ * <p/>
262258 * Note that this method will initialize the newly created session, trying
263259 * to connect to the Cassandra nodes before returning. If you only want to
264260 * create a Session object without initializing it right away, see
265261 * {@link #newSession}.
266262 *
267263 * @param keyspace The name of the keyspace to use for the created
268- * {@code Session}.
264+ * {@code Session}.
269265 * @return a new session on this cluster sets to keyspace
270266 * {@code keyspaceName}.
271- *
272267 * @throws NoHostAvailableException if the Cluster has not been initialized
273- * yet ({@link #init} has not be called and this is the first connect call)
274- * and no host amongst the contact points can be reached, or if no host can
275- * be contacted to set the {@code keyspace}.
276- * @throws AuthenticationException if an authentication error occurs while
277- * contacting the initial contact points.
278- * @throws InvalidQueryException if the keyspace does not exists.
279- * @throws IllegalStateException if the Cluster was closed prior to calling
280- * this method. This can occur either directly (through {@link #close()} or
281- * {@link #closeAsync()}), or as a result of an error while initializing the
282- * Cluster.
268+ * yet ({@link #init} has not be called and this is the first connect call)
269+ * and no host amongst the contact points can be reached, or if no host can
270+ * be contacted to set the {@code keyspace}.
271+ * @throws AuthenticationException if an authentication error occurs while
272+ * contacting the initial contact points.
273+ * @throws InvalidQueryException if the keyspace does not exists.
274+ * @throws IllegalStateException if the Cluster was closed prior to calling
275+ * this method. This can occur either directly (through {@link #close()} or
276+ * {@link #closeAsync()}), or as a result of an error while initializing the
277+ * Cluster.
283278 */
284279 public Session connect(String keyspace) {
285280 try {
@@ -291,23 +286,20 @@
291286
292287 /**
293288 * Creates a new session on this cluster and initializes it asynchronously.
294- *
289+ * <p/>
295290 * This will also initialize the {@code Cluster} if needed; note that cluster
296291 * initialization happens synchronously on the thread that called this method.
297292 * Therefore it is recommended to initialize the cluster at application
298293 * startup, and not rely on this method to do it.
299294 *
300295 * @return a future that will complete when the session is fully initialized.
301- *
302296 * @throws NoHostAvailableException if the Cluster has not been initialized
303- * yet ({@link #init} has not been called and this is the first connect call)
304- * and no host amongst the contact points can be reached.
305- *
306- * @throws IllegalStateException if the Cluster was closed prior to calling
307- * this method. This can occur either directly (through {@link #close()} or
308- * {@link #closeAsync()}), or as a result of an error while initializing the
309- * Cluster.
310- *
297+ * yet ({@link #init} has not been called and this is the first connect call)
298+ * and no host amongst the contact points can be reached.
299+ * @throws IllegalStateException if the Cluster was closed prior to calling
300+ * this method. This can occur either directly (through {@link #close()} or
301+ * {@link #closeAsync()}), or as a result of an error while initializing the
302+ * Cluster.
311303 * @see #connect()
312304 */
313305 public ListenableFuture<Session> connectAsync() {
@@ -317,24 +309,22 @@
317309 /**
318310 * Creates a new session on this cluster, and initializes it to the given
319311 * keyspace asynchronously.
320- *
312+ * <p/>
321313 * This will also initialize the {@code Cluster} if needed; note that cluster
322314 * initialization happens synchronously on the thread that called this method.
323315 * Therefore it is recommended to initialize the cluster at application
324316 * startup, and not rely on this method to do it.
325317 *
326318 * @param keyspace The name of the keyspace to use for the created
327- * {@code Session}.
319+ * {@code Session}.
328320 * @return a future that will complete when the session is fully initialized.
329- *
330321 * @throws NoHostAvailableException if the Cluster has not been initialized
331- * yet ({@link #init} has not been called and this is the first connect call)
332- * and no host amongst the contact points can be reached.
333- *
334- * @throws IllegalStateException if the Cluster was closed prior to calling
335- * this method. This can occur either directly (through {@link #close()} or
336- * {@link #closeAsync()}), or as a result of an error while initializing the
337- * Cluster.
322+ * yet ({@link #init} has not been called and this is the first connect call)
323+ * and no host amongst the contact points can be reached.
324+ * @throws IllegalStateException if the Cluster was closed prior to calling
325+ * this method. This can occur either directly (through {@link #close()} or
326+ * {@link #closeAsync()}), or as a result of an error while initializing the
327+ * Cluster.
338328 */
339329 public ListenableFuture<Session> connectAsync(final String keyspace) {
340330 checkNotClosed(manager);
@@ -362,7 +352,7 @@
362352
363353 /**
364354 * The name of this cluster object.
365- * <p>
355+ * <p/>
366356 * Note that this is not the Cassandra cluster name, but rather a name
367357 * assigned to this Cluster object. Currently, that name is only used
368358 * for one purpose: to distinguish exposed JMX metrics when multiple
@@ -380,7 +370,7 @@
380370
381371 /**
382372 * Returns read-only metadata on the connected cluster.
383- * <p>
373+ * <p/>
384374 * This includes the known nodes with their status as seen by the driver,
385375 * as well as the schema definitions. Since this return metadata on the
386376 * connected cluster, this method may trigger the creation of a connection
@@ -388,15 +378,14 @@
388378 * has been called yet).
389379 *
390380 * @return the cluster metadata.
391- *
392381 * @throws NoHostAvailableException if the Cluster has not been initialized yet
393- * and no host amongst the contact points can be reached.
394- * @throws AuthenticationException if an authentication error occurs
395- * while contacting the initial contact points.
396- * @throws IllegalStateException if the Cluster was closed prior to calling
397- * this method. This can occur either directly (through {@link #close()} or
398- * {@link #closeAsync()}), or as a result of an error while initializing the
399- * Cluster.
382+ * and no host amongst the contact points can be reached.
383+ * @throws AuthenticationException if an authentication error occurs
384+ * while contacting the initial contact points.
385+ * @throws IllegalStateException if the Cluster was closed prior to calling
386+ * this method. This can occur either directly (through {@link #close()} or
387+ * {@link #closeAsync()}), or as a result of an error while initializing the
388+ * Cluster.
400389 */
401390 public Metadata getMetadata() {
402391 manager.init();
@@ -427,9 +416,9 @@
427416 /**
428417 * Registers the provided listener to be notified on hosts
429418 * up/down/added/removed events.
430- * <p>
419+ * <p/>
431420 * Registering the same listener multiple times is a no-op.
432- * <p>
421+ * <p/>
433422 * Note that while {@link LoadBalancingPolicy} implements
434423 * {@code Host.StateListener}, the configured load balancing does not
435424 * need to (and should not) be registered through this method to
@@ -446,7 +435,7 @@
446435
447436 /**
448437 * Unregisters the provided listener from being notified on hosts events.
449- * <p>
438+ * <p/>
450439 * This method is a no-op if {@code listener} hadn't previously be
451440 * registered against this Cluster.
452441 *
@@ -462,13 +451,13 @@
462451 /**
463452 * Registers the provided tracker to be updated with hosts read
464453 * latencies.
465- * <p>
454+ * <p/>
466455 * Registering the same listener multiple times is a no-op.
467- * <p>
456+ * <p/>
468457 * Be wary that the registered tracker {@code update} method will be call
469458 * very frequently (at the end of every query to a Cassandra host) and
470459 * should thus not be costly.
471- * <p>
460+ * <p/>
472461 * The main use case for a {@code LatencyTracker} is so
473462 * {@link LoadBalancingPolicy} can implement latency awareness
474463 * Typically, {@link LatencyAwarePolicy} registers it's own internal
@@ -487,7 +476,7 @@
487476 /**
488477 * Unregisters the provided latency tracking from being updated
489478 * with host read latencies.
490- * <p>
479+ * <p/>
491480 * This method is a no-op if {@code tracker} hadn't previously be
492481 * registered against this Cluster.
493482 *
@@ -502,7 +491,7 @@
502491
503492 /**
504493 * Registers the provided listener to be updated with schema change events.
505- * <p>
494+ * <p/>
506495 * Registering the same listener multiple times is a no-op.
507496 *
508497 * @param listener the new {@link SchemaChangeListener} to register.
@@ -518,7 +507,7 @@
518507 /**
519508 * Unregisters the provided schema change listener from being updated
520509 * with schema change events.
521- * <p>
510+ * <p/>
522511 * This method is a no-op if {@code listener} hadn't previously be
523512 * registered against this Cluster.
524513 *
@@ -534,17 +523,17 @@
534523
535524 /**
536525 * Initiates a shutdown of this cluster instance.
537- * <p>
526+ * <p/>
538527 * This method is asynchronous and return a future on the completion
539528 * of the shutdown process. As soon a the cluster is shutdown, no
540529 * new request will be accepted, but already submitted queries are
541530 * allowed to complete. This method closes all connections from all
542531 * sessions and reclaims all resources used by this Cluster
543532 * instance.
544- * <p>
533+ * <p/>
545534 * If for some reason you wish to expedite this process, the
546535 * {@link CloseFuture#force} can be called on the result future.
547- * <p>
536+ * <p/>
548537 * This method has no particular effect if the cluster was already closed
549538 * (in which case the returned future will return immediately).
550539 *
@@ -557,7 +546,7 @@
557546 /**
558547 * Initiates a shutdown of this cluster instance and blocks until
559548 * that shutdown completes.
560- * <p>
549+ * <p/>
561550 * This method is a shortcut for {@code closeAsync().get()}.
562551 */
563552 public void close() {
@@ -572,7 +561,7 @@
572561
573562 /**
574563 * Whether this Cluster instance has been closed.
575- * <p>
564+ * <p/>
576565 * Note that this method returns true as soon as one of the close methods
577566 * ({@link #closeAsync} or {@link #close}) has been called, it does not guarantee
578567 * that the closing is done. If you want to guarantee that the closing is done,
@@ -593,11 +582,11 @@
593582
594583 /**
595584 * Initializer for {@link Cluster} instances.
596- * <p>
585+ * <p/>
597586 * If you want to create a new {@code Cluster} instance programmatically,
598587 * then it is advised to use {@link Cluster.Builder} which can be obtained from the
599588 * {@link Cluster#builder} method.
600- * <p>
589+ * <p/>
601590 * But it is also possible to implement a custom {@code Initializer} that
602591 * retrieves initialization from a web-service or from a configuration file.
603592 */
@@ -605,7 +594,7 @@
605594
606595 /**
607596 * An optional name for the created cluster.
608- * <p>
597+ * <p/>
609598 * Such name is optional (a default name will be created otherwise) and is currently
610599 * only use for JMX reporting of metrics. See {@link Cluster#getClusterName} for more
611600 * information.
@@ -625,15 +614,15 @@
625614
626615 /**
627616 * The configuration to use for the new cluster.
628- * <p>
617+ * <p/>
629618 * Note that some configuration can be modified after the cluster
630619 * initialization but some others cannot. In particular, the ones that
631620 * cannot be changed afterwards includes:
632621 * <ul>
633- * <li>the port use to connect to Cassandra nodes (see {@link ProtocolOptions}).</li>
634- * <li>the policies used (see {@link Policies}).</li>
635- * <li>the authentication info provided (see {@link Configuration}).</li>
636- * <li>whether metrics are enabled (see {@link Configuration}).</li>
622+ * <li>the port use to connect to Cassandra nodes (see {@link ProtocolOptions}).</li>
623+ * <li>the policies used (see {@link Policies}).</li>
624+ * <li>the authentication info provided (see {@link Configuration}).</li>
625+ * <li>whether metrics are enabled (see {@link Configuration}).</li>
637626 * </ul>
638627 *
639628 * @return the configuration to use for the new cluster.
@@ -642,7 +631,7 @@
642631
643632 /**
644633 * Optional listeners to register against the newly created cluster.
645- * <p>
634+ * <p/>
646635 * Note that contrary to listeners registered post Cluster creation,
647636 * the listeners returned by this method will see {@link Host.StateListener#onAdd}
648637 * events for the initial contact points.
@@ -705,11 +694,11 @@
705694
706695 /**
707696 * An optional name for the create cluster.
708- * <p>
697+ * <p/>
709698 * Note: this is not related to the Cassandra cluster name (though you
710699 * are free to provide the same name). See {@link Cluster#getClusterName} for
711700 * details.
712- * <p>
701+ * <p/>
713702 * If you use this method and create more than one Cluster instance in the
714703 * same JVM (which should be avoided unless you need to connect to multiple
715704 * Cassandra clusters), you should make sure each Cluster instance get a
@@ -725,7 +714,7 @@
725714
726715 /**
727716 * The port to use to connect to the Cassandra host.
728- * <p>
717+ * <p/>
729718 * If not set through this method, the default port (9042) will be used
730719 * instead.
731720 *
@@ -739,12 +728,11 @@
739728
740729 /**
741730 * Sets the maximum time to wait for schema agreement before returning from a DDL query.
742- * <p>
731+ * <p/>
743732 * If not set through this method, the default value (10 seconds) will be used.
744733 *
745734 * @param maxSchemaAgreementWaitSeconds the new value to set.
746735 * @return this Builder.
747- *
748736 * @throws IllegalStateException if the provided value is zero or less.
749737 */
750738 public Builder withMaxSchemaAgreementWaitSeconds(int maxSchemaAgreementWaitSeconds) {
@@ -757,19 +745,19 @@
757745
758746 /**
759747 * The native protocol version to use.
760- * <p>
748+ * <p/>
761749 * The driver supports versions 1 to 3 of the native protocol. Higher versions
762750 * of the protocol have more features and should be preferred, but this also depends
763751 * on the Cassandra version:
764- *
752+ * <p/>
765753 * <table>
766- * <caption>Native protocol version to Cassandra version correspondence</caption>
767- * <tr><th>Protocol version</th><th>Minimum Cassandra version</th></tr>
768- * <tr><td>1</td><td>1.2</td></tr>
769- * <tr><td>2</td><td>2.0</td></tr>
770- * <tr><td>3</td><td>2.1</td></tr>
754+ * <caption>Native protocol version to Cassandra version correspondence</caption>
755+ * <tr><th>Protocol version</th><th>Minimum Cassandra version</th></tr>
756+ * <tr><td>1</td><td>1.2</td></tr>
757+ * <tr><td>2</td><td>2.0</td></tr>
758+ * <tr><td>3</td><td>2.1</td></tr>
771759 * </table>
772- * <p>
760+ * <p/>
773761 * By default, the driver will "auto-detect" which protocol version it can use
774762 * when connecting to the first node. More precisely, it will try first with
775763 * {@link ProtocolVersion#NEWEST_SUPPORTED}, and if not supported fallback to
@@ -778,7 +766,7 @@
778766 * the driver connects to is a Cassandra 1.2 node and auto-detection is used
779767 * (the default), then the native protocol version 1 will be use for the lifetime
780768 * of the Cluster instance.
781- * <p>
769+ * <p/>
782770 * This method allows to force the use of a particular protocol version. Forcing
783771 * version 1 is always fine since all Cassandra version (at least all those
784772 * supporting the native protocol in the first place) so far support it. However,
@@ -789,17 +777,17 @@
789777 * an UnsupportedFeatureException). Using the protocol version 1 should thus
790778 * only be considered when using Cassandra 1.2, until nodes have been upgraded
791779 * to Cassandra 2.0.
792- * <p>
780+ * <p/>
793781 * If version 2 of the protocol is used, then Cassandra 1.2 nodes will be ignored
794782 * (the driver won't connect to them).
795- * <p>
783+ * <p/>
796784 * The default behavior (auto-detection) is fine in almost all case, but you may
797785 * want to force a particular version if you have a Cassandra cluster with mixed
798786 * 1.2/2.0 nodes (i.e. during a Cassandra upgrade).
799787 *
800788 * @param version the native protocol version to use. {@code null} is also supported
801- * to trigger auto-detection (see above) but this is the default (so you don't have
802- * to call this method for that behavior).
789+ * to trigger auto-detection (see above) but this is the default (so you don't have
790+ * to call this method for that behavior).
803791 * @return this Builder.
804792 */
805793 public Builder withProtocolVersion(ProtocolVersion version) {
@@ -813,8 +801,7 @@
813801 * @param version the native protocol version as a number.
814802 * @return this Builder.
815803 * @throws IllegalArgumentException if the number does not correspond to any known
816- * native protocol version.
817- *
804+ * native protocol version.
818805 * @deprecated This method is provided for backward compatibility. Use
819806 * {@link #withProtocolVersion(ProtocolVersion)} instead.
820807 */
@@ -826,14 +813,14 @@
826813
827814 /**
828815 * Adds a contact point.
829- * <p>
816+ * <p/>
830817 * Contact points are addresses of Cassandra nodes that the driver uses
831818 * to discover the cluster topology. Only one contact point is required
832819 * (the driver will retrieve the address of the other nodes
833820 * automatically), but it is usually a good idea to provide more than
834821 * one contact point, because if that single contact point is unavailable,
835822 * the driver cannot initialize itself correctly.
836- * <p>
823+ * <p/>
837824 * Note that by default (that is, unless you use the {@link #withLoadBalancingPolicy})
838825 * method of this builder), the first succesfully contacted host will be use
839826 * to define the local data-center for the client. If follows that if you are
@@ -843,11 +830,10 @@
843830 *
844831 * @param address the address of the node to connect to
845832 * @return this Builder.
846- *
847833 * @throws IllegalArgumentException if no IP address for {@code address}
848- * could be found
849- * @throws SecurityException if a security manager is present and
850- * permission to resolve the host name is denied.
834+ * could be found
835+ * @throws SecurityException if a security manager is present and
836+ * permission to resolve the host name is denied.
851837 */
852838 public Builder addContactPoint(String address) {
853839 // We explicitely check for nulls because InetAdress.getByName() will happily
@@ -866,18 +852,16 @@
866852
867853 /**
868854 * Adds contact points.
869- * <p>
855+ * <p/>
870856 * See {@link Builder#addContactPoint} for more details on contact
871857 * points.
872858 *
873859 * @param addresses addresses of the nodes to add as contact point.
874860 * @return this Builder.
875- *
876861 * @throws IllegalArgumentException if no IP address for at least one
877- * of {@code addresses} could be found
878- * @throws SecurityException if a security manager is present and
879- * permission to resolve the host name is denied.
880- *
862+ * of {@code addresses} could be found
863+ * @throws SecurityException if a security manager is present and
864+ * permission to resolve the host name is denied.
881865 * @see Builder#addContactPoint
882866 */
883867 public Builder addContactPoints(String... addresses) {
@@ -888,19 +872,17 @@
888872
889873 /**
890874 * Adds a contact point - or many if it host resolves to multiple <code>InetAddress</code>s (A records).
891- * <p>
892- *
875+ * <p/>
876+ * <p/>
893877 * If the host name points to a dns records with multiple a-records, all InetAddresses
894878 * returned will be used. Make sure that all resulting <code>InetAddress</code>s returned
895879 * points to the same cluster and datacenter.
896- * <p>
880+ * <p/>
897881 * See {@link Builder#addContactPoint} for more details on contact
898882 * points and thrown exceptions
899883 *
900884 * @param address address of the nodes to look up InetAddresses from to add as contact points.
901885 * @return this Builder.
902- *
903- *
904886 * @see Builder#addContactPoint
905887 */
906888 public Builder addContactPoints(String address) {
@@ -920,13 +902,12 @@
920902
921903 /**
922904 * Adds contact points.
923- * <p>
905+ * <p/>
924906 * See {@link Builder#addContactPoint} for more details on contact
925907 * points.
926908 *
927909 * @param addresses addresses of the nodes to add as contact point.
928910 * @return this Builder.
929- *
930911 * @see Builder#addContactPoint
931912 */
932913 public Builder addContactPoints(InetAddress... addresses) {
@@ -936,13 +917,12 @@
936917
937918 /**
938919 * Adds contact points.
939- *
920+ * <p/>
940921 * See {@link Builder#addContactPoint} for more details on contact
941922 * points.
942923 *
943924 * @param addresses addresses of the nodes to add as contact point
944925 * @return this Builder
945- *
946926 * @see Builder#addContactPoint
947927 */
948928 public Builder addContactPoints(Collection<InetAddress> addresses) {
@@ -952,7 +932,7 @@
952932
953933 /**
954934 * Adds contact points.
955- * <p>
935+ * <p/>
956936 * See {@link Builder#addContactPoint} for more details on contact
957937 * points. Contrarily to other {@code addContactPoints} methods, this method
958938 * allow to provide a different port for each contact points. Since Cassandra
@@ -969,7 +949,6 @@
969949 *
970950 * @param addresses addresses of the nodes to add as contact point
971951 * @return this Builder
972- *
973952 * @see Builder#addContactPoint
974953 */
975954 public Builder addContactPointsWithPorts(Collection<InetSocketAddress> addresses) {
@@ -979,7 +958,7 @@
979958
980959 /**
981960 * Configures the load balancing policy to use for the new cluster.
982- * <p>
961+ * <p/>
983962 * If no load balancing policy is set through this method,
984963 * {@link Policies#defaultLoadBalancingPolicy} will be used instead.
985964 *
@@ -993,7 +972,7 @@
993972
994973 /**
995974 * Configures the reconnection policy to use for the new cluster.
996- * <p>
975+ * <p/>
997976 * If no reconnection policy is set through this method,
998977 * {@link Policies#DEFAULT_RECONNECTION_POLICY} will be used instead.
999978 *
@@ -1007,7 +986,7 @@
1007986
1008987 /**
1009988 * Configures the retry policy to use for the new cluster.
1010- * <p>
989+ * <p/>
1011990 * If no retry policy is set through this method,
1012991 * {@link Policies#DEFAULT_RETRY_POLICY} will be used instead.
1013992 *
@@ -1021,7 +1000,7 @@
10211000
10221001 /**
10231002 * Configures the address translater to use for the new cluster.
1024- * <p>
1003+ * <p/>
10251004 * See {@link AddressTranslater} for more detail on address translation,
10261005 * but the default translater, {@link IdentityTranslater}, should be
10271006 * correct in most cases. If unsure, stick to the default.
@@ -1037,12 +1016,12 @@
10371016 /**
10381017 * Configures the generator that will produce the client-side timestamp sent
10391018 * with each query.
1040- * <p>
1019+ * <p/>
10411020 * This feature is only available with version {@link ProtocolVersion#V3 V3} or
10421021 * above of the native protocol. With earlier versions, timestamps are always
10431022 * generated server-side, and setting a generator through this method will have
10441023 * no effect.
1045- * <p>
1024+ * <p/>
10461025 * If no generator is set through this method, the driver will default to the
10471026 * legacy server-side behavior by using {@link ServerSideTimestampGenerator}.
10481027 *
@@ -1056,7 +1035,7 @@
10561035
10571036 /**
10581037 * Configures the speculative execution policy to use for the new cluster.
1059- * <p>
1038+ * <p/>
10601039 * If no policy is set through this method, {@link Policies#defaultSpeculativeExecutionPolicy()}
10611040 * will be used instead.
10621041 *
@@ -1070,7 +1049,7 @@
10701049
10711050 /**
10721051 * Uses the provided credentials when connecting to Cassandra hosts.
1073- * <p>
1052+ * <p/>
10741053 * This should be used if the Cassandra cluster has been configured to
10751054 * use the {@code PasswordAuthenticator}. If the the default {@code
10761055 * AllowAllAuthenticator} is used instead, using this method has no
@@ -1088,14 +1067,14 @@
10881067 /**
10891068 * Use the specified AuthProvider when connecting to Cassandra
10901069 * hosts.
1091- * <p>
1070+ * <p/>
10921071 * Use this method when a custom authentication scheme is in place.
10931072 * You shouldn't call both this method and {@code withCredentials}
10941073 * on the same {@code Builder} instance as one will supersede the
10951074 * other
10961075 *
10971076 * @param authProvider the {@link AuthProvider} to use to login to
1098- * Cassandra hosts.
1077+ * Cassandra hosts.
10991078 * @return this Builder
11001079 */
11011080 public Builder withAuthProvider(AuthProvider authProvider) {
@@ -1108,7 +1087,6 @@
11081087 *
11091088 * @param compression the compression to set.
11101089 * @return this Builder.
1111- *
11121090 * @see ProtocolOptions.Compression
11131091 */
11141092 public Builder withCompression(ProtocolOptions.Compression compression) {
@@ -1129,10 +1107,10 @@
11291107
11301108 /**
11311109 * Enables the use of SSL for the created {@code Cluster}.
1132- * <p>
1110+ * <p/>
11331111 * Calling this method will use default SSL options (see {@link SSLOptions#SSLOptions()}).
11341112 * This is thus a shortcut for {@code withSSL(new SSLOptions())}.
1135- * <p>
1113+ * <p/>
11361114 * Note that if SSL is enabled, the driver will not connect to any
11371115 * Cassandra nodes that doesn't have SSL enabled and it is strongly
11381116 * advised to enable SSL on every Cassandra node if you plan on using
@@ -1149,7 +1127,6 @@
11491127 * Enable the use of SSL for the created {@code Cluster} using the provided options.
11501128 *
11511129 * @param sslOptions the SSL options to use.
1152- *
11531130 * @return this builder.
11541131 */
11551132 public Builder withSSL(SSLOptions sslOptions) {
@@ -1159,7 +1136,7 @@
11591136
11601137 /**
11611138 * Register the provided listeners in the newly created cluster.
1162- * <p>
1139+ * <p/>
11631140 * Note: repeated calls to this method will override the previous ones.
11641141 *
11651142 * @param listeners the listeners to register.
@@ -1172,7 +1149,7 @@
11721149
11731150 /**
11741151 * Disables JMX reporting of the metrics.
1175- * <p>
1152+ * <p/>
11761153 * JMX reporting is enabled by default (see {@link Metrics}) but can be
11771154 * disabled using this option. If metrics are disabled, this is a
11781155 * no-op.
@@ -1186,7 +1163,7 @@
11861163
11871164 /**
11881165 * Sets the PoolingOptions to use for the newly created Cluster.
1189- * <p>
1166+ * <p/>
11901167 * If no pooling options are set through this method, default pooling
11911168 * options will be used.
11921169 *
@@ -1200,7 +1177,7 @@
12001177
12011178 /**
12021179 * Sets the SocketOptions to use for the newly created Cluster.
1203- * <p>
1180+ * <p/>
12041181 * If no socket options are set through this method, default socket
12051182 * options will be used.
12061183 *
@@ -1214,7 +1191,7 @@
12141191
12151192 /**
12161193 * Sets the QueryOptions to use for the newly created Cluster.
1217- * <p>
1194+ * <p/>
12181195 * If no query options are set through this method, default query
12191196 * options will be used.
12201197 *
@@ -1228,7 +1205,7 @@
12281205
12291206 /**
12301207 * Set the {@link NettyOptions} to use for the newly created Cluster.
1231- * <p>
1208+ * <p/>
12321209 * If no Netty options are set through this method, {@link NettyOptions#DEFAULT_INSTANCE}
12331210 * will be used as a default value, which means that no customization will be applied.
12341211 *
@@ -1242,7 +1219,7 @@
12421219
12431220 /**
12441221 * The configuration that will be used for the new cluster.
1245- * <p>
1222+ * <p/>
12461223 * You <b>should not</b> modify this object directly because changes made
12471224 * to the returned object may not be used by the cluster build.
12481225 * Instead, you should use the other methods of this {@code Builder}.
@@ -1252,20 +1229,20 @@
12521229 @Override
12531230 public Configuration getConfiguration() {
12541231 Policies policies = Policies.builder()
1255- .withLoadBalancingPolicy(loadBalancingPolicy)
1256- .withReconnectionPolicy(reconnectionPolicy)
1257- .withRetryPolicy(retryPolicy)
1258- .withAddressTranslater(addressTranslater)
1259- .withTimestampGenerator(timestampGenerator)
1260- .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
1261- .build();
1232+ .withLoadBalancingPolicy(loadBalancingPolicy)
1233+ .withReconnectionPolicy(reconnectionPolicy)
1234+ .withRetryPolicy(retryPolicy)
1235+ .withAddressTranslater(addressTranslater)
1236+ .withTimestampGenerator(timestampGenerator)
1237+ .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
1238+ .build();
12621239 return new Configuration(policies,
1263- new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider).setCompression(compression),
1264- poolingOptions == null ? new PoolingOptions() : poolingOptions,
1265- socketOptions == null ? new SocketOptions() : socketOptions,
1266- metricsEnabled ? new MetricsOptions(jmxEnabled) : null,
1267- queryOptions == null ? new QueryOptions() : queryOptions,
1268- nettyOptions);
1240+ new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider).setCompression(compression),
1241+ poolingOptions == null ? new PoolingOptions() : poolingOptions,
1242+ socketOptions == null ? new SocketOptions() : socketOptions,
1243+ metricsEnabled ? new MetricsOptions(jmxEnabled) : null,
1244+ queryOptions == null ? new QueryOptions() : queryOptions,
1245+ nettyOptions);
12691246 }
12701247
12711248 @Override
@@ -1276,7 +1253,7 @@
12761253 /**
12771254 * Builds the cluster with the configured set of initial contact points
12781255 * and policies.
1279- * <p>
1256+ * <p/>
12801257 * This is a convenience method for {@code Cluster.buildFrom(this)}.
12811258 *
12821259 * @return the newly built Cluster instance.
@@ -1296,7 +1273,7 @@
12961273
12971274 /**
12981275 * The sessions and hosts managed by this a Cluster instance.
1299- * <p>
1276+ * <p/>
13001277 * Note: the reason we create a Manager object separate from Cluster is
13011278 * that Manager is not publicly visible. For instance, we wouldn't want
13021279 * user to be able to call the {@link #onUp} and {@link #onDown} methods.
@@ -1347,7 +1324,7 @@
13471324
13481325 final Set<Host.StateListener> listeners;
13491326 final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>();
1350- final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>();
1327+ final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>();
13511328
13521329 EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer;
13531330 EventDebouncer<NodeRefreshRequest> nodeRefreshRequestDebouncer;
@@ -1391,23 +1368,23 @@
13911368 // create debouncers - at this stage, they are not running yet
13921369 QueryOptions queryOptions = configuration.getQueryOptions();
13931370 this.nodeListRefreshRequestDebouncer = new EventDebouncer<NodeListRefreshRequest>(
1394- "Node list refresh",
1395- scheduledTasksExecutor,
1396- new NodeListRefreshRequestDeliveryCallback(),
1397- queryOptions.getRefreshNodeListIntervalMillis(),
1398- queryOptions.getMaxPendingRefreshNodeListRequests());
1371+ "Node list refresh",
1372+ scheduledTasksExecutor,
1373+ new NodeListRefreshRequestDeliveryCallback(),
1374+ queryOptions.getRefreshNodeListIntervalMillis(),
1375+ queryOptions.getMaxPendingRefreshNodeListRequests());
13991376 this.nodeRefreshRequestDebouncer = new EventDebouncer<NodeRefreshRequest>(
1400- "Node refresh",
1401- scheduledTasksExecutor,
1402- new NodeRefreshRequestDeliveryCallback(),
1403- queryOptions.getRefreshNodeIntervalMillis(),
1404- queryOptions.getMaxPendingRefreshNodeRequests());
1377+ "Node refresh",
1378+ scheduledTasksExecutor,
1379+ new NodeRefreshRequestDeliveryCallback(),
1380+ queryOptions.getRefreshNodeIntervalMillis(),
1381+ queryOptions.getMaxPendingRefreshNodeRequests());
14051382 this.schemaRefreshRequestDebouncer = new EventDebouncer<SchemaRefreshRequest>(
1406- "Schema refresh",
1407- scheduledTasksExecutor,
1408- new SchemaRefreshRequestDeliveryCallback(),
1409- queryOptions.getRefreshSchemaIntervalMillis(),
1410- queryOptions.getMaxPendingRefreshSchemaRequests());
1383+ "Schema refresh",
1384+ scheduledTasksExecutor,
1385+ new SchemaRefreshRequestDeliveryCallback(),
1386+ queryOptions.getRefreshSchemaIntervalMillis(),
1387+ queryOptions.getMaxPendingRefreshSchemaRequests());
14111388
14121389 this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
14131390
@@ -1417,9 +1394,9 @@
14171394 // create the Host object so we can initialize the control connection.
14181395 metadata.add(address);
14191396 }
1420-
1397+
14211398 Collection<Host> allHosts = metadata.allHosts();
1422-
1399+
14231400 // At this stage, metadata.allHosts() only contains the contact points, that's what we want to pass to LBP.init().
14241401 // But the control connection will initialize first and discover more hosts, so make a copy.
14251402 Set<Host> contactPointHosts = Sets.newHashSet(allHosts);
@@ -1455,7 +1432,7 @@
14551432 // rack...) to initialize the load balancing policy
14561433 loadBalancingPolicy().init(Cluster.this, contactPointHosts);
14571434 speculativeRetryPolicy().init(Cluster.this);
1458-
1435+
14591436 for (Host host : removedContactPointHosts) {
14601437 loadBalancingPolicy().onRemove(host);
14611438 for (Host.StateListener listener : listeners)
@@ -1484,7 +1461,7 @@
14841461 logUnsupportedVersionProtocol(host, connectionFactory.protocolVersion);
14851462 continue;
14861463 }
1487-
1464+
14881465 if (!contactPointHosts.contains(host))
14891466 loadBalancingPolicy().onAdd(host);
14901467
@@ -1516,11 +1493,11 @@
15161493
15171494 private ListeningExecutorService makeExecutor(int threads, String name, LinkedBlockingQueue<Runnable> workQueue) {
15181495 ThreadPoolExecutor executor = new ThreadPoolExecutor(threads,
1519- threads,
1520- DEFAULT_THREAD_KEEP_ALIVE,
1521- TimeUnit.SECONDS,
1522- workQueue,
1523- threadFactory(name));
1496+ threads,
1497+ DEFAULT_THREAD_KEEP_ALIVE,
1498+ TimeUnit.SECONDS,
1499+ workQueue,
1500+ threadFactory(name));
15241501
15251502 executor.allowCoreThreadTimeOut(true);
15261503 return MoreExecutors.listeningDecorator(executor);
@@ -1598,13 +1575,13 @@
15981575 // And the load balancing policy
15991576 LoadBalancingPolicy loadBalancingPolicy = loadBalancingPolicy();
16001577 if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy)
1601- ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close();
1578+ ((CloseableLoadBalancingPolicy) loadBalancingPolicy).close();
16021579
16031580 speculativeRetryPolicy().close();
16041581
16051582 AddressTranslater translater = configuration.getPolicies().getAddressTranslater();
16061583 if (translater instanceof CloseableAddressTranslater)
1607- ((CloseableAddressTranslater)translater).close();
1584+ ((CloseableAddressTranslater) translater).close();
16081585
16091586 for (SchemaChangeListener listener : schemaChangeListeners) {
16101587 listener.onUnregister(Cluster.this);
@@ -1623,8 +1600,8 @@
16231600 }
16241601
16251602 return closeFuture.compareAndSet(null, future)
1626- ? future
1627- : closeFuture.get(); // We raced, it's ok, return the future that was actually set
1603+ ? future
1604+ : closeFuture.get(); // We raced, it's ok, return the future that was actually set
16281605 }
16291606
16301607 private void shutdownNow(ExecutorService executor) {
@@ -1632,20 +1609,20 @@
16321609 // If some tasks were submitted to this executor but not yet commenced, make sure the corresponding futures complete
16331610 for (Runnable pendingTask : pendingTasks) {
16341611 if (pendingTask instanceof FutureTask<?>)
1635- ((FutureTask<?>)pendingTask).cancel(false);
1612+ ((FutureTask<?>) pendingTask).cancel(false);
16361613 }
16371614 }
16381615
16391616 void logUnsupportedVersionProtocol(Host host, ProtocolVersion version) {
16401617 logger.warn("Detected added or restarted Cassandra host {} but ignoring it since it does not support the version {} of the native "
1641- + "protocol which is currently in use. If you want to force the use of a particular version of the native protocol, use "
1642- + "Cluster.Builder#usingProtocolVersion() when creating the Cluster instance.", host, version);
1618+ + "protocol which is currently in use. If you want to force the use of a particular version of the native protocol, use "
1619+ + "Cluster.Builder#usingProtocolVersion() when creating the Cluster instance.", host, version);
16431620 }
16441621
16451622 void logClusterNameMismatch(Host host, String expectedClusterName, String actualClusterName) {
16461623 logger.warn("Detected added or restarted Cassandra host {} but ignoring it since its cluster name '{}' does not match the one "
1647- + "currently known ({})",
1648- host, actualClusterName, expectedClusterName);
1624+ + "currently known ({})",
1625+ host, actualClusterName, expectedClusterName);
16491626 }
16501627
16511628 public ListenableFuture<?> triggerOnUp(final Host host) {
@@ -1679,7 +1656,7 @@
16791656 return;
16801657 }
16811658 try {
1682-
1659+
16831660 // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
16841661 if (host.state == Host.State.UP)
16851662 return;
@@ -1768,7 +1745,7 @@
17681745 }
17691746
17701747 public ListenableFuture<?> triggerOnDown(final Host host, final boolean isHostAddition, final boolean startReconnection) {
1771- if(!isClosed()) {
1748+ if (!isClosed()) {
17721749 return executor.submit(new ExceptionCatchingRunnable() {
17731750 @Override
17741751 public void runMayThrow() throws InterruptedException, ExecutionException {
@@ -2123,7 +2100,7 @@
21232100 PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().id, stmt);
21242101 if (previous != null) {
21252102 logger.warn("Re-preparing already prepared query {}. Please note that preparing the same query more than once is "
2126- + "generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.", stmt.getQueryString());
2103+ + "generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.", stmt.getQueryString());
21272104
21282105 // The one object in the cache will get GCed once it's not referenced by the client anymore since we use a weak reference.
21292106 // So we need to make sure that the instance we do return to the user is the one that is in the cache.
@@ -2136,7 +2113,7 @@
21362113 * @param reusedConnection an existing connection (from a reconnection attempt) that we want to
21372114 * reuse to prepare the statements (might be null).
21382115 * @return a connection that the rest of the initialization process can use (it will be made part
2139- * of a connection pool). Can be reusedConnection, or one that was open in the method.
2116+ * of a connection pool). Can be reusedConnection, or one that was open in the method.
21402117 */
21412118 private Connection prepareAllQueries(Host host, Connection reusedConnection) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
21422119 if (preparedQueries.isEmpty())
@@ -2146,8 +2123,8 @@
21462123 Connection connection = null;
21472124 try {
21482125 connection = (reusedConnection == null)
2149- ? connectionFactory.open(host)
2150- : reusedConnection;
2126+ ? connectionFactory.open(host)
2127+ : reusedConnection;
21512128
21522129 try {
21532130 controlConnection.waitForSchemaAgreement();
@@ -2235,8 +2212,8 @@
22352212 public void refreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final SchemaElement target, final String keyspace, final String name) {
22362213 if (logger.isDebugEnabled())
22372214 logger.debug("Refreshing schema for {}{}",
2238- target == null ? "everything" : keyspace,
2239- (target == KEYSPACE) ? "" : "." + name + " (" + target + ")");
2215+ target == null ? "everything" : keyspace,
2216+ (target == KEYSPACE) ? "" : "." + name + " (" + target + ")");
22402217
22412218 maybeRefreshSchemaAndSignal(connection, future, rs, target, keyspace, name);
22422219 }
@@ -2289,13 +2266,13 @@
22892266 return;
22902267 }
22912268
2292- final ProtocolEvent event = ((Responses.Event)response).event;
2269+ final ProtocolEvent event = ((Responses.Event) response).event;
22932270
22942271 logger.debug("Received event {}, scheduling delivery", response);
22952272
22962273 switch (event.type) {
22972274 case TOPOLOGY_CHANGE:
2298- ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange)event;
2275+ ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange) event;
22992276 InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress());
23002277 Host.statesLogger.debug("[{}] received event {}", tpAddr, tpc.change);
23012278 switch (tpc.change) {
@@ -2311,7 +2288,7 @@
23112288 }
23122289 break;
23132290 case STATUS_CHANGE:
2314- ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange)event;
2291+ ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange) event;
23152292 InetSocketAddress stAddr = translateAddress(stc.node.getAddress());
23162293 Host.statesLogger.debug("[{}] received event {}", stAddr, stc.status);
23172294 switch (stc.status) {
@@ -2327,7 +2304,7 @@
23272304 if (!configuration.getQueryOptions().isMetadataEnabled())
23282305 return;
23292306
2330- ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event;
2307+ ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange) event;
23312308 switch (scc.change) {
23322309 case CREATED:
23332310 case UPDATED:
@@ -2338,7 +2315,7 @@
23382315 switch (scc.targetType) {
23392316 case KEYSPACE:
23402317 final KeyspaceMetadata removedKeyspace = manager.metadata.removeKeyspace(scc.targetKeyspace);
2341- if(removedKeyspace != null) {
2318+ if (removedKeyspace != null) {
23422319 executor.submit(new Runnable() {
23432320 @Override
23442321 public void run() {
@@ -2351,7 +2328,7 @@
23512328 keyspace = manager.metadata.getKeyspaceInternal(scc.targetKeyspace);
23522329 if (keyspace == null)
23532330 logger.warn("Received a DROPPED notification for table {}.{}, but this keyspace is unknown in our metadata",
2354- scc.targetKeyspace, scc.targetName);
2331+ scc.targetKeyspace, scc.targetName);
23552332 else {
23562333 final TableMetadata removedTable = keyspace.removeTable(scc.targetName);
23572334 if (removedTable != null) {
@@ -2368,7 +2345,7 @@
23682345 keyspace = manager.metadata.getKeyspaceInternal(scc.targetKeyspace);
23692346 if (keyspace == null)
23702347 logger.warn("Received a DROPPED notification for UDT {}.{}, but this keyspace is unknown in our metadata",
2371- scc.targetKeyspace, scc.targetName);
2348+ scc.targetKeyspace, scc.targetName);
23722349 else {
23732350 final UserType removedType = keyspace.removeUserType(scc.targetName);
23742351 if (removedType != null) {
@@ -2464,7 +2441,8 @@
24642441 }
24652442
24662443 private class CleanupIdleConnectionsTask implements Runnable {
2467- @Override public void run() {
2444+ @Override
2445+ public void run() {
24682446 try {
24692447 long now = System.currentTimeMillis();
24702448 for (SessionManager session : sessions) {
@@ -2594,7 +2572,7 @@
25942572 // If host already existed, retrieve it and check its state, if it's not up schedule a
25952573 // hostUp event.
25962574 Host existingHost = metadata.getHost(address);
2597- if(!existingHost.isUp())
2575+ if (!existingHost.isUp())
25982576 futures.add(schedule(hostUp(existingHost)));
25992577 }
26002578 break;
@@ -2733,7 +2711,7 @@
27332711
27342712 /**
27352713 * Periodically ensures that closed connections are properly terminated once they have no more pending requests.
2736- *
2714+ * <p/>
27372715 * This is normally done when the connection errors out, or when the last request is processed; this class acts as
27382716 * a last-effort protection since unterminated connections can lead to deadlocks. If it terminates a connection,
27392717 * this indicates a bug; warnings are logged so that this can be reported.
modified driver-core/src/main/java/com/datastax/driver/core/ClusterNameMismatchException.java +1 −1
@@ -30,7 +30,7 @@
3030
3131 public ClusterNameMismatchException(InetSocketAddress address, String actualClusterName, String expectedClusterName) {
3232 super(String.format("[%s] Host %s reports cluster name '%s' that doesn't match our cluster name '%s'. This host will be ignored.",
33- address, address, actualClusterName, expectedClusterName));
33+ address, address, actualClusterName, expectedClusterName));
3434 this.address = address;
3535 this.expectedClusterName = expectedClusterName;
3636 this.actualClusterName = actualClusterName;
modified driver-core/src/main/java/com/datastax/driver/core/ColumnDefinitions.java +23 −30
@@ -15,22 +15,22 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
2018 import com.datastax.driver.core.exceptions.InvalidTypeException;
2119
20+import java.util.*;
21+
2222 /**
2323 * Metadata describing the columns returned in a {@link ResultSet} or a
2424 * {@link PreparedStatement}.
25- * <p>
25+ * <p/>
2626 * A {@code columnDefinitions}} instance is mainly a list of
2727 * {@code ColumnsDefinitions.Definition}. The definitions or metadata for a column
2828 * can be accessed either by:
2929 * <ul>
30- * <li>index (indexed from 0)</li>
31- * <li>name</li>
30+ * <li>index (indexed from 0)</li>
31+ * <li>name</li>
3232 * </ul>
33- * <p>
33+ * <p/>
3434 * When accessed by name, column selection is case insensitive. In case multiple
3535 * columns only differ by the case of their name, then the column returned with
3636 * be the first column that has been defined in CQL without forcing case sensitivity
@@ -38,17 +38,17 @@
3838 * If none of the columns have been defined in this manner, the first column matching
3939 * (with case insensitivity) is returned. You can force the case of a selection
4040 * by double quoting the name.
41- * <p>
41+ * <p/>
4242 * For example:
4343 * <ul>
44- * <li>If {@code cd} contains column {@code fOO}, then {@code cd.contains("foo")},
45- * {@code cd.contains("fOO")} and {@code cd.contains("Foo")} will return {@code true}.</li>
46- * <li>If {@code cd} contains both {@code foo} and {@code FOO} then:
47- * <ul>
48- * <li>{@code cd.getType("foo")}, {@code cd.getType("fOO")} and {@code cd.getType("FOO")}
49- * will all match column {@code foo}.</li>
50- * <li>{@code cd.getType("\"FOO\"")} will match column {@code FOO}</li>
51- * </ul>
44+ * <li>If {@code cd} contains column {@code fOO}, then {@code cd.contains("foo")},
45+ * {@code cd.contains("fOO")} and {@code cd.contains("Foo")} will return {@code true}.</li>
46+ * <li>If {@code cd} contains both {@code foo} and {@code FOO} then:
47+ * <ul>
48+ * <li>{@code cd.getType("foo")}, {@code cd.getType("fOO")} and {@code cd.getType("FOO")}
49+ * will all match column {@code foo}.</li>
50+ * <li>{@code cd.getType("\"FOO\"")} will match column {@code FOO}</li>
51+ * </ul>
5252 * </ul>
5353 * Note that the preceding rules mean that if a {@code ColumnDefinitions} object
5454 * contains multiple occurrences of the exact same name (be it the same column
@@ -69,7 +69,7 @@
6969
7070 for (int i = 0; i < defs.length; i++) {
7171 // Be optimistic, 99% of the time, previous will be null.
72- int[] previous = this.byName.put(defs[i].name.toLowerCase(), new int[]{ i });
72+ int[] previous = this.byName.put(defs[i].name.toLowerCase(), new int[]{i});
7373 if (previous != null) {
7474 int[] indexes = new int[previous.length + 1];
7575 System.arraycopy(previous, 0, indexes, 0, previous.length);
@@ -113,7 +113,7 @@
113113
114114 /**
115115 * Returns an iterator over the {@link Definition} contained in this metadata.
116- *
116+ * <p/>
117117 * The order of the iterator will be the one of this metadata.
118118 *
119119 * @return an iterator over the {@link Definition} contained in this metadata.
@@ -137,7 +137,6 @@
137137 *
138138 * @param i the index in this metadata.
139139 * @return the name of the {@code i}th column in this metadata.
140- *
141140 * @throws IndexOutOfBoundsException if {@code i < 0} or {@code i >= size()}
142141 */
143142 public String getName(int i) {
@@ -149,7 +148,6 @@
149148 *
150149 * @param i the index in this metadata.
151150 * @return the type of the {@code i}th column in this metadata.
152- *
153151 * @throws IndexOutOfBoundsException if {@code i < 0} or {@code i >= size()}
154152 */
155153 public DataType getType(int i) {
@@ -161,7 +159,6 @@
161159 *
162160 * @param name the name of the column.
163161 * @return the type of (the first occurrence of) {@code name} in this metadata.
164- *
165162 * @throws IllegalArgumentException if {@code name} is not in this metadata.
166163 */
167164 public DataType getType(String name) {
@@ -173,7 +170,6 @@
173170 *
174171 * @param i the index in this metadata.
175172 * @return the keyspace of the {@code i}th column in this metadata.
176- *
177173 * @throws IndexOutOfBoundsException if {@code i < 0} or {@code i >= size()}
178174 */
179175 public String getKeyspace(int i) {
@@ -185,7 +181,6 @@
185181 *
186182 * @param name the name of the column.
187183 * @return the keyspace of (the first occurrence of) column {@code name} in this metadata.
188- *
189184 * @throws IllegalArgumentException if {@code name} is not in this metadata.
190185 */
191186 public String getKeyspace(String name) {
@@ -197,7 +192,6 @@
197192 *
198193 * @param i the index in this metadata.
199194 * @return the table of the {@code i}th column in this metadata.
200- *
201195 * @throws IndexOutOfBoundsException if {@code i < 0} or {@code i >= size()}
202196 */
203197 public String getTable(int i) {
@@ -209,7 +203,6 @@
209203 *
210204 * @param name the name of the column.
211205 * @return the table of (the first occurrence of) column {@code name} in this metadata.
212- *
213206 * @throws IllegalArgumentException if {@code name} is not in this metadata.
214207 */
215208 public String getTable(String name) {
@@ -362,19 +355,19 @@
362355
363356 @Override
364357 public final int hashCode() {
365- return Arrays.hashCode(new Object[]{ keyspace, table, name, type});
358+ return Arrays.hashCode(new Object[]{keyspace, table, name, type});
366359 }
367360
368361 @Override
369362 public final boolean equals(Object o) {
370- if(!(o instanceof Definition))
363+ if (!(o instanceof Definition))
371364 return false;
372365
373- Definition other = (Definition)o;
366+ Definition other = (Definition) o;
374367 return keyspace.equals(other.keyspace)
375- && table.equals(other.table)
376- && name.equals(other.name)
377- && type.equals(other.type);
368+ && table.equals(other.table)
369+ && name.equals(other.name)
370+ && type.equals(other.type);
378371 }
379372 }
380373 }
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +23 −27
@@ -15,15 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.Collections;
20-import java.util.HashMap;
21-import java.util.Iterator;
22-import java.util.Map;
23-import java.util.Map.Entry;
24-
2518 import com.google.common.base.Objects;
2619
20+import java.util.*;
21+import java.util.Map.Entry;
22+
2723 /**
2824 * Describes a Column.
2925 */
@@ -116,7 +112,7 @@
116112 if (o == null || getClass() != o.getClass())
117113 return false;
118114
119- ColumnMetadata that = (ColumnMetadata)o;
115+ ColumnMetadata that = (ColumnMetadata) o;
120116
121117 if (isStatic != that.isStatic)
122118 return false;
@@ -176,7 +172,7 @@
176172
177173 /**
178174 * Returns whether this index is a custom one.
179- * <p>
175+ * <p/>
180176 * If it is indeed a custom index, {@link #getIndexClassName} will
181177 * return the name of the class used in Cassandra to implement that
182178 * index.
@@ -200,7 +196,7 @@
200196 /**
201197 * Return whether this index is a 'KEYS' index on a map, e.g.,
202198 * CREATE INDEX ON mytable (KEYS(mymap))
203- *
199+ *
204200 * @return {@code true} if this is a 'KEYS' index on a map.
205201 */
206202 public boolean isKeys() {
@@ -210,7 +206,7 @@
210206 /**
211207 * Return whether this index is a 'FULL' index on a frozen collection, e.g.,
212208 * CREATE INDEX ON mytable (FULL(mymap))
213- *
209+ *
214210 * @return {@code true} if this is a 'FULL' index on a frozen collection.
215211 */
216212 public boolean isFull() {
@@ -219,15 +215,15 @@
219215 * in IndexTarget#fromColumnDefinition.
220216 */
221217 return !isKeys()
222- && !isEntries()
223- && column.getType().isCollection()
224- && column.getType().isFrozen();
218+ && !isEntries()
219+ && column.getType().isCollection()
220+ && column.getType().isFrozen();
225221 }
226222
227223 /**
228224 * Return whether this index is a 'ENTRIES' index on a map, e.g.,
229225 * CREATE INDEX ON mytable (ENTRIES(mymap))
230- *
226+ *
231227 * @return {@code true} if this is an 'ENTRIES' index on a map.
232228 */
233229 public boolean isEntries() {
@@ -236,7 +232,7 @@
236232
237233 /**
238234 * Return the value for the given option name.
239- *
235+ *
240236 * @param name Option name
241237 * @return Option value
242238 */
@@ -246,7 +242,7 @@
246242
247243 /**
248244 * Returns a CQL query representing this index.
249- *
245+ * <p/>
250246 * This method returns a single 'CREATE INDEX' query corresponding to
251247 * this index definition.
252248 *
@@ -258,16 +254,16 @@
258254 String cfName = Metadata.escapeId(table.getName());
259255 String colName = Metadata.escapeId(column.getName());
260256 return isCustomIndex()
261- ? String.format("CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s' WITH OPTIONS = %s;",
257+ ? String.format("CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s' WITH OPTIONS = %s;",
262258 name, ksName, cfName, colName, getIndexClassName(), getOptionsAsCql())
263- : String.format("CREATE INDEX %s ON %s.%s (%s);", name, ksName, cfName, getIndexFunction(colName));
259+ : String.format("CREATE INDEX %s ON %s.%s (%s);", name, ksName, cfName, getIndexFunction(colName));
264260 }
265261
266262 /**
267263 * Builds a string representation of the custom index options.
268- *
264+ *
269265 * @return String representation of the custom index options, similar to what Cassandra stores in
270- * the 'index_options' column of the 'schema_columns' table in the 'system' keyspace.
266+ * the 'index_options' column of the 'schema_columns' table in the 'system' keyspace.
271267 */
272268 private String getOptionsAsCql() {
273269 StringBuilder builder = new StringBuilder();
@@ -286,7 +282,7 @@
286282 /**
287283 * Wraps the column name with the appropriate index function (KEYS, FULL, ENTRIES),
288284 * if necessary.
289- *
285+ *
290286 * @return Column name wrapped with the appropriate index function.
291287 */
292288 private String getIndexFunction(String colName) {
@@ -306,10 +302,10 @@
306302 if (o == null || getClass() != o.getClass())
307303 return false;
308304
309- IndexMetadata that = (IndexMetadata)o;
305+ IndexMetadata that = (IndexMetadata) o;
310306
311307 return this.name.equals(that.name)
312- && Objects.equal(this.indexOptions, that.indexOptions);
308+ && Objects.equal(this.indexOptions, that.indexOptions);
313309 }
314310
315311 @Override
@@ -347,7 +343,7 @@
347343 // Temporary class that is used to make building the schema easier. Not meant to be
348344 // exposed publicly at all.
349345 static class Raw {
350- public enum Kind { PARTITION_KEY, CLUSTERING_KEY, REGULAR, COMPACT_VALUE, STATIC }
346+ public enum Kind {PARTITION_KEY, CLUSTERING_KEY, REGULAR, COMPACT_VALUE, STATIC}
351347
352348 public final String name;
353349 public final Kind kind;
@@ -369,8 +365,8 @@
369365
370366 String name = row.getString(COLUMN_NAME);
371367 Kind kind = version.getMajor() < 2 || row.isNull(KIND)
372- ? Kind.REGULAR
373- : Enum.valueOf(Kind.class, row.getString(KIND).toUpperCase());
368+ ? Kind.REGULAR
369+ : Enum.valueOf(Kind.class, row.getString(KIND).toUpperCase());
374370 int componentIndex = row.isNull(COMPONENT_INDEX) ? 0 : row.getInt(COMPONENT_INDEX);
375371 String validatorStr = row.getString(VALIDATOR);
376372 boolean reversed = CassandraTypeParser.isReversed(validatorStr);
modified driver-core/src/main/java/com/datastax/driver/core/Configuration.java +22 −21
@@ -21,12 +21,12 @@
2121 * The configuration of the cluster.
2222 * It configures the following:
2323 * <ul>
24- * <li>Cassandra protocol level configuration (compression).</li>
25- * <li>Connection pooling configurations.</li>
26- * <li>low-level TCP configuration options (tcpNoDelay, keepAlive, ...).</li>
27- * <li>Metrics related options.</li>
28- * <li>Query related options (default consistency level, fetchSize, ...).</li>
29- * <li>Netty layer customization options.</li>
24+ * <li>Cassandra protocol level configuration (compression).</li>
25+ * <li>Connection pooling configurations.</li>
26+ * <li>low-level TCP configuration options (tcpNoDelay, keepAlive, ...).</li>
27+ * <li>Metrics related options.</li>
28+ * <li>Query related options (default consistency level, fetchSize, ...).</li>
29+ * <li>Netty layer customization options.</li>
3030 * </ul>
3131 * This is also where you get the configured policies, though those cannot be changed
3232 * (they are set during the built of the Cluster object).
@@ -47,24 +47,24 @@
4747 */
4848 public Configuration() {
4949 this(Policies.builder().build(),
50- new ProtocolOptions(),
51- new PoolingOptions(),
52- new SocketOptions(),
53- new MetricsOptions(),
54- new QueryOptions(),
55- NettyOptions.DEFAULT_INSTANCE);
50+ new ProtocolOptions(),
51+ new PoolingOptions(),
52+ new SocketOptions(),
53+ new MetricsOptions(),
54+ new QueryOptions(),
55+ NettyOptions.DEFAULT_INSTANCE);
5656 }
5757
5858 /**
5959 * Creates a configuration with the specified parameters.
60- *
61- * @param policies the policies to use
60+ *
61+ * @param policies the policies to use
6262 * @param protocolOptions the protocol options to use
63- * @param poolingOptions the pooling options to use
64- * @param socketOptions the socket options to use
65- * @param metricsOptions the metrics options, or null to disable metrics.
66- * @param queryOptions defaults related to queries.
67- * @param nettyOptions the {@link NettyOptions} instance to use
63+ * @param poolingOptions the pooling options to use
64+ * @param socketOptions the socket options to use
65+ * @param metricsOptions the metrics options, or null to disable metrics.
66+ * @param queryOptions defaults related to queries.
67+ * @param nettyOptions the {@link NettyOptions} instance to use
6868 */
6969 public Configuration(Policies policies,
7070 ProtocolOptions protocolOptions,
@@ -93,7 +93,7 @@
9393 MetricsOptions metricsOptions,
9494 QueryOptions queryOptions) {
9595 this(policies, protocolOptions, poolingOptions, socketOptions, metricsOptions, queryOptions,
96- NettyOptions.DEFAULT_INSTANCE);
96+ NettyOptions.DEFAULT_INSTANCE);
9797 }
9898
9999 void register(Cluster.Manager manager) {
@@ -140,7 +140,7 @@
140140
141141 /**
142142 * Returns the metrics configuration, if metrics are enabled.
143- * <p>
143+ * <p/>
144144 * Metrics collection is enabled by default but can be disabled at cluster
145145 * construction time through {@link Cluster.Builder#withoutMetrics}.
146146 *
@@ -161,6 +161,7 @@
161161
162162 /**
163163 * Returns the {@link NettyOptions} instance for this configuration.
164+ *
164165 * @return the {@link NettyOptions} instance for this configuration.
165166 */
166167 public NettyOptions getNettyOptions() {
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +91 −90
@@ -15,17 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.lang.ref.WeakReference;
19-import java.net.InetSocketAddress;
20-import java.util.HashSet;
21-import java.util.Iterator;
22-import java.util.List;
23-import java.util.Queue;
24-import java.util.concurrent.*;
25-import java.util.concurrent.atomic.AtomicBoolean;
26-import java.util.concurrent.atomic.AtomicInteger;
27-import java.util.concurrent.atomic.AtomicReference;
28-
18+import com.datastax.driver.core.Responses.Result.SetKeyspace;
19+import com.datastax.driver.core.exceptions.AuthenticationException;
20+import com.datastax.driver.core.exceptions.DriverException;
21+import com.datastax.driver.core.exceptions.DriverInternalError;
22+import com.datastax.driver.core.utils.MoreFutures;
2923 import com.google.common.annotations.VisibleForTesting;
3024 import com.google.common.collect.Lists;
3125 import com.google.common.collect.MapMaker;
@@ -42,19 +36,23 @@
4236 import io.netty.util.Timer;
4337 import io.netty.util.TimerTask;
4438 import io.netty.util.concurrent.GlobalEventExecutor;
45-import javax.net.ssl.SSLEngine;
4639 import org.slf4j.Logger;
4740 import org.slf4j.LoggerFactory;
4841
49-import static io.netty.handler.timeout.IdleState.ALL_IDLE;
50-
51-import com.datastax.driver.core.Responses.Result.SetKeyspace;
52-import com.datastax.driver.core.exceptions.AuthenticationException;
53-import com.datastax.driver.core.exceptions.DriverException;
54-import com.datastax.driver.core.exceptions.DriverInternalError;
55-import com.datastax.driver.core.utils.MoreFutures;
42+import javax.net.ssl.SSLEngine;
43+import java.lang.ref.WeakReference;
44+import java.net.InetSocketAddress;
45+import java.util.HashSet;
46+import java.util.Iterator;
47+import java.util.List;
48+import java.util.Queue;
49+import java.util.concurrent.*;
50+import java.util.concurrent.atomic.AtomicBoolean;
51+import java.util.concurrent.atomic.AtomicInteger;
52+import java.util.concurrent.atomic.AtomicReference;
5653
5754 import static com.datastax.driver.core.Message.Response.Type.ERROR;
55+import static io.netty.handler.timeout.IdleState.ALL_IDLE;
5856
5957 // For LoggingHandler
6058 //import org.jboss.netty.handler.logging.LoggingHandler;
@@ -70,7 +68,7 @@
7068
7169 private static final boolean DISABLE_COALESCING = SystemProperties.getBoolean("com.datastax.driver.DISABLE_COALESCING", false);
7270
73- enum State {OPEN, TRASHED, RESURRECTING, GONE }
71+ enum State {OPEN, TRASHED, RESURRECTING, GONE}
7472
7573 final AtomicReference<State> state = new AtomicReference<State>(State.OPEN);
7674
@@ -100,14 +98,14 @@
10098 private final AtomicReference<Owner> ownerRef = new AtomicReference<Owner>();
10199
102100 /**
103- /**
101+ * /**
104102 * Create a new connection to a Cassandra node and associate it with the given pool.
105103 *
106- * @param name the connection name
104+ * @param name the connection name
107105 * @param address the remote address
108106 * @param factory the connection factory to use
109- * @param owner the component owning this connection (may be null).
110- * Note that an existing connection can also be associated to an owner later with {@link #setOwner(Owner)}.
107+ * @param owner the component owning this connection (may be null).
108+ * Note that an existing connection can also be associated to an owner later with {@link #setOwner(Owner)}.
111109 */
112110 protected Connection(String name, InetSocketAddress address, Factory factory, Owner owner) {
113111 this.address = address;
@@ -135,9 +133,9 @@
135133 Bootstrap bootstrap = factory.newBootstrap();
136134 ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
137135 bootstrap.handler(
138- new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(),
139- factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
140- factory.configuration.getNettyOptions()));
136+ new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(),
137+ factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
138+ factory.configuration.getNettyOptions()));
141139
142140 ChannelFuture future = bootstrap.connect(address);
143141
@@ -176,7 +174,7 @@
176174 Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor();
177175
178176 ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture,
179- onChannelReady(protocolVersion, initExecutor), initExecutor);
177+ onChannelReady(protocolVersion, initExecutor), initExecutor);
180178
181179
182180 // Fallback on initializeTransportFuture so we can properly propagate specific exceptions.
@@ -192,10 +190,10 @@
192190 } else {
193191 // Defunct to ensure that the error will be signaled (marking the host down)
194192 Exception e = (t instanceof ConnectionException || t instanceof DriverException || t instanceof InterruptedException)
195- ? (Exception)t
196- : new ConnectionException(Connection.this.address,
197- String.format("Unexpected error during transport initialization (%s)", t),
198- t);
193+ ? (Exception) t
194+ : new ConnectionException(Connection.this.address,
195+ String.format("Unexpected error during transport initialization (%s)", t),
196+ t);
199197 future.setException(defunct(e));
200198 }
201199 return future;
@@ -219,8 +217,8 @@
219217 if (t == null)
220218 return "";
221219 String msg = t.getMessage() == null || t.getMessage().isEmpty()
222- ? t.toString()
223- : t.getMessage();
220+ ? t.toString()
221+ : t.getMessage();
224222 return " (" + msg + ')';
225223 }
226224
@@ -231,7 +229,7 @@
231229 ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
232230 Future startupResponseFuture = write(new Requests.Startup(compression));
233231 return Futures.transform(startupResponseFuture,
234- onStartupResponse(protocolVersion, initExecutor), initExecutor);
232+ onStartupResponse(protocolVersion, initExecutor), initExecutor);
235233 }
236234 };
237235 }
@@ -244,7 +242,7 @@
244242 case READY:
245243 return checkClusterName(protocolVersion, initExecutor);
246244 case ERROR:
247- Responses.Error error = (Responses.Error)response;
245+ Responses.Error error = (Responses.Error) response;
248246 // Testing for a specific string is a tad fragile but well, we don't have much choice
249247 if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version"))
250248 throw unsupportedProtocolVersionException(protocolVersion, error.serverProtocolVersion);
@@ -287,17 +285,17 @@
287285 try {
288286 write(clusterNameFuture);
289287 return Futures.transform(clusterNameFuture,
290- new AsyncFunction<ResultSet, Void>() {
291- @Override
292- public ListenableFuture<Void> apply(ResultSet rs) throws Exception {
293- Row row = rs.one();
294- String actual = row.getString("cluster_name");
295- if (!expected.equals(actual))
296- throw new ClusterNameMismatchException(address, actual, expected);
297- markInitialized();
298- return MoreFutures.VOID_SUCCESS;
299- }
300- }, executor);
288+ new AsyncFunction<ResultSet, Void>() {
289+ @Override
290+ public ListenableFuture<Void> apply(ResultSet rs) throws Exception {
291+ Row row = rs.one();
292+ String actual = row.getString("cluster_name");
293+ if (!expected.equals(actual))
294+ throw new ClusterNameMismatchException(address, actual, expected);
295+ markInitialized();
296+ return MoreFutures.VOID_SUCCESS;
297+ }
298+ }, executor);
301299 } catch (Exception e) {
302300 return Futures.immediateFailedFuture(e);
303301 }
@@ -309,23 +307,23 @@
309307 }
310308
311309 private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final ProtocolVersion protocolVersion, final Executor executor) {
312- Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials());
310+ Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator) authenticator).getCredentials());
313311 try {
314312 Future authResponseFuture = write(creds);
315313 return Futures.transform(authResponseFuture,
316- new AsyncFunction<Message.Response, Void>() {
317- @Override
318- public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
319- switch (authResponse.type) {
320- case READY:
321- return checkClusterName(protocolVersion, executor);
322- case ERROR:
323- throw new AuthenticationException(address, ((Responses.Error)authResponse).message);
324- default:
325- throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type));
314+ new AsyncFunction<Message.Response, Void>() {
315+ @Override
316+ public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
317+ switch (authResponse.type) {
318+ case READY:
319+ return checkClusterName(protocolVersion, executor);
320+ case ERROR:
321+ throw new AuthenticationException(address, ((Responses.Error) authResponse).message);
322+ default:
323+ throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type));
324+ }
326325 }
327- }
328- }, executor);
326+ }, executor);
329327 } catch (Exception e) {
330328 return Futures.immediateFailedFuture(e);
331329 }
@@ -351,10 +349,10 @@
351349 switch (authResponse.type) {
352350 case AUTH_SUCCESS:
353351 logger.trace("{} Authentication complete", this);
354- authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token);
352+ authenticator.onAuthenticationSuccess(((Responses.AuthSuccess) authResponse).token);
355353 return checkClusterName(protocolVersion, executor);
356354 case AUTH_CHALLENGE:
357- byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token);
355+ byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge) authResponse).token);
358356 if (responseToServer == null) {
359357 // If we generate a null response, then authentication has completed, proceed without
360358 // sending a further response back to the server.
@@ -371,10 +369,10 @@
371369 // attempted v2 auth against a server which only supports v1
372370 // The AIOOBE indicates that the server didn't recognise the
373371 // initial AuthResponse message
374- String message = ((Responses.Error)authResponse).message;
372+ String message = ((Responses.Error) authResponse).message;
375373 if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15"))
376374 message = String.format("Cannot use authenticator %s with protocol version 1, "
377- + "only plain text authentication is supported with this protocol version", authenticator);
375+ + "only plain text authentication is supported with this protocol version", authenticator);
378376 throw new AuthenticationException(address, message);
379377 default:
380378 throw new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type));
@@ -439,14 +437,14 @@
439437 throw defunct(e);
440438 } catch (BusyConnectionException e) {
441439 logger.warn("Tried to set the keyspace on busy {}. "
442- + "This should not happen but is not critical (it will be retried)", this);
440+ + "This should not happen but is not critical (it will be retried)", this);
443441 throw new ConnectionException(address, "Tried to set the keyspace on busy connection");
444442 } catch (ExecutionException e) {
445443 Throwable cause = e.getCause();
446444 if (cause instanceof OperationTimedOutException) {
447445 // Rethrow so that the caller doesn't try to use the connection, but do not defunct as we don't want to mark down
448446 logger.warn("Timeout while setting keyspace on {}. "
449- + "This should not happen but is not critical (it will be retried)", this);
447+ + "This should not happen but is not critical (it will be retried)", this);
450448 throw new ConnectionException(address, "Timeout while setting keyspace on connection");
451449 } else {
452450 throw defunct(new ConnectionException(address, "Error while setting keyspace", cause));
@@ -462,11 +460,11 @@
462460 @Override
463461 public ListenableFuture<Void> apply(Message.Response response) throws Exception {
464462 if (response instanceof SetKeyspace) {
465- Connection.this.keyspace = ((SetKeyspace)response).keyspace;
463+ Connection.this.keyspace = ((SetKeyspace) response).keyspace;
466464 return MoreFutures.VOID_SUCCESS;
467465 } else if (response.type == ERROR) {
468466 closeAsync().force();
469- Responses.Error error = (Responses.Error)response;
467+ Responses.Error error = (Responses.Error) response;
470468 throw error.asException(address);
471469 } else {
472470 closeAsync().force();
@@ -481,9 +479,8 @@
481479 *
482480 * @param request the request to send
483481 * @return a future on the server response
484- *
485482 * @throws ConnectionException if the connection is closed
486- * @throws TransportException if an I/O error while sending the request
483+ * @throws TransportException if an I/O error while sending the request
487484 */
488485 public Future write(Message.Request request) throws ConnectionException, BusyConnectionException {
489486 Future future = new Future(request);
@@ -577,7 +574,9 @@
577574 return this.ownerRef.get() != null;
578575 }
579576
580- /** @return whether the connection was already associated with an owner */
577+ /**
578+ * @return whether the connection was already associated with an owner
579+ */
581580 boolean setOwner(Owner owner) {
582581 return ownerRef.compareAndSet(null, owner);
583582 }
@@ -589,7 +588,7 @@
589588 void release() {
590589 Owner owner = ownerRef.get();
591590 if (owner instanceof HostConnectionPool)
592- ((HostConnectionPool)owner).returnConnection(this);
591+ ((HostConnectionPool) owner).returnConnection(this);
593592 }
594593
595594 public boolean isClosed() {
@@ -598,13 +597,12 @@
598597
599598 /**
600599 * Closes the connection: no new writes will be accepted after this method has returned.
601- *
600+ * <p/>
602601 * However, a closed connection might still have ongoing queries awaiting for their result.
603602 * When all these ongoing queries have completed, the underlying channel will be closed; we
604603 * refer to this final state as "terminated".
605604 *
606605 * @return a future that will complete once the connection has terminated.
607- *
608606 * @see #tryTerminate(boolean)
609607 */
610608 public CloseFuture closeAsync() {
@@ -644,12 +642,11 @@
644642
645643 /**
646644 * Tries to terminate a closed connection, i.e. release system resources.
647- *
645+ * <p/>
648646 * This is called both by "normal" code and by {@link Cluster.ConnectionReaper}.
649647 *
650648 * @param force whether to proceed if there are still outstanding requests.
651649 * @return whether the connection has actually terminated.
652- *
653650 * @see #closeAsync()
654651 */
655652 boolean tryTerminate(boolean force) {
@@ -719,7 +716,6 @@
719716 * Opens a new connection to the node this factory points to.
720717 *
721718 * @return the newly created (and initialized) connection.
722- *
723719 * @throws ConnectionException if connection attempt fails.
724720 */
725721 public Connection open(Host host) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
@@ -771,15 +767,15 @@
771767 static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
772768 Throwable t = e.getCause();
773769 if (t instanceof ConnectionException)
774- throw (ConnectionException)t;
770+ throw (ConnectionException) t;
775771 if (t instanceof InterruptedException)
776- throw (InterruptedException)t;
772+ throw (InterruptedException) t;
777773 if (t instanceof UnsupportedProtocolVersionException)
778- throw (UnsupportedProtocolVersionException)t;
774+ throw (UnsupportedProtocolVersionException) t;
779775 if (t instanceof ClusterNameMismatchException)
780- throw (ClusterNameMismatchException)t;
776+ throw (ClusterNameMismatchException) t;
781777 if (t instanceof DriverException)
782- throw (DriverException)t;
778+ throw (DriverException) t;
783779
784780 return new RuntimeException("Unexpected exception during connection initialization", t);
785781 }
@@ -802,7 +798,7 @@
802798 private Bootstrap newBootstrap() {
803799 Bootstrap b = new Bootstrap();
804800 b.group(eventLoopGroup)
805- .channel(channelClass);
801+ .channel(channelClass);
806802
807803 SocketOptions options = configuration.getSocketOptions();
808804
@@ -900,7 +896,7 @@
900896 }
901897
902898 private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new MapMaker()
903- .concurrencyLevel(16)
899+ .concurrencyLevel(16)
904900 .weakKeys()
905901 .makeMap();
906902
@@ -979,7 +975,7 @@
979975 protected void channelRead0(ChannelHandlerContext ctx, Message.Response response) throws Exception {
980976 int streamId = response.getStreamId();
981977
982- if(logger.isTraceEnabled())
978+ if (logger.isTraceEnabled())
983979 logger.trace("{}, stream {}, received: {}", Connection.this, streamId, asDebugString(response));
984980
985981 if (streamId < 0) {
@@ -1002,7 +998,7 @@
1002998 streamIdHandler.unmark(streamId);
1003999 if (logger.isDebugEnabled())
10041000 logger.debug("{} Response received on stream {} but no handler set anymore (either the request has "
1005- + "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
1001+ + "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
10061002 return;
10071003 }
10081004 handler.cancelTimeout();
@@ -1016,7 +1012,7 @@
10161012
10171013 @Override
10181014 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
1019- if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) {
1015+ if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == ALL_IDLE) {
10201016 logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
10211017 write(HEARTBEAT_CALLBACK);
10221018 }
@@ -1048,8 +1044,7 @@
10481044
10491045 public void errorOutAllHandler(ConnectionException ce) {
10501046 Iterator<ResponseHandler> iter = pending.values().iterator();
1051- while (iter.hasNext())
1052- {
1047+ while (iter.hasNext()) {
10531048 ResponseHandler handler = iter.next();
10541049 handler.cancelTimeout();
10551050 handler.callback.onException(Connection.this, ce, System.nanoTime() - handler.startTime, handler.retryCount);
@@ -1202,9 +1197,13 @@
12021197
12031198 interface ResponseCallback {
12041199 public Message.Request request();
1200+
12051201 public int retryCount();
1202+
12061203 public void onSet(Connection connection, Message.Response response, long latency, int retryCount);
1204+
12071205 public void onException(Connection connection, Exception exception, long latency, int retryCount);
1206+
12081207 public boolean onTimeout(Connection connection, long latency, int retryCount);
12091208 }
12101209
@@ -1336,7 +1335,9 @@
13361335 }
13371336 }
13381337
1339- /** A component that "owns" a connection, and should be notified when it dies. */
1338+ /**
1339+ * A component that "owns" a connection, and should be notified when it dies.
1340+ */
13401341 interface Owner {
13411342 void onConnectionDefunct(Connection connection);
13421343 }
modified driver-core/src/main/java/com/datastax/driver/core/ConnectionException.java +2 −4
@@ -23,14 +23,12 @@
2323
2424 public final InetSocketAddress address;
2525
26- public ConnectionException(InetSocketAddress address, String msg, Throwable cause)
27- {
26+ public ConnectionException(InetSocketAddress address, String msg, Throwable cause) {
2827 super(msg, cause);
2928 this.address = address;
3029 }
3130
32- public ConnectionException(InetSocketAddress address, String msg)
33- {
31+ public ConnectionException(InetSocketAddress address, String msg) {
3432 super(msg);
3533 this.address = address;
3634 }
modified driver-core/src/main/java/com/datastax/driver/core/ConsistencyLevel.java +12 −11
@@ -19,21 +19,22 @@
1919
2020 public enum ConsistencyLevel {
2121
22- ANY (0),
23- ONE (1),
24- TWO (2),
25- THREE (3),
26- QUORUM (4),
27- ALL (5),
28- LOCAL_QUORUM (6),
29- EACH_QUORUM (7),
30- SERIAL (8),
31- LOCAL_SERIAL (9),
32- LOCAL_ONE (10);
22+ ANY(0),
23+ ONE(1),
24+ TWO(2),
25+ THREE(3),
26+ QUORUM(4),
27+ ALL(5),
28+ LOCAL_QUORUM(6),
29+ EACH_QUORUM(7),
30+ SERIAL(8),
31+ LOCAL_SERIAL(9),
32+ LOCAL_ONE(10);
3333
3434 // Used by the native protocol
3535 final int code;
3636 private static final ConsistencyLevel[] codeIdx;
37+
3738 static {
3839 int maxCode = -1;
3940 for (ConsistencyLevel cl : ConsistencyLevel.values())
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +37 −39
@@ -15,26 +15,24 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.net.InetSocketAddress;
20-import java.net.UnknownHostException;
21-import java.util.*;
22-import java.util.concurrent.*;
23-import java.util.concurrent.atomic.AtomicReference;
24-
18+import com.datastax.driver.core.exceptions.DriverException;
19+import com.datastax.driver.core.exceptions.DriverInternalError;
20+import com.datastax.driver.core.exceptions.NoHostAvailableException;
2521 import com.google.common.annotations.VisibleForTesting;
2622 import com.google.common.base.Objects;
2723 import com.google.common.util.concurrent.ListenableFuture;
2824 import org.slf4j.Logger;
2925 import org.slf4j.LoggerFactory;
3026
31-import com.datastax.driver.core.exceptions.DriverException;
32-import com.datastax.driver.core.exceptions.DriverInternalError;
33-import com.datastax.driver.core.exceptions.NoHostAvailableException;
27+import java.net.InetAddress;
28+import java.net.InetSocketAddress;
29+import java.net.UnknownHostException;
30+import java.util.*;
31+import java.util.concurrent.ExecutionException;
32+import java.util.concurrent.TimeUnit;
33+import java.util.concurrent.atomic.AtomicReference;
3434
35-import static com.datastax.driver.core.SchemaElement.KEYSPACE;
36-import static com.datastax.driver.core.SchemaElement.TABLE;
37-import static com.datastax.driver.core.SchemaElement.TYPE;
35+import static com.datastax.driver.core.SchemaElement.*;
3836
3937 class ControlConnection implements Host.StateListener, Connection.Owner {
4038
@@ -103,8 +101,8 @@
103101 Host connectedHost() {
104102 Connection current = connectionRef.get();
105103 return (current == null)
106- ? null
107- : cluster.metadata.getHost(current.address);
104+ ? null
105+ : cluster.metadata.getHost(current.address);
108106 }
109107
110108 void triggerReconnect() {
@@ -266,9 +264,9 @@
266264 try {
267265 logger.trace("[Control connection] Registering for events");
268266 List<ProtocolEvent.Type> evs = Arrays.asList(
269- ProtocolEvent.Type.TOPOLOGY_CHANGE,
270- ProtocolEvent.Type.STATUS_CHANGE,
271- ProtocolEvent.Type.SCHEMA_CHANGE
267+ ProtocolEvent.Type.TOPOLOGY_CHANGE,
268+ ProtocolEvent.Type.STATUS_CHANGE,
269+ ProtocolEvent.Type.SCHEMA_CHANGE
272270 );
273271 connection.write(new Requests.Register(evs));
274272
@@ -305,8 +303,8 @@
305303
306304 public void refreshSchema(SchemaElement targetType, String targetKeyspace, String targetName) throws InterruptedException {
307305 logger.debug("[Control connection] Refreshing schema for {}{}",
308- targetType == null ? "everything" : targetKeyspace,
309- (targetType == KEYSPACE) ? "" : "." + targetName + " (" + targetType + ")");
306+ targetType == null ? "everything" : targetKeyspace,
307+ (targetType == KEYSPACE) ? "" : "." + targetName + " (" + targetType + ")");
310308 try {
311309 Connection c = connectionRef.get();
312310 // At startup, when we add the initial nodes, this will be null, which is ok
@@ -341,7 +339,7 @@
341339 if (host == null || host.getCassandraVersion() == null) {
342340 cassandraVersion = cluster.protocolVersion().minCassandraVersion();
343341 logger.warn("Cannot find Cassandra version for host {} to parse the schema, using {} based on protocol version in use. "
344- + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion);
342+ + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion);
345343 } else {
346344 cassandraVersion = host.getCassandraVersion();
347345 }
@@ -358,17 +356,17 @@
358356
359357 boolean isSchemaOrKeyspace = (targetType == null || targetType == KEYSPACE);
360358 DefaultResultSetFuture ksFuture = isSchemaOrKeyspace
361- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_KEYSPACES + whereClause))
362- : null;
359+ ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_KEYSPACES + whereClause))
360+ : null;
363361 DefaultResultSetFuture udtFuture = (isSchemaOrKeyspace && supportsUdts(cassandraVersion) || targetType == TYPE)
364- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_USERTYPES + whereClause))
365- : null;
362+ ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_USERTYPES + whereClause))
363+ : null;
366364 DefaultResultSetFuture cfFuture = (isSchemaOrKeyspace || targetType == TABLE)
367- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_COLUMN_FAMILIES + whereClause))
368- : null;
365+ ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_COLUMN_FAMILIES + whereClause))
366+ : null;
369367 DefaultResultSetFuture colsFuture = (isSchemaOrKeyspace || targetType == TABLE)
370- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_COLUMNS + whereClause))
371- : null;
368+ ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_COLUMNS + whereClause))
369+ : null;
372370
373371 if (ksFuture != null)
374372 connection.write(ksFuture);
@@ -381,11 +379,11 @@
381379
382380 try {
383381 cluster.metadata.rebuildSchema(targetType, targetKeyspace, targetName,
384- ksFuture == null ? null : ksFuture.get(),
385- udtFuture == null ? null : udtFuture.get(),
386- cfFuture == null ? null : cfFuture.get(),
387- colsFuture == null ? null : colsFuture.get(),
388- cassandraVersion);
382+ ksFuture == null ? null : ksFuture.get(),
383+ udtFuture == null ? null : udtFuture.get(),
384+ cfFuture == null ? null : cfFuture.get(),
385+ colsFuture == null ? null : colsFuture.get(),
386+ cassandraVersion);
389387 } catch (RuntimeException e) {
390388 // Failure to parse the schema is definitively wrong so log a full-on error, but this won't generally prevent queries to
391389 // work and this can happen when new Cassandra versions modify stuff in the schema and the driver hasn't yet be modified.
@@ -447,8 +445,8 @@
447445 boolean isConnectedHost = c.address.equals(host.getSocketAddress());
448446 if (isConnectedHost || host.listenAddress != null) {
449447 DefaultResultSetFuture future = isConnectedHost
450- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_LOCAL))
451- : new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS + " WHERE peer='" + host.listenAddress.getHostAddress() + '\''));
448+ ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_LOCAL))
449+ : new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS + " WHERE peer='" + host.listenAddress.getHostAddress() + '\''));
452450 c.write(future);
453451 return future.get().one();
454452 }
@@ -529,8 +527,8 @@
529527 String version = row.getString("release_version");
530528 // We don't know if it's a 'local' or a 'peers' row, and only 'peers' rows have the 'peer' field.
531529 InetAddress listenAddress = row.getColumnDefinitions().contains("peer")
532- ? row.getInet("peer")
533- : null;
530+ ? row.getInet("peer")
531+ : null;
534532
535533 host.setVersionAndListenAdress(version, listenAddress);
536534 }
@@ -722,7 +720,7 @@
722720
723721 if (current != null && current.address.equals(host.getSocketAddress())) {
724722 logger.debug("[Control connection] {} is down/removed and it was the control host, triggering reconnect",
725- current.address);
723+ current.address);
726724 if (!current.isClosed())
727725 current.closeAsync();
728726 backgroundReconnect(0);
modified driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +4 −4
@@ -15,16 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.policies.ReconnectionPolicy;
19+
1820 import java.util.concurrent.atomic.AtomicInteger;
1921
2022 import static java.util.concurrent.TimeUnit.MILLISECONDS;
2123 import static java.util.concurrent.TimeUnit.NANOSECONDS;
2224
23-import com.datastax.driver.core.policies.ReconnectionPolicy;
24-
2525 /**
2626 * The policy with which to decide whether a host should be considered down.
27- *
27+ * <p/>
2828 * TODO: this class is fully abstract (rather than an interface) because I'm
2929 * not sure it's worth exposing (and if we do expose it, we need to expose
3030 * ConnectionException). Maybe just exposing say a threshold of error before
@@ -127,7 +127,7 @@
127127 @Override
128128 boolean canReconnectNow() {
129129 return nextReconnectionTime == Long.MIN_VALUE ||
130- System.nanoTime() >= nextReconnectionTime;
130+ System.nanoTime() >= nextReconnectionTime;
131131 }
132132
133133 static class Factory implements ConvictionPolicy.Factory {
modified driver-core/src/main/java/com/datastax/driver/core/DataType.java +130 −136
@@ -15,20 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.math.BigDecimal;
19-import java.math.BigInteger;
20-import java.net.InetAddress;
21-import java.nio.ByteBuffer;
22-import java.util.*;
23-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+import com.datastax.driver.core.exceptions.InvalidTypeException;
2420 import com.google.common.base.Objects;
2521 import com.google.common.collect.ImmutableList;
2622 import com.google.common.collect.ImmutableSet;
2723 import com.google.common.reflect.TypeToken;
2824 import io.netty.buffer.ByteBuf;
2925
30-import com.datastax.driver.core.exceptions.DriverInternalError;
31-import com.datastax.driver.core.exceptions.InvalidTypeException;
26+import java.math.BigDecimal;
27+import java.math.BigInteger;
28+import java.net.InetAddress;
29+import java.nio.ByteBuffer;
30+import java.util.*;
3231
3332 /**
3433 * Data types supported by cassandra.
@@ -40,33 +39,34 @@
4039 */
4140 public enum Name {
4241
43- ASCII (1, String.class),
44- BIGINT (2, Long.class),
45- BLOB (3, ByteBuffer.class),
46- BOOLEAN (4, Boolean.class),
47- COUNTER (5, Long.class),
48- DECIMAL (6, BigDecimal.class),
49- DOUBLE (7, Double.class),
50- FLOAT (8, Float.class),
51- INET (16, InetAddress.class),
52- INT (9, Integer.class),
53- TEXT (10, String.class),
54- TIMESTAMP (11, Date.class),
55- UUID (12, UUID.class),
56- VARCHAR (13, String.class),
57- VARINT (14, BigInteger.class),
58- TIMEUUID (15, UUID.class),
59- LIST (32, List.class),
60- SET (34, Set.class),
61- MAP (33, Map.class),
62- UDT (48, UDTValue.class),
63- TUPLE (49, TupleValue.class),
64- CUSTOM (0, ByteBuffer.class);
42+ ASCII(1, String.class),
43+ BIGINT(2, Long.class),
44+ BLOB(3, ByteBuffer.class),
45+ BOOLEAN(4, Boolean.class),
46+ COUNTER(5, Long.class),
47+ DECIMAL(6, BigDecimal.class),
48+ DOUBLE(7, Double.class),
49+ FLOAT(8, Float.class),
50+ INET(16, InetAddress.class),
51+ INT(9, Integer.class),
52+ TEXT(10, String.class),
53+ TIMESTAMP(11, Date.class),
54+ UUID(12, UUID.class),
55+ VARCHAR(13, String.class),
56+ VARINT(14, BigInteger.class),
57+ TIMEUUID(15, UUID.class),
58+ LIST(32, List.class),
59+ SET(34, Set.class),
60+ MAP(33, Map.class),
61+ UDT(48, UDTValue.class),
62+ TUPLE(49, TupleValue.class),
63+ CUSTOM(0, ByteBuffer.class);
6564
6665 final int protocolId;
6766 final Class<?> javaType;
6867
6968 private static final Name[] nameToIds;
69+
7070 static {
7171 int maxCode = -1;
7272 for (Name name : Name.values())
@@ -110,33 +110,33 @@
110110
111111 /**
112112 * Returns the Java Class corresponding to this CQL type name.
113- *
113+ * <p/>
114114 * The correspondence between CQL types and java ones is as follow:
115115 * <table>
116- * <caption>DataType to Java class correspondence</caption>
117- * <tr><th>DataType (CQL)</th><th>Java Class</th></tr>
118- * <tr><td>ASCII </td><td>String</td></tr>
119- * <tr><td>BIGINT </td><td>Long</td></tr>
120- * <tr><td>BLOB </td><td>ByteBuffer</td></tr>
121- * <tr><td>BOOLEAN </td><td>Boolean</td></tr>
122- * <tr><td>COUNTER </td><td>Long</td></tr>
123- * <tr><td>CUSTOM </td><td>ByteBuffer</td></tr>
124- * <tr><td>DECIMAL </td><td>BigDecimal</td></tr>
125- * <tr><td>DOUBLE </td><td>Double</td></tr>
126- * <tr><td>FLOAT </td><td>Float</td></tr>
127- * <tr><td>INET </td><td>InetAddress</td></tr>
128- * <tr><td>INT </td><td>Integer</td></tr>
129- * <tr><td>LIST </td><td>List</td></tr>
130- * <tr><td>MAP </td><td>Map</td></tr>
131- * <tr><td>SET </td><td>Set</td></tr>
132- * <tr><td>TEXT </td><td>String</td></tr>
133- * <tr><td>TIMESTAMP </td><td>Date</td></tr>
134- * <tr><td>UUID </td><td>UUID</td></tr>
135- * <tr><td>UDT </td><td>UDTValue</td></tr>
136- * <tr><td>TUPLE </td><td>TupleValue</td></tr>
137- * <tr><td>VARCHAR </td><td>String</td></tr>
138- * <tr><td>VARINT </td><td>BigInteger</td></tr>
139- * <tr><td>TIMEUUID </td><td>UUID</td></tr>
116+ * <caption>DataType to Java class correspondence</caption>
117+ * <tr><th>DataType (CQL)</th><th>Java Class</th></tr>
118+ * <tr><td>ASCII </td><td>String</td></tr>
119+ * <tr><td>BIGINT </td><td>Long</td></tr>
120+ * <tr><td>BLOB </td><td>ByteBuffer</td></tr>
121+ * <tr><td>BOOLEAN </td><td>Boolean</td></tr>
122+ * <tr><td>COUNTER </td><td>Long</td></tr>
123+ * <tr><td>CUSTOM </td><td>ByteBuffer</td></tr>
124+ * <tr><td>DECIMAL </td><td>BigDecimal</td></tr>
125+ * <tr><td>DOUBLE </td><td>Double</td></tr>
126+ * <tr><td>FLOAT </td><td>Float</td></tr>
127+ * <tr><td>INET </td><td>InetAddress</td></tr>
128+ * <tr><td>INT </td><td>Integer</td></tr>
129+ * <tr><td>LIST </td><td>List</td></tr>
130+ * <tr><td>MAP </td><td>Map</td></tr>
131+ * <tr><td>SET </td><td>Set</td></tr>
132+ * <tr><td>TEXT </td><td>String</td></tr>
133+ * <tr><td>TIMESTAMP </td><td>Date</td></tr>
134+ * <tr><td>UUID </td><td>UUID</td></tr>
135+ * <tr><td>UDT </td><td>UDTValue</td></tr>
136+ * <tr><td>TUPLE </td><td>TupleValue</td></tr>
137+ * <tr><td>VARCHAR </td><td>String</td></tr>
138+ * <tr><td>VARINT </td><td>BigInteger</td></tr>
139+ * <tr><td>TIMEUUID </td><td>UUID</td></tr>
140140 * </table>
141141 *
142142 * @return the java Class corresponding to this CQL type name.
@@ -154,12 +154,14 @@
154154 protected final DataType.Name name;
155155
156156 private static final Map<Name, DataType> primitiveTypeMap = new EnumMap<Name, DataType>(Name.class);
157+
157158 static {
158159 for (Name name : Name.values()) {
159160 if (!name.isCollection() && name != Name.CUSTOM && name != Name.UDT && name != Name.TUPLE)
160161 primitiveTypeMap.put(name, new DataType.Native(name));
161162 }
162163 }
164+
163165 private static final Set<DataType> primitiveTypeSet = ImmutableSet.copyOf(primitiveTypeMap.values());
164166
165167 protected DataType(DataType.Name name) {
@@ -172,8 +174,8 @@
172174 case CUSTOM:
173175 String className = CBUtil.readString(buffer);
174176 return CassandraTypeParser.isUserType(className) || CassandraTypeParser.isTupleType(className)
175- ? CassandraTypeParser.parseOne(className)
176- : custom(className);
177+ ? CassandraTypeParser.parseOne(className)
178+ : custom(className);
177179 case LIST:
178180 return list(decode(buffer));
179181 case SET:
@@ -355,7 +357,7 @@
355357 * Returns the type of lists of {@code elementType} elements.
356358 *
357359 * @param elementType the type of the list elements.
358- * @param frozen whether the list is frozen.
360+ * @param frozen whether the list is frozen.
359361 * @return the type of lists of {@code elementType} elements.
360362 */
361363 public static DataType list(DataType elementType, boolean frozen) {
@@ -364,7 +366,7 @@
364366
365367 /**
366368 * Returns the type of "not frozen" lists of {@code elementType} elements.
367- * <p>
369+ * <p/>
368370 * This is a shorthand for {@code list(elementType, false);}.
369371 *
370372 * @param elementType the type of the list elements.
@@ -376,7 +378,7 @@
376378
377379 /**
378380 * Returns the type of frozen lists of {@code elementType} elements.
379- * <p>
381+ * <p/>
380382 * This is a shorthand for {@code list(elementType, true);}.
381383 *
382384 * @param elementType the type of the list elements.
@@ -390,7 +392,7 @@
390392 * Returns the type of sets of {@code elementType} elements.
391393 *
392394 * @param elementType the type of the set elements.
393- * @param frozen whether the set is frozen.
395+ * @param frozen whether the set is frozen.
394396 * @return the type of sets of {@code elementType} elements.
395397 */
396398 public static DataType set(DataType elementType, boolean frozen) {
@@ -399,7 +401,7 @@
399401
400402 /**
401403 * Returns the type of "not frozen" sets of {@code elementType} elements.
402- * <p>
404+ * <p/>
403405 * This is a shorthand for {@code set(elementType, false);}.
404406 *
405407 * @param elementType the type of the set elements.
@@ -411,7 +413,7 @@
411413
412414 /**
413415 * Returns the type of frozen sets of {@code elementType} elements.
414- * <p>
416+ * <p/>
415417 * This is a shorthand for {@code set(elementType, true);}.
416418 *
417419 * @param elementType the type of the set elements.
@@ -424,9 +426,9 @@
424426 /**
425427 * Returns the type of maps of {@code keyType} to {@code valueType} elements.
426428 *
427- * @param keyType the type of the map keys.
429+ * @param keyType the type of the map keys.
428430 * @param valueType the type of the map values.
429- * @param frozen whether the map is frozen.
431+ * @param frozen whether the map is frozen.
430432 * @return the type of maps of {@code keyType} to {@code valueType} elements.
431433 */
432434 public static DataType map(DataType keyType, DataType valueType, boolean frozen) {
@@ -435,10 +437,10 @@
435437
436438 /**
437439 * Returns the type of "not frozen" maps of {@code keyType} to {@code valueType} elements.
438- * <p>
440+ * <p/>
439441 * This is a shorthand for {@code map(keyType, valueType, false);}.
440442 *
441- * @param keyType the type of the map keys.
443+ * @param keyType the type of the map keys.
442444 * @param valueType the type of the map values.
443445 * @return the type of "not frozen" maps of {@code keyType} to {@code valueType} elements.
444446 */
@@ -448,10 +450,10 @@
448450
449451 /**
450452 * Returns the type of frozen maps of {@code keyType} to {@code valueType} elements.
451- * <p>
453+ * <p/>
452454 * This is a shorthand for {@code map(keyType, valueType, true);}.
453455 *
454- * @param keyType the type of the map keys.
456+ * @param keyType the type of the map keys.
455457 * @param valueType the type of the map values.
456458 * @return the type of frozen maps of {@code keyType} to {@code valueType} elements.
457459 */
@@ -461,13 +463,13 @@
461463
462464 /**
463465 * Returns a Custom type.
464- * <p>
466+ * <p/>
465467 * A custom type is defined by the name of the class used on the Cassandra
466468 * side to implement it. Note that the support for custom type by the
467469 * driver is limited: values of a custom type won't be interpreted by the
468470 * driver in any way. They will thus have to be set (by {@link BoundStatement#setBytesUnsafe}
469471 * and retrieved (by {@link Row#getBytesUnsafe}) as raw ByteBuffer.
470- * <p>
472+ * <p/>
471473 * The use of custom types is rarely useful and is thus not encouraged.
472474 *
473475 * @param typeClassName the server-side fully qualified class name for the type.
@@ -490,7 +492,7 @@
490492
491493 /**
492494 * Returns whether this data type is frozen.
493- * <p>
495+ * <p/>
494496 * This applies to User Defined Types, tuples and nested collections. Frozen types are serialized as a single value in
495497 * Cassandra's storage engine, whereas non-frozen types are stored in a form that allows updates to individual subfields.
496498 *
@@ -500,17 +502,17 @@
500502
501503 /**
502504 * Returns the type arguments of this type.
503- * <p>
505+ * <p/>
504506 * Note that only the collection types (LIST, MAP, SET) have type
505507 * arguments. For the other types, this will return an empty list.
506- * <p>
508+ * <p/>
507509 * For the collection types:
508510 * <ul>
509- * <li>For lists and sets, this method returns one argument, the type of
510- * the elements.</li>
511- * <li>For maps, this method returns two arguments, the first one is the
512- * type of the map keys, the second one is the type of the map
513- * values.</li>
511+ * <li>For lists and sets, this method returns one argument, the type of
512+ * the elements.</li>
513+ * <li>For maps, this method returns two arguments, the first one is the
514+ * type of the map keys, the second one is the type of the map
515+ * values.</li>
514516 * </ul>
515517 *
516518 * @return an immutable list containing the type arguments of this type.
@@ -538,10 +540,9 @@
538540 * @param value the value to parse.
539541 * @return a java object representing {@code value}. If {@code value == null}, then
540542 * {@code null} is returned.
541- *
542543 * @throws InvalidTypeException if {@code value} is not a valid CQL string
543- * representation for this type. Please note that values for custom types
544- * can never be parsed and will always return this exception.
544+ * representation for this type. Please note that values for custom types
545+ * can never be parsed and will always return this exception.
545546 */
546547 public Object parse(String value) {
547548 // We don't care about the protocol version for parsing
@@ -553,10 +554,9 @@
553554 *
554555 * @param value the value to format.
555556 * @return a string corresponding to the CQL representation of {@code value}.
556- *
557557 * @throws InvalidTypeException if {@code value} does not correspond to
558- * a CQL value (known by the driver). Please note that for custom types this
559- * method will always return this exception.
558+ * a CQL value (known by the driver). Please note that for custom types this
559+ * method will always return this exception.
560560 */
561561 public String format(Object value) {
562562 // We don't care about the protocol version for formatting
@@ -574,11 +574,10 @@
574574
575575 /**
576576 * Returns the Java Class corresponding to this type.
577- *
577+ * <p/>
578578 * This is a shortcut for {@code getName().asJavaClass()}.
579579 *
580580 * @return the java Class corresponding to this type.
581- *
582581 * @see Name#asJavaClass
583582 */
584583 public Class<?> asJavaClass() {
@@ -598,19 +597,18 @@
598597
599598 /**
600599 * Serialize a value of this type to bytes, with the given protocol version.
601- * <p>
600+ * <p/>
602601 * The actual format of the resulting bytes will correspond to the
603602 * Cassandra encoding for this type (for the requested protocol version).
604603 *
605- * @param value the value to serialize.
604+ * @param value the value to serialize.
606605 * @param protocolVersion the protocol version to use when serializing
607- * {@code bytes}. In most cases, the proper value to provide for this argument
608- * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
609- * is the protocol version in use by the driver).
606+ * {@code bytes}. In most cases, the proper value to provide for this argument
607+ * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
608+ * is the protocol version in use by the driver).
610609 * @return the value serialized, or {@code null} if {@code value} is null.
611- *
612610 * @throws InvalidTypeException if {@code value} is not a valid object
613- * for this {@code DataType}.
611+ * for this {@code DataType}.
614612 */
615613 public ByteBuffer serialize(Object value, ProtocolVersion protocolVersion) {
616614 Class<?> providedClass = value.getClass();
@@ -630,7 +628,6 @@
630628 * Serialize a value of this type to bytes, with the given numeric protocol version.
631629 *
632630 * @throws IllegalArgumentException if {@code protocolVersion} does not correspond to any known version.
633- *
634631 * @deprecated This method is provided for backward compatibility. Use
635632 * {@link #serialize(Object, ProtocolVersion)} instead.
636633 */
@@ -651,11 +648,11 @@
651648 /**
652649 * Deserialize a value of this type from the provided bytes using the given protocol version.
653650 *
654- * @param bytes bytes holding the value to deserialize.
651+ * @param bytes bytes holding the value to deserialize.
655652 * @param protocolVersion the protocol version to use when deserializing
656- * {@code bytes}. In most cases, the proper value to provide for this argument
657- * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
658- * is the protocol version in use by the driver).
653+ * {@code bytes}. In most cases, the proper value to provide for this argument
654+ * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
655+ * is the protocol version in use by the driver).
659656 * @return the deserialized value (of class {@code this.asJavaClass()}).
660657 * Will return {@code null} if either {@code bytes} is {@code null} or if
661658 * {@code bytes.remaining() == 0} and this type has no value corresponding
@@ -665,9 +662,8 @@
665662 * throwing an exception in that case. It is however highly discouraged to
666663 * store empty byte buffers for types for which it doesn't make sense, so
667664 * this detail can generally be ignored).
668- *
669665 * @throws InvalidTypeException if {@code bytes} is not a valid
670- * encoding of an object of this {@code DataType}.
666+ * encoding of an object of this {@code DataType}.
671667 */
672668 public Object deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
673669 return codec(protocolVersion).deserialize(bytes);
@@ -677,9 +673,8 @@
677673 * Deserialize a value of this type from the provided bytes using the given numeric protocol version.
678674 *
679675 * @throws IllegalArgumentException if {@code protocolVersion} does not correspond to any known version.
680- *
681676 * @deprecated This method is provided for backward compatibility. Use
682- * {@link #deserialize(ByteBuffer,ProtocolVersion)} instead.
677+ * {@link #deserialize(ByteBuffer, ProtocolVersion)} instead.
683678 */
684679 public Object deserialize(ByteBuffer bytes, int protocolVersion) {
685680 return deserialize(bytes, ProtocolVersion.fromInt(protocolVersion));
@@ -696,7 +691,7 @@
696691
697692 /**
698693 * Serialize an object based on its java class.
699- * <p>
694+ * <p/>
700695 * This is equivalent to {@link #serialize} but with the difference that
701696 * the actual {@code DataType} of the resulting value is inferred from the
702697 * java class of {@code value}. The correspondence between CQL {@code DataType}
@@ -704,16 +699,15 @@
704699 * Note that if you know the {@code DataType} of {@code value}, you should use
705700 * the {@link #serialize} method instead as it is going to be faster.
706701 *
707- * @param value the value to serialize.
702+ * @param value the value to serialize.
708703 * @param protocolVersion the protocol version to use when deserializing
709- * {@code bytes}. In most cases, the proper value to provide for this argument
710- * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
711- * is the protocol version in use by the driver).
704+ * {@code bytes}. In most cases, the proper value to provide for this argument
705+ * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
706+ * is the protocol version in use by the driver).
712707 * @return the value serialized, or {@code null} if {@code value} is null.
713- *
714708 * @throws IllegalArgumentException if {@code value} is not of a type
715- * corresponding to a CQL3 type, i.e. is not a Class that could be returned
716- * by {@link DataType#asJavaClass}.
709+ * corresponding to a CQL3 type, i.e. is not a Class that could be returned
710+ * by {@link DataType#asJavaClass}.
717711 */
718712 public static ByteBuffer serializeValue(Object value, ProtocolVersion protocolVersion) {
719713 if (value == null)
@@ -737,7 +731,6 @@
737731 * Serialize an object based on its java class, with the given numeric protocol version.
738732 *
739733 * @throws IllegalArgumentException if {@code protocolVersion} does not correspond to any known version.
740- *
741734 * @deprecated This method is provided for backward compatibility. Use
742735 * {@link #serializeValue(Object, ProtocolVersion)} instead.
743736 */
@@ -778,19 +771,19 @@
778771 @Override
779772 public final int hashCode() {
780773 return (name == Name.TEXT)
781- ? Name.VARCHAR.hashCode()
782- : name.hashCode();
774+ ? Name.VARCHAR.hashCode()
775+ : name.hashCode();
783776 }
784777
785778 @Override
786779 public final boolean equals(Object o) {
787- if(!(o instanceof DataType.Native))
780+ if (!(o instanceof DataType.Native))
788781 return false;
789782
790- Native that = (DataType.Native)o;
783+ Native that = (DataType.Native) o;
791784 return name == that.name ||
792- name == Name.VARCHAR && that.name == Name.TEXT ||
793- name == Name.TEXT && that.name == Name.VARCHAR;
785+ name == Name.VARCHAR && that.name == Name.TEXT ||
786+ name == Name.TEXT && that.name == Name.VARCHAR;
794787 }
795788
796789 @Override
@@ -821,14 +814,14 @@
821814 switch (name) {
822815 case LIST:
823816 return typeToken.getRawType().isAssignableFrom(List.class) &&
824- typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0]));
817+ typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0]));
825818 case SET:
826819 return typeToken.getRawType().isAssignableFrom(Set.class) &&
827- typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0]));
820+ typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0]));
828821 case MAP:
829822 return typeToken.getRawType().isAssignableFrom(Map.class) &&
830- typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0])) &&
831- typeArguments.get(1).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[1]));
823+ typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0])) &&
824+ typeArguments.get(1).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[1]));
832825 }
833826 throw new AssertionError();
834827 }
@@ -836,11 +829,13 @@
836829 @SuppressWarnings("unchecked")
837830 @Override
838831 TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
839- switch (name)
840- {
841- case LIST: return (TypeCodec)TypeCodec.listOf(typeArguments.get(0), protocolVersion);
842- case SET: return (TypeCodec)TypeCodec.setOf(typeArguments.get(0), protocolVersion);
843- case MAP: return (TypeCodec)TypeCodec.mapOf(typeArguments.get(0), typeArguments.get(1), protocolVersion);
832+ switch (name) {
833+ case LIST:
834+ return (TypeCodec) TypeCodec.listOf(typeArguments.get(0), protocolVersion);
835+ case SET:
836+ return (TypeCodec) TypeCodec.setOf(typeArguments.get(0), protocolVersion);
837+ case MAP:
838+ return (TypeCodec) TypeCodec.mapOf(typeArguments.get(0), typeArguments.get(1), protocolVersion);
844839 }
845840 throw new AssertionError();
846841 }
@@ -852,15 +847,15 @@
852847
853848 @Override
854849 public final int hashCode() {
855- return Arrays.hashCode(new Object[]{ name, typeArguments });
850+ return Arrays.hashCode(new Object[]{name, typeArguments});
856851 }
857852
858853 @Override
859854 public final boolean equals(Object o) {
860- if(!(o instanceof DataType.Collection))
855+ if (!(o instanceof DataType.Collection))
861856 return false;
862857
863- DataType.Collection d = (DataType.Collection)o;
858+ DataType.Collection d = (DataType.Collection) o;
864859 return name == d.name && typeArguments.equals(d.typeArguments);
865860 }
866861
@@ -869,8 +864,7 @@
869864 if (name == Name.MAP) {
870865 String template = frozen ? "frozen<%s<%s, %s>>" : "%s<%s, %s>";
871866 return String.format(template, name, typeArguments.get(0), typeArguments.get(1));
872- }
873- else {
867+ } else {
874868 String template = frozen ? "frozen<%s<%s>>" : "%s<%s>";
875869 return String.format(template, name, typeArguments.get(0));
876870 }
@@ -899,7 +893,7 @@
899893 @SuppressWarnings("unchecked")
900894 @Override
901895 TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
902- return (TypeCodec)TypeCodec.bytesCodec;
896+ return (TypeCodec) TypeCodec.bytesCodec;
903897 }
904898
905899 @Override
@@ -919,15 +913,15 @@
919913
920914 @Override
921915 public final int hashCode() {
922- return Arrays.hashCode(new Object[]{ name, customClassName });
916+ return Arrays.hashCode(new Object[]{name, customClassName});
923917 }
924918
925919 @Override
926920 public final boolean equals(Object o) {
927- if(!(o instanceof DataType.Custom))
921+ if (!(o instanceof DataType.Custom))
928922 return false;
929923
930- DataType.Custom d = (DataType.Custom)o;
924+ DataType.Custom d = (DataType.Custom) o;
931925 return name == d.name && Objects.equal(customClassName, d.customClassName);
932926 }
933927
modified driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java +3 −3
@@ -15,12 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.policies.RetryPolicy;
19+
1820 import java.nio.ByteBuffer;
1921 import java.util.List;
2022
21-import com.datastax.driver.core.policies.RetryPolicy;
22-
23-public class DefaultPreparedStatement implements IdempotenceAwarePreparedStatement{
23+public class DefaultPreparedStatement implements IdempotenceAwarePreparedStatement {
2424
2525 final PreparedId preparedId;
2626
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +40 −38
@@ -15,16 +15,18 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.ExecutionException;
19-import java.util.concurrent.TimeUnit;
20-import java.util.concurrent.TimeoutException;
21-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+import com.datastax.driver.core.exceptions.NoHostAvailableException;
20+import com.datastax.driver.core.exceptions.QueryExecutionException;
21+import com.datastax.driver.core.exceptions.QueryValidationException;
2222 import com.google.common.util.concurrent.AbstractFuture;
2323 import com.google.common.util.concurrent.Uninterruptibles;
2424 import org.slf4j.Logger;
2525 import org.slf4j.LoggerFactory;
2626
27-import com.datastax.driver.core.exceptions.*;
27+import java.util.concurrent.ExecutionException;
28+import java.util.concurrent.TimeUnit;
29+import java.util.concurrent.TimeoutException;
2830
2931 /**
3032 * Internal implementation of ResultSetFuture.
@@ -59,11 +61,11 @@
5961 try {
6062 switch (response.type) {
6163 case RESULT:
62- Responses.Result rm = (Responses.Result)response;
64+ Responses.Result rm = (Responses.Result) response;
6365 switch (rm.kind) {
6466 case SET_KEYSPACE:
6567 // propagate the keyspace change to other connections
66- session.poolsState.setKeyspace(((Responses.Result.SetKeyspace)rm).keyspace);
68+ session.poolsState.setKeyspace(((Responses.Result.SetKeyspace) rm).keyspace);
6769 set(ArrayBackedResultSet.fromMessage(rm, session, protocolVersion, info, statement));
6870 break;
6971 case SCHEMA_CHANGE:
@@ -72,7 +74,7 @@
7274 if (!cluster.configuration.getQueryOptions().isMetadataEnabled()) {
7375 cluster.waitForSchemaAgreementAndSignal(connection, this, rs);
7476 } else {
75- Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm;
77+ Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange) rm;
7678 switch (scc.change) {
7779 case CREATED:
7880 case UPDATED:
@@ -101,7 +103,7 @@
101103 keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.targetKeyspace);
102104 if (keyspace == null)
103105 logger.warn("Received a DROPPED notification for table {}.{}, but this keyspace is unknown in our metadata",
104- scc.targetKeyspace, scc.targetName);
106+ scc.targetKeyspace, scc.targetName);
105107 else {
106108 final TableMetadata removedTable = keyspace.removeTable(scc.targetName);
107109 if (removedTable != null) {
@@ -118,7 +120,7 @@
118120 keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.targetKeyspace);
119121 if (keyspace == null)
120122 logger.warn("Received a DROPPED notification for UDT {}.{}, but this keyspace is unknown in our metadata",
121- scc.targetKeyspace, scc.targetName);
123+ scc.targetKeyspace, scc.targetName);
122124 else {
123125 final UserType removedType = keyspace.removeUserType(scc.targetName);
124126 if (removedType != null) {
@@ -146,7 +148,7 @@
146148 }
147149 break;
148150 case ERROR:
149- setException(((Responses.Error)response).asException(connection.address));
151+ setException(((Responses.Error) response).asException(connection.address));
150152 break;
151153 default:
152154 // This mean we have probably have a bad node, so defunct the connection
@@ -189,23 +191,23 @@
189191
190192 /**
191193 * Waits for the query to return and return its result.
192- *
194+ * <p/>
193195 * This method is usually more convenient than {@link #get} because it:
194196 * <ul>
195- * <li>Waits for the result uninterruptibly, and so doesn't throw
196- * {@link InterruptedException}.</li>
197- * <li>Returns meaningful exceptions, instead of having to deal
198- * with ExecutionException.</li>
197+ * <li>Waits for the result uninterruptibly, and so doesn't throw
198+ * {@link InterruptedException}.</li>
199+ * <li>Returns meaningful exceptions, instead of having to deal
200+ * with ExecutionException.</li>
199201 * </ul>
200202 * As such, it is the preferred way to get the future result.
201203 *
202204 * @throws NoHostAvailableException if no host in the cluster can be
203- * contacted successfully to execute this query.
204- * @throws QueryExecutionException if the query triggered an execution
205- * exception, that is an exception thrown by Cassandra when it cannot execute
206- * the query with the requested consistency level successfully.
205+ * contacted successfully to execute this query.
206+ * @throws QueryExecutionException if the query triggered an execution
207+ * exception, that is an exception thrown by Cassandra when it cannot execute
208+ * the query with the requested consistency level successfully.
207209 * @throws QueryValidationException if the query is invalid (syntax error,
208- * unauthorized or any other validation problem).
210+ * unauthorized or any other validation problem).
209211 */
210212 public ResultSet getUninterruptibly() {
211213 try {
@@ -218,26 +220,26 @@
218220 /**
219221 * Waits for the provided time for the query to return and return its
220222 * result if available.
221- *
223+ * <p/>
222224 * This method is usually more convenient than {@link #get} because it:
223225 * <ul>
224- * <li>Waits for the result uninterruptibly, and so doesn't throw
225- * {@link InterruptedException}.</li>
226- * <li>Returns meaningful exceptions, instead of having to deal
227- * with ExecutionException.</li>
226+ * <li>Waits for the result uninterruptibly, and so doesn't throw
227+ * {@link InterruptedException}.</li>
228+ * <li>Returns meaningful exceptions, instead of having to deal
229+ * with ExecutionException.</li>
228230 * </ul>
229231 * As such, it is the preferred way to get the future result.
230232 *
231233 * @throws NoHostAvailableException if no host in the cluster can be
232- * contacted successfully to execute this query.
233- * @throws QueryExecutionException if the query triggered an execution
234- * exception, that is an exception thrown by Cassandra when it cannot execute
235- * the query with the requested consistency level successfully.
234+ * contacted successfully to execute this query.
235+ * @throws QueryExecutionException if the query triggered an execution
236+ * exception, that is an exception thrown by Cassandra when it cannot execute
237+ * the query with the requested consistency level successfully.
236238 * @throws QueryValidationException if the query if invalid (syntax error,
237- * unauthorized or any other validation problem).
238- * @throws TimeoutException if the wait timed out (Note that this is
239- * different from a Cassandra timeout, which is a {@code
240- * QueryExecutionException}).
239+ * unauthorized or any other validation problem).
240+ * @throws TimeoutException if the wait timed out (Note that this is
241+ * different from a Cassandra timeout, which is a {@code
242+ * QueryExecutionException}).
241243 */
242244 public ResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException {
243245 try {
@@ -250,12 +252,12 @@
250252 /**
251253 * Attempts to cancel the execution of the request corresponding to this
252254 * future. This attempt will fail if the request has already returned.
253- * <p>
255+ * <p/>
254256 * Please note that this only cancels the request driver side, but nothing
255257 * is done to interrupt the execution of the request Cassandra side (and that even
256258 * if {@code mayInterruptIfRunning} is true) since Cassandra does not
257259 * support such interruption.
258- * <p>
260+ * <p/>
259261 * This method can be used to ensure no more work is performed driver side
260262 * (which, while it doesn't include stopping a request already submitted
261263 * to a Cassandra node, may include not retrying another Cassandra host on
@@ -275,7 +277,7 @@
275277 * <pre>
276278 *
277279 * @param mayInterruptIfRunning the value of this parameter is currently
278- * ignored.
280+ * ignored.
279281 * @return {@code false} if the future could not be cancelled (it has already
280282 * completed normally); {@code true} otherwise.
281283 */
@@ -284,7 +286,7 @@
284286 if (!super.cancel(mayInterruptIfRunning))
285287 return false;
286288
287- if(handler != null) {
289+ if (handler != null) {
288290 handler.cancel();
289291 }
290292 return true;
modified driver-core/src/main/java/com/datastax/driver/core/DelegatingCluster.java +2 −2
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.util.concurrent.ListenableFuture;
19+
1820 import java.net.InetSocketAddress;
1921 import java.util.Collections;
2022
21-import com.google.common.util.concurrent.ListenableFuture;
22-
2323 /**
2424 * Base class for custom {@link Cluster} implementations that wrap another instance (delegate / decorator pattern).
2525 */
modified driver-core/src/main/java/com/datastax/driver/core/DriverThrowables.java +4 −4
@@ -15,18 +15,18 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.ExecutionException;
19-
2018 import com.datastax.driver.core.exceptions.DriverException;
2119 import com.datastax.driver.core.exceptions.DriverInternalError;
2220
21+import java.util.concurrent.ExecutionException;
22+
2323 class DriverThrowables {
2424
2525 static RuntimeException propagateCause(ExecutionException e) {
2626 Throwable cause = e.getCause();
2727
2828 if (cause instanceof Error)
29- throw ((Error)cause);
29+ throw ((Error) cause);
3030
3131 // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been
3232 // created on the I/O thread receiving the response. Which means that the stacktrace associated
@@ -34,7 +34,7 @@
3434 // out which execute() statement actually raised the exception. So instead, we re-create the
3535 // exception.
3636 if (cause instanceof DriverException)
37- throw ((DriverException)cause).copy();
37+ throw ((DriverException) cause).copy();
3838 else
3939 throw new DriverInternalError("Unexpected exception thrown", cause);
4040 }
modified driver-core/src/main/java/com/datastax/driver/core/EventDebouncer.java +19 −16
@@ -15,15 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-import java.util.Queue;
20-import java.util.concurrent.*;
21-import java.util.concurrent.atomic.AtomicInteger;
22-import java.util.concurrent.atomic.AtomicReference;
23-
24-import static java.util.concurrent.TimeUnit.NANOSECONDS;
25-import static java.util.concurrent.TimeUnit.SECONDS;
26-
18+import com.datastax.driver.core.utils.MoreFutures;
2719 import com.google.common.collect.Lists;
2820 import com.google.common.util.concurrent.FutureCallback;
2921 import com.google.common.util.concurrent.Futures;
@@ -32,13 +24,22 @@
3224 import org.slf4j.Logger;
3325 import org.slf4j.LoggerFactory;
3426
35-import static com.google.common.base.Preconditions.checkNotNull;
27+import java.util.List;
28+import java.util.Queue;
29+import java.util.concurrent.ConcurrentLinkedQueue;
30+import java.util.concurrent.Future;
31+import java.util.concurrent.ScheduledExecutorService;
32+import java.util.concurrent.TimeUnit;
33+import java.util.concurrent.atomic.AtomicInteger;
34+import java.util.concurrent.atomic.AtomicReference;
3635
37-import com.datastax.driver.core.utils.MoreFutures;
36+import static com.google.common.base.Preconditions.checkNotNull;
37+import static java.util.concurrent.TimeUnit.NANOSECONDS;
38+import static java.util.concurrent.TimeUnit.SECONDS;
3839
3940 /**
4041 * A helper class to debounce events received by the Control Connection.
41- *
42+ * <p/>
4243 * This class accumulates received events, and delivers them when either:
4344 * - no events have been received for delayMs
4445 * - maxPendingEvents have been received
@@ -87,7 +88,7 @@
8788 state = State.RUNNING;
8889 if (!events.isEmpty()) {
8990 logger.trace("{} debouncer: {} events were accumulated before the debouncer started: delivering now",
90- name, eventCount.get());
91+ name, eventCount.get());
9192 scheduleImmediateDelivery();
9293 }
9394 }
@@ -114,7 +115,9 @@
114115 }
115116 }
116117
117- /** @return a future that will complete once the event has been processed */
118+ /**
119+ * @return a future that will complete once the event has been processed
120+ */
118121 ListenableFuture<Void> eventReceived(T event) {
119122 if (state == State.STOPPED) {
120123 logger.trace("{} debouncer is stopped, rejecting event: {}", name, event);
@@ -130,8 +133,8 @@
130133 if (count > MAX_QUEUED_EVENTS && (now = System.nanoTime()) > lastOverflowWarning + OVERFLOW_WARNING_INTERVAL) {
131134 lastOverflowWarning = now;
132135 logger.warn("{} debouncer enqueued more than {} events, rejecting new events. "
133- + "This should not happen and is likely a sign that something is wrong.",
134- name, MAX_QUEUED_EVENTS);
136+ + "This should not happen and is likely a sign that something is wrong.",
137+ name, MAX_QUEUED_EVENTS);
135138 return MoreFutures.VOID_SUCCESS;
136139 }
137140
modified driver-core/src/main/java/com/datastax/driver/core/ExceptionCode.java +17 −16
@@ -15,39 +15,40 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+
1820 import java.util.HashMap;
1921 import java.util.Map;
2022
21-import com.datastax.driver.core.exceptions.DriverInternalError;
22-
2323 /**
2424 * Exceptions code, as defined by the native protocol.
2525 */
2626 enum ExceptionCode {
2727
28- SERVER_ERROR (0x0000),
29- PROTOCOL_ERROR (0x000A),
28+ SERVER_ERROR(0x0000),
29+ PROTOCOL_ERROR(0x000A),
3030
31- BAD_CREDENTIALS (0x0100),
31+ BAD_CREDENTIALS(0x0100),
3232
3333 // 1xx: problem during request execution
34- UNAVAILABLE (0x1000),
35- OVERLOADED (0x1001),
34+ UNAVAILABLE(0x1000),
35+ OVERLOADED(0x1001),
3636 IS_BOOTSTRAPPING(0x1002),
37- TRUNCATE_ERROR (0x1003),
38- WRITE_TIMEOUT (0x1100),
39- READ_TIMEOUT (0x1200),
37+ TRUNCATE_ERROR(0x1003),
38+ WRITE_TIMEOUT(0x1100),
39+ READ_TIMEOUT(0x1200),
4040
4141 // 2xx: problem validating the request
42- SYNTAX_ERROR (0x2000),
43- UNAUTHORIZED (0x2100),
44- INVALID (0x2200),
45- CONFIG_ERROR (0x2300),
46- ALREADY_EXISTS (0x2400),
47- UNPREPARED (0x2500);
42+ SYNTAX_ERROR(0x2000),
43+ UNAUTHORIZED(0x2100),
44+ INVALID(0x2200),
45+ CONFIG_ERROR(0x2300),
46+ ALREADY_EXISTS(0x2400),
47+ UNPREPARED(0x2500);
4848
4949 public final int value;
5050 private static final Map<Integer, ExceptionCode> valueToCode = new HashMap<Integer, ExceptionCode>(ExceptionCode.values().length);
51+
5152 static {
5253 for (ExceptionCode code : ExceptionCode.values())
5354 valueToCode.put(code.value, code);
modified driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +11 −13
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.Bytes;
19+
1820 import java.nio.ByteBuffer;
1921 import java.util.List;
2022
21-import com.datastax.driver.core.utils.Bytes;
22-
2323 /**
2424 * Basic information on the execution of a query.
2525 */
@@ -64,7 +64,7 @@
6464
6565 /**
6666 * The list of tried hosts for this query.
67- * <p>
67+ * <p/>
6868 * In general, this will be a singleton list with the host that coordinated
6969 * that query. However:
7070 * <ul>
@@ -76,7 +76,7 @@
7676 * <li>if {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}
7777 * are enabled, other hosts might have been tried speculatively as well.</li>
7878 * </ul>
79- * <p>
79+ * <p/>
8080 * If you are only interested in fetching the final (and often only) node
8181 * coordinating the query, {@link #getQueriedHost} provides a shortcut to
8282 * fetch the last element of the list returned by this method.
@@ -89,7 +89,7 @@
8989
9090 /**
9191 * Return the Cassandra host that coordinated this query.
92- * <p>
92+ * <p/>
9393 * This is a shortcut for {@code getTriedHosts().get(getTriedHosts().size())}.
9494 *
9595 * @return return the Cassandra host that coordinated this query.
@@ -103,7 +103,7 @@
103103 * due to the {@link com.datastax.driver.core.policies.RetryPolicy}, this
104104 * return the biggest consistency level that has been actually achieved by
105105 * the query.
106- * <p>
106+ * <p/>
107107 * Note that the default {@code RetryPolicy}
108108 * ({@link com.datastax.driver.core.policies.DefaultRetryPolicy})
109109 * will never allow a query to be successful without achieving the
@@ -133,12 +133,11 @@
133133
134134 /**
135135 * The paging state of the query.
136- *
136+ * <p/>
137137 * This object represents the next page to be fetched if this query is
138138 * multi page. It can be saved and reused later on the same statement.
139139 *
140140 * @return the paging state or null if there is no next page.
141- *
142141 * @see Statement#setPagingState(PagingState)
143142 */
144143 public PagingState getPagingState() {
@@ -149,12 +148,11 @@
149148
150149 /**
151150 * Returns the "raw" paging state of the query.
152- *
151+ * <p/>
153152 * Contrary to {@link #getPagingState()}, there will be no validation when
154153 * this is later reinjected into a statement.
155154 *
156155 * @return the paging state or null if there is no next page.
157- *
158156 * @see Statement#setPagingStateUnsafe(byte[])
159157 */
160158 public byte[] getPagingStateUnsafe() {
@@ -165,15 +163,15 @@
165163
166164 /**
167165 * Whether the cluster had reached schema agreement after the execution of this query.
168- *
166+ * <p/>
169167 * After a successful schema-altering query (ex: creating a table), the driver
170168 * will check if the cluster's nodes agree on the new schema version. If not,
171169 * it will keep retrying for a given delay (configurable via
172170 * {@link Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int)}).
173- * <p>
171+ * <p/>
174172 * If this method returns {@code false}, clients can call {@link Metadata#checkSchemaAgreement()}
175173 * later to perform the check manually.
176- * <p>
174+ * <p/>
177175 * Note that the schema agreement check is only performed for schema-altering queries
178176 * For other query types, this method will always return {@code true}.
179177 *
modified driver-core/src/main/java/com/datastax/driver/core/Frame.java +22 −24
@@ -15,15 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.EnumSet;
19-import java.util.List;
20-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
2119 import io.netty.buffer.ByteBuf;
2220 import io.netty.channel.ChannelHandler;
2321 import io.netty.channel.ChannelHandlerContext;
2422 import io.netty.handler.codec.*;
2523
26-import com.datastax.driver.core.exceptions.DriverInternalError;
24+import java.util.EnumSet;
25+import java.util.List;
2726
2827 class Frame {
2928
@@ -33,24 +32,24 @@
3332 /**
3433 * On-wire frame.
3534 * Frames for protocol versions 1+2 are defined as:
36- *
37- * 0 8 16 24 32
38- * +---------+---------+---------+---------+
39- * | version | flags | stream | opcode |
40- * +---------+---------+---------+---------+
41- * | length |
42- * +---------+---------+---------+---------+
43- *
35+ * <p/>
36+ * 0 8 16 24 32
37+ * +---------+---------+---------+---------+
38+ * | version | flags | stream | opcode |
39+ * +---------+---------+---------+---------+
40+ * | length |
41+ * +---------+---------+---------+---------+
42+ * <p/>
4443 * Frames for protocol version 3 are defined as:
45- *
46- * 0 8 16 24 32
47- * +---------+---------+---------+---------+
48- * | version | flags | stream |
49- * +---------+---------+---------+---------+
50- * | opcode | length |
51- * +---------+---------+---------+---------+
52- * | length |
53- * +---------+
44+ * <p/>
45+ * 0 8 16 24 32
46+ * +---------+---------+---------+---------+
47+ * | version | flags | stream |
48+ * +---------+---------+---------+---------+
49+ * | opcode | length |
50+ * +---------+---------+---------+---------+
51+ * | length |
52+ * +---------+
5453 */
5554 private Frame(Header header, ByteBuf body) {
5655 this.header = header;
@@ -64,7 +63,7 @@
6463 // version first byte is the "direction" of the frame (request or response)
6564 ProtocolVersion version = ProtocolVersion.fromInt(versionBytes & 0x7F);
6665 int hdrLen = Header.lengthFor(version);
67- assert fullFrame.readableBytes() >= (hdrLen-1) : String.format("Frame too short (%d bytes)", fullFrame.readableBytes());
66+ assert fullFrame.readableBytes() >= (hdrLen - 1) : String.format("Frame too short (%d bytes)", fullFrame.readableBytes());
6867
6968 int flags = fullFrame.readByte();
7069 int streamId = readStreamid(fullFrame, version);
@@ -123,8 +122,7 @@
123122 }
124123 }
125124
126- public static enum Flag
127- {
125+ public static enum Flag {
128126 // The order of that enum matters!!
129127 COMPRESSED,
130128 TRACING;
modified driver-core/src/main/java/com/datastax/driver/core/FrameCompressor.java +9 −7
@@ -15,26 +15,27 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.io.IOException;
19-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
2019 import io.netty.buffer.Unpooled;
2120 import net.jpountz.lz4.LZ4Factory;
2221 import org.slf4j.Logger;
2322 import org.slf4j.LoggerFactory;
2423 import org.xerial.snappy.Snappy;
2524
26-import com.datastax.driver.core.exceptions.DriverInternalError;
25+import java.io.IOException;
2726
2827 abstract class FrameCompressor {
2928
3029 private static final Logger logger = LoggerFactory.getLogger(FrameCompressor.class);
3130
3231 public abstract Frame compress(Frame frame) throws IOException;
32+
3333 public abstract Frame decompress(Frame frame) throws IOException;
3434
3535 public static class SnappyCompressor extends FrameCompressor {
3636
3737 public static final SnappyCompressor instance;
38+
3839 static {
3940 SnappyCompressor i;
4041 try {
@@ -78,6 +79,7 @@
7879 public static class LZ4Compressor extends FrameCompressor {
7980
8081 public static final LZ4Compressor instance;
82+
8183 static {
8284 LZ4Compressor i;
8385 try {
@@ -111,7 +113,7 @@
111113
112114 output[0] = (byte) (input.length >>> 24);
113115 output[1] = (byte) (input.length >>> 16);
114- output[2] = (byte) (input.length >>> 8);
116+ output[2] = (byte) (input.length >>> 8);
115117 output[3] = (byte) (input.length);
116118
117119 try {
@@ -126,9 +128,9 @@
126128 byte[] input = CBUtil.readRawBytes(frame.body);
127129
128130 int uncompressedLength = ((input[0] & 0xFF) << 24)
129- | ((input[1] & 0xFF) << 16)
130- | ((input[2] & 0xFF) << 8)
131- | ((input[3] & 0xFF));
131+ | ((input[1] & 0xFF) << 16)
132+ | ((input[2] & 0xFF) << 8)
133+ | ((input[3] & 0xFF));
132134
133135 byte[] output = new byte[uncompressedLength];
134136
modified driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java +50 −74
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.google.common.reflect.TypeToken;
20+
1821 import java.math.BigDecimal;
1922 import java.math.BigInteger;
2023 import java.net.InetAddress;
2124 import java.nio.ByteBuffer;
2225 import java.util.*;
2326
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
27-
2827 /**
2928 * Collection of (typed) CQL values that can be retrieved by index (starting a 0).
3029 */
@@ -35,9 +34,8 @@
3534 *
3635 * @param i the index ({@code 0 <= i < size()}) of the value to check.
3736 * @return whether the {@code i}th value is NULL.
38- *
3937 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for
40- * this object.
38+ * this object.
4139 */
4240 public boolean isNull(int i);
4341
@@ -47,9 +45,8 @@
4745 * @param i the index ({@code 0 <= i < size()}) to retrieve.
4846 * @return the boolean value of the {@code i}th element. If the
4947 * value is NULL, {@code false} is returned.
50- *
5148 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
52- * @throws InvalidTypeException if value {@code i} is not of type BOOLEAN.
49+ * @throws InvalidTypeException if value {@code i} is not of type BOOLEAN.
5350 */
5451 public boolean getBool(int i);
5552
@@ -59,9 +56,8 @@
5956 * @param i the index ({@code 0 <= i < size()}) to retrieve.
6057 * @return the value of the {@code i}th element as an integer. If the
6158 * value is NULL, {@code 0} is returned.
62- *
6359 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
64- * @throws InvalidTypeException if value {@code i} is not of type INT.
60+ * @throws InvalidTypeException if value {@code i} is not of type INT.
6561 */
6662 public int getInt(int i);
6763
@@ -71,9 +67,8 @@
7167 * @param i the index ({@code 0 <= i < size()}) to retrieve.
7268 * @return the value of the {@code i}th element as a long. If the
7369 * value is NULL, {@code 0L} is returned.
74- *
7570 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
76- * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
71+ * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
7772 */
7873 public long getLong(int i);
7974
@@ -83,9 +78,8 @@
8378 * @param i the index ({@code 0 <= i < size()}) to retrieve.
8479 * @return the value of the {@code i}th element as a data. If the
8580 * value is NULL, {@code null} is returned.
86- *
8781 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
88- * @throws InvalidTypeException if value {@code i} is not of type TIMESTAMP.
82+ * @throws InvalidTypeException if value {@code i} is not of type TIMESTAMP.
8983 */
9084 public Date getDate(int i);
9185
@@ -95,9 +89,8 @@
9589 * @param i the index ({@code 0 <= i < size()}) to retrieve.
9690 * @return the value of the {@code i}th element as a float. If the
9791 * value is NULL, {@code 0.0f} is returned.
98- *
9992 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
100- * @throws InvalidTypeException if value {@code i} is not of type FLOAT.
93+ * @throws InvalidTypeException if value {@code i} is not of type FLOAT.
10194 */
10295 public float getFloat(int i);
10396
@@ -107,15 +100,14 @@
107100 * @param i the index ({@code 0 <= i < size()}) to retrieve.
108101 * @return the value of the {@code i}th element as a double. If the
109102 * value is NULL, {@code 0.0} is returned.
110- *
111103 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
112- * @throws InvalidTypeException if value {@code i} is not of type DOUBLE.
104+ * @throws InvalidTypeException if value {@code i} is not of type DOUBLE.
113105 */
114106 public double getDouble(int i);
115107
116108 /**
117109 * Returns the {@code i}th value as a ByteBuffer.
118- *
110+ * <p/>
119111 * Note: this method always return the bytes composing the value, even if
120112 * the column is not of type BLOB. That is, this method never throw an
121113 * InvalidTypeException. However, if the type is not BLOB, it is up to the
@@ -124,23 +116,21 @@
124116 * @param i the index ({@code 0 <= i < size()}) to retrieve.
125117 * @return the value of the {@code i}th element as a ByteBuffer. If the
126118 * value is NULL, {@code null} is returned.
127- *
128119 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
129120 */
130121 public ByteBuffer getBytesUnsafe(int i);
131122
132123 /**
133124 * Returns the {@code i}th value as a byte array.
134- * <p>
125+ * <p/>
135126 * Note that this method validate that the column is of type BLOB. If you want to retrieve
136127 * the bytes for any type, use {@link #getBytesUnsafe(int)} instead.
137128 *
138129 * @param i the index ({@code 0 <= i < size()}) to retrieve.
139130 * @return the value of the {@code i}th element as a byte array. If the
140131 * value is NULL, {@code null} is returned.
141- *
142132 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
143- * @throws InvalidTypeException if value {@code i} type is not of type BLOB.
133+ * @throws InvalidTypeException if value {@code i} type is not of type BLOB.
144134 */
145135 public ByteBuffer getBytes(int i);
146136
@@ -150,10 +140,9 @@
150140 * @param i the index ({@code 0 <= i < size()}) to retrieve.
151141 * @return the value of the {@code i}th element as a string. If the
152142 * value is NULL, {@code null} is returned.
153- *
154143 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
155- * @throws InvalidTypeException if value {@code i} type is none of:
156- * VARCHAR, TEXT or ASCII.
144+ * @throws InvalidTypeException if value {@code i} type is none of:
145+ * VARCHAR, TEXT or ASCII.
157146 */
158147 public String getString(int i);
159148
@@ -163,9 +152,8 @@
163152 * @param i the index ({@code 0 <= i < size()}) to retrieve.
164153 * @return the value of the {@code i}th element as a variable
165154 * length integer. If the value is NULL, {@code null} is returned.
166- *
167155 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
168- * @throws InvalidTypeException if value {@code i} is not of type VARINT.
156+ * @throws InvalidTypeException if value {@code i} is not of type VARINT.
169157 */
170158 public BigInteger getVarint(int i);
171159
@@ -175,9 +163,8 @@
175163 * @param i the index ({@code 0 <= i < size()}) to retrieve.
176164 * @return the value of the {@code i}th element as a variable
177165 * length decimal. If the value is NULL, {@code null} is returned.
178- *
179166 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
180- * @throws InvalidTypeException if value {@code i} is not of type DECIMAL.
167+ * @throws InvalidTypeException if value {@code i} is not of type DECIMAL.
181168 */
182169 public BigDecimal getDecimal(int i);
183170
@@ -187,10 +174,9 @@
187174 * @param i the index ({@code 0 <= i < size()}) to retrieve.
188175 * @return the value of the {@code i}th element as a UUID.
189176 * If the value is NULL, {@code null} is returned.
190- *
191177 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
192- * @throws InvalidTypeException if value {@code i} is not of type UUID
193- * or TIMEUUID.
178+ * @throws InvalidTypeException if value {@code i} is not of type UUID
179+ * or TIMEUUID.
194180 */
195181 public UUID getUUID(int i);
196182
@@ -200,133 +186,126 @@
200186 * @param i the index ({@code 0 <= i < size()}) to retrieve.
201187 * @return the value of the {@code i}th element as an InetAddress.
202188 * If the value is NULL, {@code null} is returned.
203- *
204189 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
205- * @throws InvalidTypeException if value {@code i} is not of type INET.
190+ * @throws InvalidTypeException if value {@code i} is not of type INET.
206191 */
207192 public InetAddress getInet(int i);
208193
209194 /**
210195 * Returns the {@code i}th value as a list.
211- * <p>
196+ * <p/>
212197 * If the type of the elements is generic, use {@link #getList(int, TypeToken)}.
213198 *
214- * @param i the index ({@code 0 <= i < size()}) to retrieve.
199+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
215200 * @param elementsClass the class for the elements of the list to retrieve.
216201 * @return the value of the {@code i}th element as a list of
217202 * {@code T} objects. If the value is NULL, an empty list is
218203 * returned (note that Cassandra makes no difference between an empty list
219204 * and column of type list that is not set). The returned list is immutable.
220- *
221205 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
222- * @throws InvalidTypeException if value {@code i} is not a list or if its
223- * elements are not of class {@code T}.
206+ * @throws InvalidTypeException if value {@code i} is not a list or if its
207+ * elements are not of class {@code T}.
224208 */
225209 public <T> List<T> getList(int i, Class<T> elementsClass);
226210
227211 /**
228212 * Returns the {@code i}th value as a list.
229- * <p>
213+ * <p/>
230214 * Use this variant with nested collections, which produce a generic element type:
231215 * <pre>
232216 * {@code List<List<String>> l = row.getList(1, new TypeToken<List<String>>() {});}
233217 * </pre>
234218 *
235- * @param i the index ({@code 0 <= i < size()}) to retrieve.
219+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
236220 * @param elementsType the type of the elements of the list to retrieve.
237221 * @return the value of the {@code i}th element as a list of
238222 * {@code T} objects. If the value is NULL, an empty list is
239223 * returned (note that Cassandra makes no difference between an empty list
240224 * and column of type list that is not set). The returned list is immutable.
241- *
242225 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
243- * @throws InvalidTypeException if value {@code i} is not a list or if its
244- * elements are not of class {@code T}.
226+ * @throws InvalidTypeException if value {@code i} is not a list or if its
227+ * elements are not of class {@code T}.
245228 */
246229 public <T> List<T> getList(int i, TypeToken<T> elementsType);
247230
248231 /**
249232 * Returns the {@code i}th value as a set.
250- * <p>
233+ * <p/>
251234 * If the type of the elements is generic, use {@link #getSet(int, TypeToken)}.
252235 *
253- * @param i the index ({@code 0 <= i < size()}) to retrieve.
236+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
254237 * @param elementsClass the class for the elements of the set to retrieve.
255238 * @return the value of the {@code i}th element as a set of
256239 * {@code T} objects. If the value is NULL, an empty set is
257240 * returned (note that Cassandra makes no difference between an empty set
258241 * and column of type set that is not set). The returned set is immutable.
259- *
260242 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
261- * @throws InvalidTypeException if value {@code i} is not a set or if its
262- * elements are not of class {@code T}.
243+ * @throws InvalidTypeException if value {@code i} is not a set or if its
244+ * elements are not of class {@code T}.
263245 */
264246 public <T> Set<T> getSet(int i, Class<T> elementsClass);
265247
266248 /**
267249 * Returns the {@code i}th value as a set.
268- * <p>
250+ * <p/>
269251 * Use this variant with nested collections, which produce a generic element type:
270252 * <pre>
271253 * {@code Set<List<String>> l = row.getSet(1, new TypeToken<List<String>>() {});}
272254 * </pre>
273255 *
274- * @param i the index ({@code 0 <= i < size()}) to retrieve.
256+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
275257 * @param elementsType the type for the elements of the set to retrieve.
276258 * @return the value of the {@code i}th element as a set of
277259 * {@code T} objects. If the value is NULL, an empty set is
278260 * returned (note that Cassandra makes no difference between an empty set
279261 * and column of type set that is not set). The returned set is immutable.
280- *
281262 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
282- * @throws InvalidTypeException if value {@code i} is not a set or if its
283- * elements are not of class {@code T}.
263+ * @throws InvalidTypeException if value {@code i} is not a set or if its
264+ * elements are not of class {@code T}.
284265 */
285266 public <T> Set<T> getSet(int i, TypeToken<T> elementsType);
286267
287268 /**
288269 * Returns the {@code i}th value as a map.
289- * <p>
270+ * <p/>
290271 * If the type of the keys and/or values is generic, use {@link #getMap(int, TypeToken, TypeToken)}.
291272 *
292- * @param i the index ({@code 0 <= i < size()}) to retrieve.
293- * @param keysClass the class for the keys of the map to retrieve.
273+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
274+ * @param keysClass the class for the keys of the map to retrieve.
294275 * @param valuesClass the class for the values of the map to retrieve.
295276 * @return the value of the {@code i}th element as a map of
296277 * {@code K} to {@code V} objects. If the value is NULL,
297278 * an empty map is returned (note that Cassandra makes no difference
298279 * between an empty map and column of type map that is not set). The
299280 * returned map is immutable.
300- *
301281 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
302- * @throws InvalidTypeException if value {@code i} is not a map, if its
303- * keys are not of class {@code K} or if its values are not of
304- * class {@code V}.
282+ * @throws InvalidTypeException if value {@code i} is not a map, if its
283+ * keys are not of class {@code K} or if its values are not of
284+ * class {@code V}.
305285 */
306286 public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass);
307287
308288
309289 /**
310290 * Returns the {@code i}th value as a map.
311- * <p>
291+ * <p/>
312292 * Use this variant with nested collections, which produce a generic element type:
313293 * <pre>
314294 * {@code Map<Int, List<String>> l = row.getMap(1, TypeToken.of(Integer.class), new TypeToken<List<String>>() {});}
315295 * </pre>
316296 *
317- * @param i the index ({@code 0 <= i < size()}) to retrieve.
318- * @param keysType the type for the keys of the map to retrieve.
297+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
298+ * @param keysType the type for the keys of the map to retrieve.
319299 * @param valuesType the type for the values of the map to retrieve.
320300 * @return the value of the {@code i}th element as a map of
321301 * {@code K} to {@code V} objects. If the value is NULL,
322302 * an empty map is returned (note that Cassandra makes no difference
323303 * between an empty map and column of type map that is not set). The
324304 * returned map is immutable.
325- *
326305 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
327- * @throws InvalidTypeException if value {@code i} is not a map, if its
328- * keys are not of class {@code K} or if its values are not of
329- * class {@code V}.
306+ * @throws InvalidTypeException if value {@code i} is not a map, if its
307+ * keys are not of class {@code K} or if its values are not of
308+ * class {@code V}.
330309 */
331310 public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType);
332311
@@ -336,9 +315,8 @@
336315 * @param i the index ({@code 0 <= i < size()}) to retrieve.
337316 * @return the value of the {@code i}th element as a UDT value. If the value is NULL,
338317 * then {@code null} will be returned.
339- *
340318 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
341- * @throws InvalidTypeException if value {@code i} is not a UDT value.
319+ * @throws InvalidTypeException if value {@code i} is not a UDT value.
342320 */
343321 public UDTValue getUDTValue(int i);
344322
@@ -348,9 +326,8 @@
348326 * @param i the index ({@code 0 <= i < size()}) to retrieve.
349327 * @return the value of the {@code i}th element as a tuple value. If the value is NULL,
350328 * then {@code null} will be returned.
351- *
352329 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
353- * @throws InvalidTypeException if value {@code i} is not a tuple value.
330+ * @throws InvalidTypeException if value {@code i} is not a tuple value.
354331 */
355332 public TupleValue getTupleValue(int i);
356333
@@ -361,7 +338,6 @@
361338 * @return the value of the {@code i}th value as the Java type matching its CQL type.
362339 * If the value is NULL and is a simple type, UDT or tuple, {@code null} is returned.
363340 * If it is NULL and is a collection type, an empty (immutable) collection is returned.
364- *
365341 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
366342 */
367343 public Object getObject(int i);
modified driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java +50 −74
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.google.common.reflect.TypeToken;
20+
1821 import java.math.BigDecimal;
1922 import java.math.BigInteger;
2023 import java.net.InetAddress;
2124 import java.nio.ByteBuffer;
2225 import java.util.*;
2326
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
27-
2827 /**
2928 * Collection of (typed) CQL values that can be retrieved by name.
3029 */
@@ -35,7 +34,6 @@
3534 *
3635 * @param name the name to check.
3736 * @return whether the value for {@code name} is NULL.
38- *
3937 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
4038 */
4139 public boolean isNull(String name);
@@ -46,9 +44,8 @@
4644 * @param name the name to retrieve.
4745 * @return the boolean value for {@code name}. If the value is NULL,
4846 * {@code false} is returned.
49- *
5047 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
51- * @throws InvalidTypeException if value {@code name} is not of type BOOLEAN.
48+ * @throws InvalidTypeException if value {@code name} is not of type BOOLEAN.
5249 */
5350 public boolean getBool(String name);
5451
@@ -58,9 +55,8 @@
5855 * @param name the name to retrieve.
5956 * @return the value for {@code name} as an integer. If the value is NULL,
6057 * {@code 0} is returned.
61- *
6258 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
63- * @throws InvalidTypeException if value {@code name} is not of type INT.
59+ * @throws InvalidTypeException if value {@code name} is not of type INT.
6460 */
6561 public int getInt(String name);
6662
@@ -70,9 +66,8 @@
7066 * @param name the name to retrieve.
7167 * @return the value for {@code name} as a long. If the value is NULL,
7268 * {@code 0L} is returned.
73- *
7469 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
75- * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
70+ * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
7671 */
7772 public long getLong(String name);
7873
@@ -82,9 +77,8 @@
8277 * @param name the name to retrieve.
8378 * @return the value for {@code name} as a date. If the value is NULL,
8479 * {@code null} is returned.
85- *
8680 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
87- * @throws InvalidTypeException if value {@code name} is not of type TIMESTAMP.
81+ * @throws InvalidTypeException if value {@code name} is not of type TIMESTAMP.
8882 */
8983 public Date getDate(String name);
9084
@@ -94,9 +88,8 @@
9488 * @param name the name to retrieve.
9589 * @return the value for {@code name} as a float. If the value is NULL,
9690 * {@code 0.0f} is returned.
97- *
9891 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
99- * @throws InvalidTypeException if value {@code name} is not of type FLOAT.
92+ * @throws InvalidTypeException if value {@code name} is not of type FLOAT.
10093 */
10194 public float getFloat(String name);
10295
@@ -106,15 +99,14 @@
10699 * @param name the name to retrieve.
107100 * @return the value for {@code name} as a double. If the value is NULL,
108101 * {@code 0.0} is returned.
109- *
110102 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
111- * @throws InvalidTypeException if value {@code name} is not of type DOUBLE.
103+ * @throws InvalidTypeException if value {@code name} is not of type DOUBLE.
112104 */
113105 public double getDouble(String name);
114106
115107 /**
116108 * Returns the value for {@code name} as a ByteBuffer.
117- *
109+ * <p/>
118110 * Note: this method always return the bytes composing the value, even if
119111 * the column is not of type BLOB. That is, this method never throw an
120112 * InvalidTypeException. However, if the type is not BLOB, it is up to the
@@ -123,23 +115,21 @@
123115 * @param name the name to retrieve.
124116 * @return the value for {@code name} as a ByteBuffer. If the value is NULL,
125117 * {@code null} is returned.
126- *
127118 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
128119 */
129120 public ByteBuffer getBytesUnsafe(String name);
130121
131122 /**
132123 * Returns the value for {@code name} as a byte array.
133- * <p>
124+ * <p/>
134125 * Note that this method validate that the column is of type BLOB. If you want to retrieve
135126 * the bytes for any type, use {@link #getBytesUnsafe(String)} instead.
136127 *
137128 * @param name the name to retrieve.
138129 * @return the value for {@code name} as a byte array. If the value is NULL,
139130 * {@code null} is returned.
140- *
141131 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
142- * @throws InvalidTypeException if value {@code i} type is not of type BLOB.
132+ * @throws InvalidTypeException if value {@code i} type is not of type BLOB.
143133 */
144134 public ByteBuffer getBytes(String name);
145135
@@ -149,10 +139,9 @@
149139 * @param name the name to retrieve.
150140 * @return the value for {@code name} as a string. If the value is NULL,
151141 * {@code null} is returned.
152- *
153142 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
154- * @throws InvalidTypeException if value {@code name} type is none of:
155- * VARCHAR, TEXT or ASCII.
143+ * @throws InvalidTypeException if value {@code name} type is none of:
144+ * VARCHAR, TEXT or ASCII.
156145 */
157146 public String getString(String name);
158147
@@ -162,9 +151,8 @@
162151 * @param name the name to retrieve.
163152 * @return the value for {@code name} as a variable length integer.
164153 * If the value is NULL, {@code null} is returned.
165- *
166154 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
167- * @throws InvalidTypeException if value {@code name} is not of type VARINT.
155+ * @throws InvalidTypeException if value {@code name} is not of type VARINT.
168156 */
169157 public BigInteger getVarint(String name);
170158
@@ -174,9 +162,8 @@
174162 * @param name the name to retrieve.
175163 * @return the value for {@code name} as a variable length decimal.
176164 * If the value is NULL, {@code null} is returned.
177- *
178165 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
179- * @throws InvalidTypeException if value {@code name} is not of type DECIMAL.
166+ * @throws InvalidTypeException if value {@code name} is not of type DECIMAL.
180167 */
181168 public BigDecimal getDecimal(String name);
182169
@@ -186,10 +173,9 @@
186173 * @param name the name to retrieve.
187174 * @return the value for {@code name} as a UUID.
188175 * If the value is NULL, {@code null} is returned.
189- *
190176 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
191- * @throws InvalidTypeException if value {@code name} is not of type
192- * UUID or TIMEUUID.
177+ * @throws InvalidTypeException if value {@code name} is not of type
178+ * UUID or TIMEUUID.
193179 */
194180 public UUID getUUID(String name);
195181
@@ -199,133 +185,126 @@
199185 * @param name the name to retrieve.
200186 * @return the value for {@code name} as an InetAddress.
201187 * If the value is NULL, {@code null} is returned.
202- *
203188 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
204- * @throws InvalidTypeException if value {@code name} is not of type
205- * INET.
189+ * @throws InvalidTypeException if value {@code name} is not of type
190+ * INET.
206191 */
207192 public InetAddress getInet(String name);
208193
209194 /**
210195 * Returns the value for {@code name} as a list.
211- * <p>
196+ * <p/>
212197 * If the type of the elements is generic, use {@link #getList(String, TypeToken)}.
213198 *
214- * @param name the name to retrieve.
199+ * @param name the name to retrieve.
215200 * @param elementsClass the class for the elements of the list to retrieve.
216201 * @return the value of the {@code i}th element as a list of
217202 * {@code T} objects. If the value is NULL, an empty list is
218203 * returned (note that Cassandra makes no difference between an empty list
219204 * and column of type list that is not set). The returned list is immutable.
220- *
221205 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
222- * @throws InvalidTypeException if value {@code name} is not a list or if its
223- * elements are not of class {@code T}.
206+ * @throws InvalidTypeException if value {@code name} is not a list or if its
207+ * elements are not of class {@code T}.
224208 */
225209 public <T> List<T> getList(String name, Class<T> elementsClass);
226210
227211 /**
228212 * Returns the value for {@code name} as a list.
229- * <p>
213+ * <p/>
230214 * Use this variant with nested collections, which produce a generic element type:
231215 * <pre>
232216 * {@code List<List<String>> l = row.getList("theColumn", new TypeToken<List<String>>() {});}
233217 * </pre>
234218 *
235- * @param name the name to retrieve.
219+ * @param name the name to retrieve.
236220 * @param elementsType the type for the elements of the list to retrieve.
237221 * @return the value of the {@code i}th element as a list of
238222 * {@code T} objects. If the value is NULL, an empty list is
239223 * returned (note that Cassandra makes no difference between an empty list
240224 * and column of type list that is not set). The returned list is immutable.
241- *
242225 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
243- * @throws InvalidTypeException if value {@code name} is not a list or if its
244- * elements are not of class {@code T}.
226+ * @throws InvalidTypeException if value {@code name} is not a list or if its
227+ * elements are not of class {@code T}.
245228 */
246229 public <T> List<T> getList(String name, TypeToken<T> elementsType);
247230
248231 /**
249232 * Returns the value for {@code name} as a set.
250- * <p>
233+ * <p/>
251234 * If the type of the elements is generic, use {@link #getSet(String, TypeToken)}.
252235 *
253- * @param name the name to retrieve.
236+ * @param name the name to retrieve.
254237 * @param elementsClass the class for the elements of the set to retrieve.
255238 * @return the value of the {@code i}th element as a set of
256239 * {@code T} objects. If the value is NULL, an empty set is
257240 * returned (note that Cassandra makes no difference between an empty set
258241 * and column of type set that is not set). The returned set is immutable.
259- *
260242 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
261- * @throws InvalidTypeException if value {@code name} is not a set or if its
262- * elements are not of class {@code T}.
243+ * @throws InvalidTypeException if value {@code name} is not a set or if its
244+ * elements are not of class {@code T}.
263245 */
264246 public <T> Set<T> getSet(String name, Class<T> elementsClass);
265247
266248 /**
267249 * Returns the value for {@code name} as a set.
268- * <p>
250+ * <p/>
269251 * Use this variant with nested collections, which produce a generic element type:
270252 * <pre>
271253 * {@code Set<List<String>> l = row.getSet("theColumn", new TypeToken<List<String>>() {});}
272254 * </pre>
273255 *
274- * @param name the name to retrieve.
256+ * @param name the name to retrieve.
275257 * @param elementsType the type for the elements of the set to retrieve.
276258 * @return the value of the {@code i}th element as a set of
277259 * {@code T} objects. If the value is NULL, an empty set is
278260 * returned (note that Cassandra makes no difference between an empty set
279261 * and column of type set that is not set). The returned set is immutable.
280- *
281262 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
282- * @throws InvalidTypeException if value {@code name} is not a set or if its
283- * elements are not of class {@code T}.
263+ * @throws InvalidTypeException if value {@code name} is not a set or if its
264+ * elements are not of class {@code T}.
284265 */
285266 public <T> Set<T> getSet(String name, TypeToken<T> elementsType);
286267
287268 /**
288269 * Returns the value for {@code name} as a map.
289- * <p>
270+ * <p/>
290271 * If the type of the keys and/or values is generic, use {@link #getMap(String, TypeToken, TypeToken)}.
291272 *
292- * @param name the name to retrieve.
293- * @param keysClass the class for the keys of the map to retrieve.
273+ * @param name the name to retrieve.
274+ * @param keysClass the class for the keys of the map to retrieve.
294275 * @param valuesClass the class for the values of the map to retrieve.
295276 * @return the value of {@code name} as a map of
296277 * {@code K} to {@code V} objects. If the value is NULL,
297278 * an empty map is returned (note that Cassandra makes no difference
298279 * between an empty map and column of type map that is not set). The
299280 * returned map is immutable.
300- *
301281 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
302- * @throws InvalidTypeException if value {@code name} is not a map, if its
303- * keys are not of class {@code K} or if its values are not of
304- * class {@code V}.
282+ * @throws InvalidTypeException if value {@code name} is not a map, if its
283+ * keys are not of class {@code K} or if its values are not of
284+ * class {@code V}.
305285 */
306286 public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass);
307287
308288 /**
309289 * Returns the value for {@code name} as a map.
310- * <p>
290+ * <p/>
311291 * Use this variant with nested collections, which produce a generic element type:
312292 * <pre>
313293 * {@code Map<Int, List<String>> l = row.getMap("theColumn", TypeToken.of(Integer.class), new TypeToken<List<String>>() {});}
314294 * </pre>
315295 *
316- * @param name the name to retrieve.
317- * @param keysType the class for the keys of the map to retrieve.
296+ * @param name the name to retrieve.
297+ * @param keysType the class for the keys of the map to retrieve.
318298 * @param valuesType the class for the values of the map to retrieve.
319299 * @return the value of {@code name} as a map of
320300 * {@code K} to {@code V} objects. If the value is NULL,
321301 * an empty map is returned (note that Cassandra makes no difference
322302 * between an empty map and column of type map that is not set). The
323303 * returned map is immutable.
324- *
325304 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
326- * @throws InvalidTypeException if value {@code name} is not a map, if its
327- * keys are not of class {@code K} or if its values are not of
328- * class {@code V}.
305+ * @throws InvalidTypeException if value {@code name} is not a map, if its
306+ * keys are not of class {@code K} or if its values are not of
307+ * class {@code V}.
329308 */
330309 public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType);
331310
@@ -335,9 +314,8 @@
335314 * @param name the name to retrieve.
336315 * @return the value of {@code name} as a UDT value. If the value is NULL,
337316 * then {@code null} will be returned.
338- *
339317 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
340- * @throws InvalidTypeException if value {@code i} is not a UDT value.
318+ * @throws InvalidTypeException if value {@code i} is not a UDT value.
341319 */
342320 public UDTValue getUDTValue(String name);
343321
@@ -347,9 +325,8 @@
347325 * @param name the name to retrieve.
348326 * @return the value of {@code name} as a tuple value. If the value is NULL,
349327 * then {@code null} will be returned.
350- *
351328 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
352- * @throws InvalidTypeException if value {@code i} is not a tuple value.
329+ * @throws InvalidTypeException if value {@code i} is not a tuple value.
353330 */
354331 public TupleValue getTupleValue(String name);
355332
@@ -360,7 +337,6 @@
360337 * @return the value of the {@code i}th value as the Java type matching its CQL type.
361338 * If the value is NULL and is a simple type, UDT or tuple, {@code null} is returned.
362339 * If it is NULL and is a collection type, an empty (immutable) collection is returned.
363- *
364340 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
365341 */
366342 Object getObject(String name);
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +26 −24
@@ -15,21 +15,21 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.net.InetSocketAddress;
20-import java.util.Set;
21-import java.util.concurrent.atomic.AtomicReference;
22-import java.util.concurrent.locks.ReentrantLock;
23-
2418 import com.google.common.collect.ImmutableList;
2519 import com.google.common.util.concurrent.Futures;
2620 import com.google.common.util.concurrent.ListenableFuture;
2721 import org.slf4j.Logger;
2822 import org.slf4j.LoggerFactory;
2923
24+import java.net.InetAddress;
25+import java.net.InetSocketAddress;
26+import java.util.Set;
27+import java.util.concurrent.atomic.AtomicReference;
28+import java.util.concurrent.locks.ReentrantLock;
29+
3030 /**
3131 * A Cassandra node.
32- *
32+ * <p/>
3333 * This class keeps the information the driver maintain on a given Cassandra node.
3434 */
3535 public class Host {
@@ -40,9 +40,12 @@
4040
4141 private final InetSocketAddress address;
4242
43- enum State { ADDED, DOWN, UP }
43+ enum State {ADDED, DOWN, UP}
44+
4445 volatile State state;
45- /** Ensures state change notifications for that host are handled serially */
46+ /**
47+ * Ensures state change notifications for that host are handled serially
48+ */
4649 final ReentrantLock notificationsLock = new ReentrantLock(true);
4750
4851 final ConvictionPolicy convictionPolicy;
@@ -99,7 +102,7 @@
99102
100103 /**
101104 * Returns the node address.
102- * <p>
105+ * <p/>
103106 * This is a shortcut for {@code getSocketAddress().getAddress()}.
104107 *
105108 * @return the node {@link InetAddress}.
@@ -119,7 +122,7 @@
119122
120123 /**
121124 * Returns the name of the datacenter this host is part of.
122- * <p>
125+ * <p/>
123126 * The returned datacenter name is the one as known by Cassandra.
124127 * It is also possible for this information to be unavailable. In that
125128 * case this method returns {@code null}, and the caller should always be aware
@@ -133,7 +136,7 @@
133136
134137 /**
135138 * Returns the name of the rack this host is part of.
136- * <p>
139+ * <p/>
137140 * The returned rack name is the one as known by Cassandra.
138141 * It is also possible for this information to be unavailable. In that case
139142 * this method returns {@code null}, and the caller should always aware of this
@@ -147,7 +150,7 @@
147150
148151 /**
149152 * The Cassandra version the host is running.
150- * <p>
153+ * <p/>
151154 * As for other host information fetch from Cassandra above, the returned
152155 * version can theoretically be null if the information is unavailable.
153156 *
@@ -172,7 +175,7 @@
172175
173176 /**
174177 * Returns whether the host is considered up by the driver.
175- * <p>
178+ * <p/>
176179 * Please note that this is only the view of the driver and may not reflect
177180 * reality. In particular a node can be down but the driver hasn't detected
178181 * it yet, or it can have been restarted and the driver hasn't detected it
@@ -189,7 +192,7 @@
189192
190193 /**
191194 * Returns a description of the host's state, as seen by the driver.
192- * <p>
195+ * <p/>
193196 * This is exposed for debugging purposes only; the format of this string might
194197 * change between driver versions, so clients should not make any assumptions
195198 * about it.
@@ -203,12 +206,11 @@
203206 /**
204207 * Returns a {@code ListenableFuture} representing the completion of the first
205208 * reconnection attempt after a node has been suspected.
206- * <p>
209+ * <p/>
207210 * This is useful in load balancing policies when there are no more live nodes and
208211 * we are trying suspected nodes.
209212 *
210213 * @return the future.
211- *
212214 * @deprecated the suspicion mechanism has been disabled. This will always return
213215 * a completed future.
214216 */
@@ -220,7 +222,7 @@
220222 /**
221223 * Returns a {@code ListenableFuture} representing the completion of the reconnection
222224 * attempts scheduled after a host is marked {@code DOWN}.
223- * <p>
225+ * <p/>
224226 * <b>If the caller cancels this future,</b> the driver will not try to reconnect to
225227 * this host until it receives an UP event for it. Note that this could mean never, if
226228 * the node was marked down because of a driver-side error (e.g. read timeout) but no
@@ -235,14 +237,14 @@
235237
236238 /**
237239 * Triggers an asynchronous reconnection attempt to this host.
238- * <p>
240+ * <p/>
239241 * This method is intended for load balancing policies that mark hosts as {@link HostDistance#IGNORED IGNORED},
240242 * but still need a way to periodically check these hosts' states (UP / DOWN).
241- * <p>
243+ * <p/>
242244 * For a host that is at distance {@code IGNORED}, this method will try to reconnect exactly once: if
243245 * reconnection succeeds, the host is marked {@code UP}; otherwise, no further attempts will be scheduled.
244246 * It has no effect if the node is already {@code UP}, or if a reconnection attempt is already in progress.
245- * <p>
247+ * <p/>
246248 * Note that if the host is <em>not</em> a distance {@code IGNORED}, this method <em>will</em> trigger a periodic
247249 * reconnection attempt if the reconnection fails.
248250 */
@@ -253,7 +255,7 @@
253255 @Override
254256 public boolean equals(Object other) {
255257 if (other instanceof Host) {
256- Host that = (Host)other;
258+ Host that = (Host) other;
257259 return this.address.equals(that.address);
258260 }
259261 return false;
@@ -284,7 +286,7 @@
284286 /**
285287 * Interface for listeners that are interested in hosts added, up, down and
286288 * removed events.
287- * <p>
289+ * <p/>
288290 * It is possible for the same event to be fired multiple times,
289291 * particularly for up or down events. Therefore, a listener should ignore
290292 * the same event if it has already been notified of a node's state.
@@ -293,7 +295,7 @@
293295
294296 /**
295297 * Called when a new node is added to the cluster.
296- * <p>
298+ * <p/>
297299 * The newly added node should be considered up.
298300 *
299301 * @param host the host that has been newly added.
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +27 −23
@@ -15,6 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.AuthenticationException;
19+import com.datastax.driver.core.utils.MoreFutures;
20+import com.google.common.annotations.VisibleForTesting;
21+import com.google.common.base.Throwables;
22+import com.google.common.collect.Lists;
23+import com.google.common.util.concurrent.*;
24+import org.slf4j.Logger;
25+import org.slf4j.LoggerFactory;
26+
1827 import java.util.ArrayList;
1928 import java.util.List;
2029 import java.util.ListIterator;
@@ -26,20 +35,7 @@
2635 import java.util.concurrent.locks.Lock;
2736 import java.util.concurrent.locks.ReentrantLock;
2837
29-import com.google.common.annotations.VisibleForTesting;
30-import com.google.common.base.Throwables;
31-import com.google.common.collect.Lists;
32-import com.google.common.util.concurrent.*;
33-import org.slf4j.Logger;
34-import org.slf4j.LoggerFactory;
35-
36-import com.datastax.driver.core.exceptions.AuthenticationException;
37-import com.datastax.driver.core.utils.MoreFutures;
38-
39-import static com.datastax.driver.core.Connection.State.GONE;
40-import static com.datastax.driver.core.Connection.State.OPEN;
41-import static com.datastax.driver.core.Connection.State.RESURRECTING;
42-import static com.datastax.driver.core.Connection.State.TRASHED;
38+import static com.datastax.driver.core.Connection.State.*;
4339
4440 class HostConnectionPool implements Connection.Owner {
4541
@@ -53,9 +49,13 @@
5349
5450 final List<Connection> connections;
5551 private final AtomicInteger open;
56- /** The total number of in-flight requests on all connections of this pool. */
52+ /**
53+ * The total number of in-flight requests on all connections of this pool.
54+ */
5755 final AtomicInteger totalInFlight = new AtomicInteger();
58- /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/
56+ /**
57+ * The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}
58+ */
5959 private final AtomicInteger maxTotalInFlight = new AtomicInteger();
6060 @VisibleForTesting
6161 final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
@@ -149,7 +149,7 @@
149149 forceClose(connections);
150150 } else {
151151 logger.debug("Created connection pool to host {} ({} connections needed, {} successfully opened)",
152- host, coreSize, connections.size());
152+ host, coreSize, connections.size());
153153 phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
154154 initFuture.set(null);
155155 }
@@ -269,7 +269,7 @@
269269 } else if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
270270 // Add a connection if we fill the first n-1 connections and almost fill the last one
271271 int currentCapacity = (connectionCount - 1) * options().getMaxRequestsPerConnection(hostDistance)
272- + options().getNewConnectionThreshold(hostDistance);
272+ + options().getNewConnectionThreshold(hostDistance);
273273 if (totalInFlightCount > currentCapacity)
274274 maybeSpawnNewConnection();
275275 }
@@ -546,7 +546,9 @@
546546 cleanupTrash(now);
547547 }
548548
549- /** If we have more active connections than needed, trash some of them */
549+ /**
550+ * If we have more active connections than needed, trash some of them
551+ */
550552 private void shrinkIfBelowCapacity() {
551553 int currentLoad = maxTotalInFlight.getAndSet(totalInFlight.get());
552554
@@ -559,7 +561,7 @@
559561 int toTrash = Math.max(0, actual - needed);
560562
561563 logger.trace("Current inFlight = {}, {} connections needed, {} connections available, trashing {}",
562- currentLoad, needed, actual, toTrash);
564+ currentLoad, needed, actual, toTrash);
563565
564566 if (toTrash <= 0)
565567 return;
@@ -572,7 +574,9 @@
572574 }
573575 }
574576
575- /** Close connections that have been sitting in the trash for too long */
577+ /**
578+ * Close connections that have been sitting in the trash for too long
579+ */
576580 private void cleanupTrash(long now) {
577581 for (Connection connection : trash) {
578582 if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) {
@@ -612,8 +616,8 @@
612616 future = new CloseFuture.Forwarding(discardAvailableConnections());
613617
614618 return closeFuture.compareAndSet(null, future)
615- ? future
616- : closeFuture.get(); // We raced, it's ok, return the future that was actually set
619+ ? future
620+ : closeFuture.get(); // We raced, it's ok, return the future that was actually set
617621 }
618622
619623 public int opened() {
modified driver-core/src/main/java/com/datastax/driver/core/HostDistance.java +2 −2
@@ -19,7 +19,7 @@
1919 * The distance to a Cassandra node as assigned by a
2020 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy} (through its {@code
2121 * distance} method).
22- *
22+ * <p/>
2323 * The distance assigned to an host influences how many connections the driver
2424 * maintains towards this host. If for a given host the assigned {@code HostDistance}
2525 * is {@code LOCAL} or {@code REMOTE}, some connections will be maintained by
@@ -27,7 +27,7 @@
2727 * {@code LOCAL} host than to a {@code REMOTE} one (and thus well behaving
2828 * {@code LoadBalancingPolicy} should assign a {@code REMOTE} distance only to
2929 * hosts that are the less often queried).
30- * <p>
30+ * <p/>
3131 * However, if a host is assigned the distance {@code IGNORED}, no connection
3232 * to that host will maintained active. In other words, {@code IGNORED} should
3333 * be assigned to hosts that should not be used by this driver (because they
modified driver-core/src/main/java/com/datastax/driver/core/IdempotenceAwarePreparedStatement.java +1 −2
@@ -36,12 +36,11 @@
3636 * without changing the result beyond the initial application.
3737 * <p/>
3838 * See {@link com.datastax.driver.core.Statement#isIdempotent} for more explanations about this property.
39- *
39+ * <p/>
4040 * Please note that idempotence will be propagated to all {@link BoundStatement}s created from this prepared statement.
4141 *
4242 * @return whether this statement is idempotent, or {@code null} to use
4343 * {@link QueryOptions#getDefaultIdempotence()}.
44- *
4544 */
4645 public Boolean isIdempotent();
4746 }
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +11 −8
@@ -15,7 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
18+import java.util.Collection;
19+import java.util.Collections;
20+import java.util.HashMap;
21+import java.util.Map;
1922 import java.util.concurrent.ConcurrentHashMap;
2023
2124 /**
@@ -23,9 +26,9 @@
2326 */
2427 public class KeyspaceMetadata {
2528
26- public static final String KS_NAME = "keyspace_name";
27- private static final String DURABLE_WRITES = "durable_writes";
28- private static final String STRATEGY_CLASS = "strategy_class";
29+ public static final String KS_NAME = "keyspace_name";
30+ private static final String DURABLE_WRITES = "durable_writes";
31+ private static final String STRATEGY_CLASS = "strategy_class";
2932 private static final String STRATEGY_OPTIONS = "strategy_options";
3033
3134 private final String name;
@@ -139,11 +142,11 @@
139142 /**
140143 * Returns a {@code String} containing CQL queries representing this
141144 * keyspace and the user types and tables it contains.
142- * <p>
145+ * <p/>
143146 * In other words, this method returns the queries that would allow to
144147 * recreate the schema of this keyspace, along with all its user
145148 * types/tables.
146- * <p>
149+ * <p/>
147150 * Note that the returned String is formatted to be human readable (for
148151 * some definition of human readable at least).
149152 *
@@ -166,7 +169,7 @@
166169
167170 /**
168171 * Returns a CQL query representing this keyspace.
169- * <p>
172+ * <p/>
170173 * This method returns a single 'CREATE KEYSPACE' query with the options
171174 * corresponding to this keyspace definition.
172175 *
@@ -200,7 +203,7 @@
200203 if (o == null || getClass() != o.getClass())
201204 return false;
202205
203- KeyspaceMetadata that = (KeyspaceMetadata)o;
206+ KeyspaceMetadata that = (KeyspaceMetadata) o;
204207
205208 if (durableWrites != that.durableWrites)
206209 return false;
modified driver-core/src/main/java/com/datastax/driver/core/LatencyTracker.java +8 −8
@@ -18,7 +18,7 @@
1818 /**
1919 * Interface for objects that are interested in tracking the latencies
2020 * of the driver queries to each Cassandra nodes.
21- * <p>
21+ * <p/>
2222 * An implementation of this interface can be registered against a Cluster
2323 * object trough the {@link Cluster#register} method, after which the
2424 * {@link #update(Host, Statement, Exception, long)} method will be called after each query of the driver to a Cassandra
@@ -29,17 +29,17 @@
2929 /**
3030 * A method that is called after each request to a Cassandra node with
3131 * the duration of that operation.
32- * <p>
32+ * <p/>
3333 * Note that there is no guarantee that this method won't be called
3434 * concurrently by multiple threads, so implementations should synchronize
3535 * internally if need be.
3636 *
37- * @param host The Cassandra host on which a request has been performed.
38- * This parameter is never {@code null}.
39- * @param statement The {@link com.datastax.driver.core.Statement} that has been executed.
40- * This parameter is never {@code null}.
41- * @param exception An {@link Exception} thrown when receiving the response, or {@code null}
42- * if the response was successful.
37+ * @param host The Cassandra host on which a request has been performed.
38+ * This parameter is never {@code null}.
39+ * @param statement The {@link com.datastax.driver.core.Statement} that has been executed.
40+ * This parameter is never {@code null}.
41+ * @param exception An {@link Exception} thrown when receiving the response, or {@code null}
42+ * if the response was successful.
4343 * @param newLatencyNanos the latency in nanoseconds of the operation.
4444 * This latency corresponds to the time elapsed between
4545 * when the query was sent to {@code host} and
modified driver-core/src/main/java/com/datastax/driver/core/MD5Digest.java +7 −7
@@ -15,17 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-
2018 import com.datastax.driver.core.utils.Bytes;
2119
20+import java.util.Arrays;
21+
2222 /**
2323 * The result of the computation of an MD5 digest.
24- *
24+ * <p/>
2525 * A MD5 is really just a byte[] but arrays are a no go as map keys. We could
2626 * wrap it in a ByteBuffer but:
27- * 1. MD5Digest is a more explicit name than ByteBuffer to represent a md5.
28- * 2. Using our own class allows to use our FastByteComparison for equals.
27+ * 1. MD5Digest is a more explicit name than ByteBuffer to represent a md5.
28+ * 2. Using our own class allows to use our FastByteComparison for equals.
2929 */
3030 class MD5Digest {
3131
@@ -46,9 +46,9 @@
4646
4747 @Override
4848 public final boolean equals(Object o) {
49- if(!(o instanceof MD5Digest))
49+ if (!(o instanceof MD5Digest))
5050 return false;
51- MD5Digest that = (MD5Digest)o;
51+ MD5Digest that = (MD5Digest) o;
5252 // handles nulls properly
5353 return Arrays.equals(this.bytes, that.bytes);
5454 }
modified driver-core/src/main/java/com/datastax/driver/core/Message.java +57 −40
@@ -15,11 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.EnumSet;
20-import java.util.List;
21-import java.util.UUID;
22-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
2319 import io.netty.buffer.ByteBuf;
2420 import io.netty.channel.ChannelHandler;
2521 import io.netty.channel.ChannelHandlerContext;
@@ -28,7 +24,10 @@
2824 import org.slf4j.Logger;
2925 import org.slf4j.LoggerFactory;
3026
31-import com.datastax.driver.core.exceptions.DriverInternalError;
27+import java.nio.ByteBuffer;
28+import java.util.EnumSet;
29+import java.util.List;
30+import java.util.UUID;
3231
3332 /**
3433 * A message from the CQL binary protocol.
@@ -39,6 +38,7 @@
3938
4039 public interface Coder<R extends Request> {
4140 public void encode(R request, ByteBuf dest, ProtocolVersion version);
41+
4242 public int encodedSize(R request, ProtocolVersion version);
4343 }
4444
@@ -48,7 +48,8 @@
4848
4949 private volatile int streamId;
5050
51- protected Message() {}
51+ protected Message() {
52+ }
5253
5354 public Message setStreamId(int streamId) {
5455 this.streamId = streamId;
@@ -62,15 +63,15 @@
6263 public static abstract class Request extends Message {
6364
6465 public enum Type {
65- STARTUP (1, Requests.Startup.coder),
66- CREDENTIALS (4, Requests.Credentials.coder),
67- OPTIONS (5, Requests.Options.coder),
68- QUERY (7, Requests.Query.coder),
69- PREPARE (9, Requests.Prepare.coder),
70- EXECUTE (10, Requests.Execute.coder),
71- REGISTER (11, Requests.Register.coder),
72- BATCH (13, Requests.Batch.coder),
73- AUTH_RESPONSE (15, Requests.AuthResponse.coder);
66+ STARTUP(1, Requests.Startup.coder),
67+ CREDENTIALS(4, Requests.Credentials.coder),
68+ OPTIONS(5, Requests.Options.coder),
69+ QUERY(7, Requests.Query.coder),
70+ PREPARE(9, Requests.Prepare.coder),
71+ EXECUTE(10, Requests.Execute.coder),
72+ REGISTER(11, Requests.Register.coder),
73+ BATCH(13, Requests.Batch.coder),
74+ AUTH_RESPONSE(15, Requests.AuthResponse.coder);
7475
7576 public final int opcode;
7677 public final Coder<?> coder;
@@ -99,36 +100,51 @@
99100
100101 ConsistencyLevel consistency() {
101102 switch (this.type) {
102- case QUERY: return ((Requests.Query)this).options.consistency;
103- case EXECUTE: return ((Requests.Execute)this).options.consistency;
104- case BATCH: return ((Requests.Batch)this).options.consistency;
105- default: return null;
103+ case QUERY:
104+ return ((Requests.Query) this).options.consistency;
105+ case EXECUTE:
106+ return ((Requests.Execute) this).options.consistency;
107+ case BATCH:
108+ return ((Requests.Batch) this).options.consistency;
109+ default:
110+ return null;
106111 }
107112 }
108113
109114 ConsistencyLevel serialConsistency() {
110115 switch (this.type) {
111- case QUERY: return ((Requests.Query)this).options.serialConsistency;
112- case EXECUTE: return ((Requests.Execute)this).options.serialConsistency;
113- case BATCH: return ((Requests.Batch)this).options.serialConsistency;
114- default: return null;
116+ case QUERY:
117+ return ((Requests.Query) this).options.serialConsistency;
118+ case EXECUTE:
119+ return ((Requests.Execute) this).options.serialConsistency;
120+ case BATCH:
121+ return ((Requests.Batch) this).options.serialConsistency;
122+ default:
123+ return null;
115124 }
116125 }
117126
118127 long defaultTimestamp() {
119128 switch (this.type) {
120- case QUERY: return ((Requests.Query)this).options.defaultTimestamp;
121- case EXECUTE: return ((Requests.Execute)this).options.defaultTimestamp;
122- case BATCH: return ((Requests.Batch)this).options.defaultTimestamp;
123- default: return 0;
129+ case QUERY:
130+ return ((Requests.Query) this).options.defaultTimestamp;
131+ case EXECUTE:
132+ return ((Requests.Execute) this).options.defaultTimestamp;
133+ case BATCH:
134+ return ((Requests.Batch) this).options.defaultTimestamp;
135+ default:
136+ return 0;
124137 }
125138 }
126139
127140 ByteBuffer pagingState() {
128141 switch (this.type) {
129- case QUERY: return ((Requests.Query)this).options.pagingState;
130- case EXECUTE: return ((Requests.Execute)this).options.pagingState;
131- default: return null;
142+ case QUERY:
143+ return ((Requests.Query) this).options.pagingState;
144+ case EXECUTE:
145+ return ((Requests.Execute) this).options.pagingState;
146+ default:
147+ return null;
132148 }
133149 }
134150
@@ -144,19 +160,20 @@
144160 public static abstract class Response extends Message {
145161
146162 public enum Type {
147- ERROR (0, Responses.Error.decoder),
148- READY (2, Responses.Ready.decoder),
149- AUTHENTICATE (3, Responses.Authenticate.decoder),
150- SUPPORTED (6, Responses.Supported.decoder),
151- RESULT (8, Responses.Result.decoder),
152- EVENT (12, Responses.Event.decoder),
153- AUTH_CHALLENGE (14, Responses.AuthChallenge.decoder),
154- AUTH_SUCCESS (16, Responses.AuthSuccess.decoder);
163+ ERROR(0, Responses.Error.decoder),
164+ READY(2, Responses.Ready.decoder),
165+ AUTHENTICATE(3, Responses.Authenticate.decoder),
166+ SUPPORTED(6, Responses.Supported.decoder),
167+ RESULT(8, Responses.Result.decoder),
168+ EVENT(12, Responses.Event.decoder),
169+ AUTH_CHALLENGE(14, Responses.AuthChallenge.decoder),
170+ AUTH_SUCCESS(16, Responses.AuthSuccess.decoder);
155171
156172 public final int opcode;
157173 public final Decoder<?> decoder;
158174
159175 private static final Type[] opcodeIdx;
176+
160177 static {
161178 int maxOpcode = -1;
162179 for (Type type : Type.values())
@@ -235,7 +252,7 @@
235252 flags.add(Frame.Header.Flag.TRACING);
236253
237254 @SuppressWarnings("unchecked")
238- Coder<Request> coder = (Coder<Request>)request.type.coder;
255+ Coder<Request> coder = (Coder<Request>) request.type.coder;
239256 ByteBuf body = ctx.alloc().buffer(coder.encodedSize(request, protocolVersion));
240257 coder.encode(request, body, protocolVersion);
241258
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +45 −50
@@ -15,6 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.collect.ImmutableMap;
19+import com.google.common.collect.ImmutableSet;
20+import com.google.common.collect.Maps;
21+import org.slf4j.Logger;
22+import org.slf4j.LoggerFactory;
23+
1824 import java.net.InetSocketAddress;
1925 import java.nio.ByteBuffer;
2026 import java.util.*;
@@ -22,15 +28,7 @@
2228 import java.util.concurrent.ConcurrentMap;
2329 import java.util.regex.Pattern;
2430
25-import com.google.common.collect.ImmutableMap;
26-import com.google.common.collect.ImmutableSet;
27-import com.google.common.collect.Maps;
28-import org.slf4j.Logger;
29-import org.slf4j.LoggerFactory;
30-
31-import static com.datastax.driver.core.SchemaElement.KEYSPACE;
32-import static com.datastax.driver.core.SchemaElement.TABLE;
33-import static com.datastax.driver.core.SchemaElement.TYPE;
31+import static com.datastax.driver.core.SchemaElement.*;
3432
3533 /**
3634 * Keeps metadata on the connected cluster, including known nodes and schema definitions.
@@ -112,7 +110,7 @@
112110 private Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupByKeyspaceAndTable(ResultSet rows, VersionNumber cassandraVersion) {
113111 if (rows == null)
114112 return Collections.emptyMap();
115-
113+
116114 Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupedRows = new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>();
117115 for (Row row : rows) {
118116 String ksName = row.getString(KeyspaceMetadata.KS_NAME);
@@ -156,7 +154,7 @@
156154
157155 private Map<String, TableMetadata> buildTables(KeyspaceMetadata keyspace, List<Row> tableRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) {
158156 Map<String, TableMetadata> tables = new LinkedHashMap<String, TableMetadata>();
159- if(tableRows != null) {
157+ if (tableRows != null) {
160158 for (Row tableDef : tableRows) {
161159 String cfName = tableDef.getString(TableMetadata.CF_NAME);
162160 try {
@@ -185,8 +183,8 @@
185183 } catch (RuntimeException e) {
186184 // See ControlConnection#refreshSchema for why we'd rather not probably this further
187185 logger.error(String.format("Error parsing schema for table %s.%s: "
188- + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
189- keyspace.getName(), cfName, keyspace.getName(), cfName), e);
186+ + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
187+ keyspace.getName(), cfName, keyspace.getName(), cfName), e);
190188 }
191189 }
192190 }
@@ -209,11 +207,11 @@
209207 * This method also takes care of triggering the relevant events
210208 * as the updates take place.
211209 *
212- * @param oldKeyspaces the set of keyspaces to be updated.
213- * @param newKeyspaces the temporary set of keyspaces built with information gathered
214- * from schema tables.
210+ * @param oldKeyspaces the set of keyspaces to be updated.
211+ * @param newKeyspaces the temporary set of keyspaces built with information gathered
212+ * from schema tables.
215213 * @param keyspaceToRebuild If we are rebuilding just one keyspace, the update operation will be limited
216- * to this keyspace only (in which case {@code newKeyspaces} shoudl contain only one entry for it)
214+ * to this keyspace only (in which case {@code newKeyspaces} shoudl contain only one entry for it)
217215 */
218216 private void updateKeyspaces(Map<String, KeyspaceMetadata> oldKeyspaces, Map<String, KeyspaceMetadata> newKeyspaces, String keyspaceToRebuild) {
219217 Iterator<KeyspaceMetadata> it = oldKeyspaces.values().iterator();
@@ -246,11 +244,11 @@
246244 * This method also takes care of triggering the relevant events
247245 * as the updates take place.
248246 *
249- * @param oldTables the set of tables to be updated.
250- * @param newTables the temporary set of tables built with information gathered
251- * from schema tables.
247+ * @param oldTables the set of tables to be updated.
248+ * @param newTables the temporary set of tables built with information gathered
249+ * from schema tables.
252250 * @param tableToRebuild If we are rebuilding just one table, the update operation will be limited
253- * to this table only (in which case {@code newTables} shoudl contain only one entry for it)
251+ * to this table only (in which case {@code newTables} shoudl contain only one entry for it)
254252 */
255253 private void updateTables(Map<String, TableMetadata> oldTables, Map<String, TableMetadata> newTables, String tableToRebuild) {
256254 Iterator<TableMetadata> it = oldTables.values().iterator();
@@ -353,8 +351,8 @@
353351 return;
354352
355353 Token.Factory factory = partitioner == null
356- ? (tokenMap == null ? null : tokenMap.factory)
357- : Token.getFactory(partitioner);
354+ ? (tokenMap == null ? null : tokenMap.factory)
355+ : Token.getFactory(partitioner);
358356 if (factory == null)
359357 return;
360358
@@ -426,7 +424,7 @@
426424
427425 /**
428426 * Quote a keyspace, table or column identifier to make it case sensitive.
429- * <p>
427+ * <p/>
430428 * CQL identifiers, including keyspace, table and column ones, are case insensitive
431429 * by default. Case sensitive identifiers can however be provided by enclosing
432430 * the identifier in double quotes (see the
@@ -446,7 +444,7 @@
446444
447445 /**
448446 * Returns the token ranges that define data distribution in the ring.
449- * <p>
447+ * <p/>
450448 * Note that this information is refreshed asynchronously by the control
451449 * connection, when schema or ring topology changes. It might occasionally
452450 * be stale.
@@ -462,13 +460,13 @@
462460 /**
463461 * Returns the token ranges that are replicated on the given host, for the given
464462 * keyspace.
465- * <p>
463+ * <p/>
466464 * Note that this information is refreshed asynchronously by the control
467465 * connection, when schema or ring topology changes. It might occasionally
468466 * be stale (or even empty).
469467 *
470468 * @param keyspace the name of the keyspace to get token ranges for.
471- * @param host the host.
469+ * @param host the host.
472470 * @return the (immutable) set of token ranges for {@code host} as known
473471 * by the driver. Note that the result might be stale or empty if metadata
474472 * was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -491,14 +489,14 @@
491489
492490 /**
493491 * Returns the set of hosts that are replica for a given partition key.
494- * <p>
492+ * <p/>
495493 * Note that this information is refreshed asynchronously by the control
496494 * connection, when schema or ring topology changes. It might occasionally
497495 * be stale (or even empty).
498496 *
499- * @param keyspace the name of the keyspace to get replicas for.
497+ * @param keyspace the name of the keyspace to get replicas for.
500498 * @param partitionKey the partition key for which to find the set of
501- * replica.
499+ * replica.
502500 * @return the (immutable) set of replicas for {@code partitionKey} as known
503501 * by the driver. Note that the result might be stale or empty if metadata was
504502 * explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -516,13 +514,13 @@
516514
517515 /**
518516 * Returns the set of hosts that are replica for a given token range.
519- * <p>
517+ * <p/>
520518 * Note that this information is refreshed asynchronously by the control
521519 * connection, when schema or ring topology changes. It might occasionally
522520 * be stale (or even empty).
523521 *
524522 * @param keyspace the name of the keyspace to get replicas for.
525- * @param range the token range.
523+ * @param range the token range.
526524 * @return the (immutable) set of replicas for {@code range} as known by the driver.
527525 * Note that the result might be stale or empty if metadata was explicitly disabled
528526 * with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -567,7 +565,7 @@
567565
568566 /**
569567 * Checks whether hosts that are currently up agree on the schema definition.
570- * <p>
568+ * <p/>
571569 * This method performs a one-time check only, without any form of retry; therefore {@link Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int)}
572570 * does not apply in this case.
573571 *
@@ -587,7 +585,7 @@
587585 * Returns the metadata of a keyspace given its name.
588586 *
589587 * @param keyspace the name of the keyspace for which metadata should be
590- * returned.
588+ * returned.
591589 * @return the metadata of the requested keyspace or {@code null} if {@code
592590 * keyspace} is not a known keyspace. Note that the result might be stale or null if
593591 * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -624,13 +622,13 @@
624622 /**
625623 * Returns a {@code String} containing CQL queries representing the schema
626624 * of this cluster.
627- *
625+ * <p/>
628626 * In other words, this method returns the queries that would allow to
629627 * recreate the schema of this cluster.
630- *
628+ * <p/>
631629 * Note that the returned String is formatted to be human readable (for
632630 * some definition of human readable at least).
633- *
631+ * <p/>
634632 * It might be stale or empty if metadata was explicitly disabled with
635633 * {@link QueryOptions#setMetadataEnabled(boolean)}.
636634 *
@@ -652,10 +650,9 @@
652650 *
653651 * @param tokenStr the string representation.
654652 * @return the token.
655- *
656653 * @throws IllegalStateException if the token factory was not initialized. This would typically
657- * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
658- * before startup.
654+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
655+ * before startup.
659656 */
660657 public Token newToken(String tokenStr) {
661658 TokenMap current = tokenMap;
@@ -669,12 +666,11 @@
669666 * Builds a new {@link TokenRange}.
670667 *
671668 * @param start the start token.
672- * @param end the end token.
669+ * @param end the end token.
673670 * @return the range.
674- *
675671 * @throws IllegalStateException if the token factory was not initialized. This would typically
676- * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
677- * before startup.
672+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
673+ * before startup.
678674 */
679675 public TokenRange newTokenRange(Token start, Token end) {
680676 TokenMap current = tokenMap;
@@ -747,14 +743,13 @@
747743 Map<String, Map<Token, Set<Host>>> tokenToHosts = new HashMap<String, Map<Token, Set<Host>>>();
748744 Map<ReplicationStrategy, Map<Token, Set<Host>>> replStrategyToHosts = new HashMap<ReplicationStrategy, Map<Token, Set<Host>>>();
749745 Map<String, Map<Host, Set<TokenRange>>> hostsToRanges = new HashMap<String, Map<Host, Set<TokenRange>>>();
750- for (KeyspaceMetadata keyspace : keyspaces)
751- {
746+ for (KeyspaceMetadata keyspace : keyspaces) {
752747 ReplicationStrategy strategy = keyspace.replicationStrategy();
753748 Map<Token, Set<Host>> ksTokens = replStrategyToHosts.get(strategy);
754749 if (ksTokens == null) {
755750 ksTokens = (strategy == null)
756- ? makeNonReplicatedMap(tokenToPrimary)
757- : strategy.computeTokenToReplicaMap(keyspace.getName(), tokenToPrimary, ring);
751+ ? makeNonReplicatedMap(tokenToPrimary)
752+ : strategy.computeTokenToReplicaMap(keyspace.getName(), tokenToPrimary, ring);
758753 replStrategyToHosts.put(strategy, ksTokens);
759754 }
760755
@@ -807,8 +802,8 @@
807802 private static Set<TokenRange> makeTokenRanges(List<Token> ring, Token.Factory factory) {
808803 ImmutableSet.Builder<TokenRange> builder = ImmutableSet.builder();
809804 // JAVA-684: if there is only one token, return the range ]minToken, minToken]
810- if(ring.size() == 1) {
811- builder.add(new TokenRange(factory.minToken(), factory.minToken(), factory));
805+ if (ring.size() == 1) {
806+ builder.add(new TokenRange(factory.minToken(), factory.minToken(), factory));
812807 } else {
813808 for (int i = 0; i < ring.size(); i++) {
814809 Token start = ring.get(i);
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +16 −17
@@ -15,20 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.HashSet;
19-import java.util.Set;
20-
2118 import com.codahale.metrics.*;
22-
2319 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2420
21+import java.util.HashSet;
22+import java.util.Set;
23+
2524 /**
2625 * Metrics exposed by the driver.
27- * <p>
26+ * <p/>
2827 * The metrics exposed by this class use the <a href="http://metrics.codahale.com/">Metrics</a>
2928 * library and you should refer its <a href="http://metrics.codahale.com/manual/">documentation</a>
3029 * for details on how to handle the exposed metric objects.
31- * <p>
30+ * <p/>
3231 * By default, metrics are exposed through JMX, which is very useful for
3332 * development and browsing, but for production environments you may want to
3433 * have a look at the <a href="http://metrics.codahale.com/manual/core/#reporters">reporters</a>
@@ -93,7 +92,7 @@
9392 }
9493 });
9594
96- private final Gauge<Integer> reconnectionSchedulerQueueSize= registry.register("reconnection-scheduler-task-count", new Gauge<Integer>() {
95+ private final Gauge<Integer> reconnectionSchedulerQueueSize = registry.register("reconnection-scheduler-task-count", new Gauge<Integer>() {
9796 @Override
9897 public Integer getValue() {
9998 return manager.reconnectionExecutor.getQueue().size();
@@ -119,17 +118,17 @@
119118
120119 /**
121120 * Returns the registry containing all metrics.
122- * <p>
121+ * <p/>
123122 * The metrics registry allows you to easily use the reporters that ship
124123 * with <a href="http://metrics.codahale.com/manual/core/#reporters">Metrics</a>
125124 * or a custom written one.
126- * <p>
125+ * <p/>
127126 * For instance, if {@code metrics} is {@code this} object, you could export the
128127 * metrics to csv files using:
129128 * <pre>
130129 * com.codahale.metrics.CsvReporter.forRegistry(metrics.getRegistry()).build(new File("measurements/")).start(1, TimeUnit.SECONDS);
131130 * </pre>
132- * <p>
131+ * <p/>
133132 * If you already have a {@code MetricRegistry} in your application and wish to
134133 * add the driver's metrics to it, the recommended approach is to use a listener:
135134 * <pre>
@@ -161,12 +160,12 @@
161160
162161 /**
163162 * Returns metrics on the user requests performed on the Cluster.
164- * <p>
163+ * <p/>
165164 * This metric exposes
166165 * <ul>
167- * <li>the total number of requests.</li>
168- * <li>the requests rate (in requests per seconds), including 1, 5 and 15 minute rates.</li>
169- * <li>the mean, min and max latencies, as well as latency at a given percentile.</li>
166+ * <li>the total number of requests.</li>
167+ * <li>the requests rate (in requests per seconds), including 1, 5 and 15 minute rates.</li>
168+ * <li>the mean, min and max latencies, as well as latency at a given percentile.</li>
170169 * </ul>
171170 *
172171 * @return a {@code Timer} metric object exposing the rate and latency for
@@ -216,7 +215,7 @@
216215
217216 /**
218217 * Returns the total number of currently "trashed" connections to Cassandra hosts.
219- * <p>
218+ * <p/>
220219 * When the load to a host decreases, the driver will reclaim some connections in order to save
221220 * resources. No requests are sent to these connections anymore, but they are kept open for an
222221 * additional amount of time ({@link PoolingOptions#getIdleTimeoutSeconds()}), in case the load
@@ -289,11 +288,11 @@
289288
290289 /**
291290 * Returns the number of connection to Cassandra nodes errors.
292- * <p>
291+ * <p/>
293292 * This represents the number of times that a request to a Cassandra node
294293 * has failed due to a connection problem. This thus also corresponds to
295294 * how often the driver had to pick a fallback host for a request.
296- * <p>
295+ * <p/>
297296 * You can expect a few connection errors when a Cassandra node fails
298297 * (or is stopped) ,but if that number grows continuously you likely have
299298 * a problem.
modified driver-core/src/main/java/com/datastax/driver/core/MetricsOptions.java +3 −6
@@ -25,8 +25,7 @@
2525 /**
2626 * Creates a new {@code MetricsOptions} object with default values.
2727 */
28- public MetricsOptions()
29- {
28+ public MetricsOptions() {
3029 this(true);
3130 }
3231
@@ -35,8 +34,7 @@
3534 *
3635 * @param jmxEnabled whether to enable JMX reporting or not.
3736 */
38- public MetricsOptions(boolean jmxEnabled)
39- {
37+ public MetricsOptions(boolean jmxEnabled) {
4038 this.jmxEnabled = jmxEnabled;
4139 }
4240
@@ -45,8 +43,7 @@
4543 *
4644 * @return whether JMX reporting is enabled.
4745 */
48- public boolean isJMXReportingEnabled()
49- {
46+ public boolean isJMXReportingEnabled() {
5047 return jmxEnabled;
5148 }
5249 }
modified driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +36 −41
@@ -15,30 +15,25 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.ThreadFactory;
19-import java.util.concurrent.TimeUnit;
20-
21-import static java.util.concurrent.TimeUnit.SECONDS;
22-
2318 import io.netty.bootstrap.Bootstrap;
2419 import io.netty.buffer.PooledByteBufAllocator;
2520 import io.netty.channel.ChannelOption;
2621 import io.netty.channel.EventLoopGroup;
27-import io.netty.channel.nio.NioEventLoopGroup;
2822 import io.netty.channel.socket.SocketChannel;
29-import io.netty.channel.socket.nio.NioSocketChannel;
3023 import io.netty.util.HashedWheelTimer;
3124 import io.netty.util.Timer;
3225
26+import java.util.concurrent.ThreadFactory;
27+
3328 /**
3429 * A set of hooks that allow clients to customize the driver's underlying Netty layer.
35- * <p>
30+ * <p/>
3631 * Clients that need to hook into the driver's underlying Netty layer can
3732 * subclass this class and provide the necessary customization by overriding
3833 * its methods.
39- * <p>
34+ * <p/>
4035 * Typically, clients would register this class with {@link Cluster#builder()}:
41- *
36+ * <p/>
4237 * <pre>
4338 * NettyOptions nettyOptions = ...
4439 * Cluster cluster = Cluster.builder()
@@ -46,24 +41,24 @@
4641 * .withNettyOptions(nettyOptions)
4742 * .build();
4843 * </pre>
49- *
44+ * <p/>
5045 * <strong>Extending the NettyOptions API</strong>
51- * <p>
46+ * <p/>
5247 * Contrary to other driver options, the options available in this class should
5348 * be considered as advanced features and as such, <em>they should only be
5449 * modified by expert users</em>.
55- * <p>
50+ * <p/>
5651 * <strong>A misconfiguration introduced by the means of this API can have unexpected results
5752 * and cause the driver to completely fail to connect.</strong>
58- * <p>
53+ * <p/>
5954 * Moreover, since versions 2.0.9 and 2.1.4 (see JAVA-538),
6055 * the driver is available in two different flavors: with a standard Maven dependency on Netty,
6156 * or with a "shaded" (internalized) Netty dependency.
62- * <p>
57+ * <p/>
6358 * Given that NettyOptions API exposes Netty classes ({@link SocketChannel}, etc.),
6459 * <em>it should only be extended by clients using the non-shaded
6560 * version of driver</em>.
66- * <p>
61+ * <p/>
6762 * <strong>Extending this API with shaded Netty classes is not supported,
6863 * and in particular for OSGi applications, it is likely that such a configuration would lead to
6964 * compile and/or runtime errors.</strong>
@@ -79,15 +74,15 @@
7974
8075 /**
8176 * Return the {@code EventLoopGroup} instance to use.
82- * <p>
77+ * <p/>
8378 * This hook is invoked only once at {@link Cluster} initialization;
8479 * the returned instance will be kept in use throughout the cluster lifecycle.
85- * <p>
80+ * <p/>
8681 * Typically, implementors would return a newly-created instance;
8782 * it is however possible to re-use a shared instance, but in this
8883 * case implementors should also override {@link #onClusterClose(EventLoopGroup)}
8984 * to prevent the shared instance to be closed when the cluster is closed.
90- * <p>
85+ * <p/>
9186 * The default implementation returns a new instance of {@code io.netty.channel.epoll.EpollEventLoopGroup}
9287 * if {@link NettyUtil#isEpollAvailable() epoll is available},
9388 * or {@code io.netty.channel.nio.NioEventLoopGroup} otherwise.
@@ -103,11 +98,11 @@
10398
10499 /**
105100 * Return the specific {@code SocketChannel} subclass to use.
106- * <p>
101+ * <p/>
107102 * This hook is invoked only once at {@link Cluster} initialization;
108103 * the returned instance will then be used each time the driver creates a new {@link Connection}
109104 * and configures a new instance of {@link Bootstrap} for it.
110- * <p>
105+ * <p/>
111106 * The default implementation returns {@code io.netty.channel.epoll.EpollSocketChannel} if {@link NettyUtil#isEpollAvailable() epoll is available},
112107 * or {@code io.netty.channel.socket.nio.NioSocketChannel} otherwise.
113108 *
@@ -120,13 +115,13 @@
120115 /**
121116 * Hook invoked each time the driver creates a new {@link Connection}
122117 * and configures a new instance of {@link Bootstrap} for it.
123- * <p>
118+ * <p/>
124119 * This hook is guaranteed to be called <em>after</em> the driver has applied all
125120 * {@link SocketOptions}s.
126- * <p>
121+ * <p/>
127122 * This is a good place to add extra {@link io.netty.channel.ChannelHandler ChannelOption}s to the boostrap; e.g.
128123 * plug a custom {@link io.netty.buffer.ByteBufAllocator ByteBufAllocator} implementation:
129- *
124+ * <p/>
130125 * <pre>
131126 * ByteBufAllocator myCustomByteBufAllocator = ...
132127 *
@@ -134,7 +129,7 @@
134129 * bootstrap.option(ChannelOption.ALLOCATOR, myCustomByteBufAllocator);
135130 * }
136131 * </pre>
137- *
132+ * <p/>
138133 * Note that the default implementation of this method configures a pooled {@code ByteBufAllocator} (Netty 4.0
139134 * defaults to unpooled). If you override this method to set unrelated options, make sure you call
140135 * {@code super.afterBootstrapInitialized(bootstrap)}.
@@ -149,21 +144,21 @@
149144 /**
150145 * Hook invoked each time the driver creates a new {@link Connection}
151146 * and initializes the {@link SocketChannel channel}.
152- * <p>
147+ * <p/>
153148 * This hook is guaranteed to be called <em>after</em> the driver has registered
154149 * all its internal channel handlers, and applied the configured {@link SSLOptions}, if any.
155- * <p>
150+ * <p/>
156151 * This is a good place to add extra {@link io.netty.channel.ChannelHandler ChannelHandler}s
157152 * to the channel's pipeline; e.g. to add a custom SSL handler to the beginning of the handler chain,
158153 * do the following:
159- *
154+ * <p/>
160155 * <pre>
161156 * ChannelPipeline pipeline = channel.pipeline();
162157 * SSLEngine myCustomSSLEngine = ...
163158 * SslHandler myCustomSSLHandler = new SslHandler(myCustomSSLEngine);
164159 * pipeline.addFirst("ssl", myCustomSSLHandler);
165160 * </pre>
166- *
161+ * <p/>
167162 * Note: if you intend to provide your own SSL implementation,
168163 * do not enable the driver's built-in {@link SSLOptions} at the same time.
169164 *
@@ -176,15 +171,15 @@
176171
177172 /**
178173 * Hook invoked when the cluster is shutting down after a call to {@link Cluster#close()}.
179- * <p>
174+ * <p/>
180175 * This is guaranteed to be called only after all connections have been individually
181176 * closed, and their channels closed, and only once per {@link EventLoopGroup} instance.
182- * <p>
177+ * <p/>
183178 * This gives the implementor a chance to close the {@link EventLoopGroup} properly, if required.
184- * <p>
179+ * <p/>
185180 * The default implementation initiates a {@link EventLoopGroup#shutdownGracefully() graceful shutdown}
186181 * of the passed {@link EventLoopGroup}, then waits uninterruptibly for the shutdown to complete or timeout.
187- * <p>
182+ * <p/>
188183 * Implementation note: if the {@link EventLoopGroup} instance is being shared, or used for other purposes than to
189184 * coordinate Netty events for the current cluster, then it should not be shut down here;
190185 * subclasses would have to override this method accordingly to take the appropriate action.
@@ -197,17 +192,17 @@
197192
198193 /**
199194 * Return the {@link Timer} instance used by Read Timeouts and Speculative Execution.
200- * <p>
195+ * <p/>
201196 * This hook is invoked only once at {@link Cluster} initialization;
202197 * the returned instance will be kept in use throughout the cluster lifecycle.
203- * <p>
198+ * <p/>
204199 * Typically, implementors would return a newly-created instance;
205200 * it is however possible to re-use a shared instance, but in this
206201 * case implementors should also override {@link #onClusterClose(Timer)}
207202 * to prevent the shared instance to be closed when the cluster is closed.
208- * <p>
203+ * <p/>
209204 * The default implementation returns a new instance created by {@link HashedWheelTimer#HashedWheelTimer(ThreadFactory)}.
210- *
205+ *
211206 * @param threadFactory The {@link ThreadFactory} to use when creating a new {@link HashedWheelTimer} instance;
212207 * The driver will provide its own internal thread factory here.
213208 * It is safe to ignore it and use another thread factory.
@@ -219,14 +214,14 @@
219214
220215 /**
221216 * Hook invoked when the cluster is shutting down after a call to {@link Cluster#close()}.
222- * <p>
217+ * <p/>
223218 * This is guaranteed to be called only after all connections have been individually
224219 * closed, and their channels closed, and only once per {@link Timer} instance.
225- * <p>
220+ * <p/>
226221 * This gives the implementor a chance to close the {@link Timer} properly, if required.
227- * <p>
222+ * <p/>
228223 * The default implementation calls a {@link Timer#stop()} of the passed {@link Timer} instance.
229- * <p>
224+ * <p/>
230225 * Implementation note: if the {@link Timer} instance is being shared, or used for other purposes than to
231226 * schedule actions for the current cluster, than it should not be stopped here;
232227 * subclasses would have to override this method accordingly to take the appropriate action.
modified driver-core/src/main/java/com/datastax/driver/core/NettyUtil.java +14 −15
@@ -15,10 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.lang.reflect.Constructor;
19-import java.util.Locale;
20-import java.util.concurrent.ThreadFactory;
21-
2218 import com.google.common.base.Throwables;
2319 import io.netty.channel.EventLoopGroup;
2420 import io.netty.channel.nio.NioEventLoopGroup;
@@ -27,6 +23,10 @@
2723 import org.slf4j.Logger;
2824 import org.slf4j.LoggerFactory;
2925
26+import java.lang.reflect.Constructor;
27+import java.util.Locale;
28+import java.util.concurrent.ThreadFactory;
29+
3030 /**
3131 * A set of utilities related to the underlying Netty layer.
3232 */
@@ -45,7 +45,7 @@
4545
4646 private static final Class<? extends SocketChannel> EPOLL_CHANNEL_CLASS;
4747
48- private static final Class[] EVENT_GROUP_ARGUMENTS = { int.class, ThreadFactory.class };
48+ private static final Class[] EVENT_GROUP_ARGUMENTS = {int.class, ThreadFactory.class};
4949
5050 static {
5151 boolean shaded;
@@ -68,13 +68,13 @@
6868 Class<?> epoll = Class.forName("io.netty.channel.epoll.Epoll");
6969 if (FORCE_NIO) {
7070 LOGGER.info("Found Netty's native epoll transport in the classpath, "
71- + "but NIO was forced through the FORCE_NIO system property.");
71+ + "but NIO was forced through the FORCE_NIO system property.");
7272 } else if (!System.getProperty("os.name", "").toLowerCase(Locale.US).equals("linux")) {
7373 LOGGER.warn("Found Netty's native epoll transport, but not running on linux-based operating " +
74- "system. Using NIO instead.");
75- } else if (!(Boolean)epoll.getMethod("isAvailable").invoke(null)) {
74+ "system. Using NIO instead.");
75+ } else if (!(Boolean) epoll.getMethod("isAvailable").invoke(null)) {
7676 LOGGER.warn("Found Netty's native epoll transport in the classpath, but epoll is not available. "
77- + "Using NIO instead.", (Throwable)epoll.getMethod("unavailabilityCause").invoke(null));
77+ + "Using NIO instead.", (Throwable) epoll.getMethod("unavailabilityCause").invoke(null));
7878 } else {
7979 LOGGER.info("Found Netty's native epoll transport in the classpath, using it");
8080 useEpoll = true;
@@ -86,16 +86,16 @@
8686 }
8787 } else {
8888 LOGGER.info("Detected shaded Netty classes in the classpath; native epoll transport will not work properly, "
89- + "defaulting to NIO.");
89+ + "defaulting to NIO.");
9090 }
9191 USE_EPOLL = useEpoll;
9292 Constructor<? extends EventLoopGroup> constructor = null;
9393 Class<? extends SocketChannel> channelClass = null;
9494 if (USE_EPOLL) {
9595 try {
96- channelClass = (Class<? extends SocketChannel>)Class.forName("io.netty.channel.epoll.EpollSocketChannel");
96+ channelClass = (Class<? extends SocketChannel>) Class.forName("io.netty.channel.epoll.EpollSocketChannel");
9797 Class<?> epoolEventLoupGroupClass = Class.forName("io.netty.channel.epoll.EpollEventLoopGroup");
98- constructor = (Constructor<? extends EventLoopGroup>)epoolEventLoupGroupClass.getDeclaredConstructor(EVENT_GROUP_ARGUMENTS);
98+ constructor = (Constructor<? extends EventLoopGroup>) epoolEventLoupGroupClass.getDeclaredConstructor(EVENT_GROUP_ARGUMENTS);
9999 } catch (Exception e) {
100100 throw new AssertionError("Netty's native epoll is in use but cannot locate Epoll classes, this should not happen: " + e);
101101 }
@@ -105,7 +105,6 @@
105105 }
106106
107107 /**
108- *
109108 * @return true if the current driver bundle is using shaded Netty classes, false otherwise.
110109 */
111110
@@ -122,7 +121,7 @@
122121
123122 /**
124123 * Return a new instance of {@link EventLoopGroup}.
125- * <p>
124+ * <p/>
126125 * Returns an instance of {@link io.netty.channel.epoll.EpollEventLoopGroup} if {@link #isEpollAvailable() epoll is available},
127126 * or an instance of {@link NioEventLoopGroup} otherwise.
128127 *
@@ -143,7 +142,7 @@
143142
144143 /**
145144 * Return the SocketChannel class to use.
146- * <p>
145+ * <p/>
147146 * Returns an instance of {@link io.netty.channel.epoll.EpollSocketChannel} if {@link #isEpollAvailable() epoll is available},
148147 * or an instance of {@link NioSocketChannel} otherwise.
149148 *
modified driver-core/src/main/java/com/datastax/driver/core/PagingState.java +14 −16
@@ -16,20 +16,20 @@
1616
1717 package com.datastax.driver.core;
1818
19+import com.datastax.driver.core.exceptions.PagingStateException;
20+import com.datastax.driver.core.utils.Bytes;
21+
1922 import java.nio.ByteBuffer;
2023 import java.security.MessageDigest;
2124 import java.security.NoSuchAlgorithmException;
2225 import java.util.Arrays;
2326
24-import com.datastax.driver.core.exceptions.PagingStateException;
25-import com.datastax.driver.core.utils.Bytes;
26-
2727 /**
2828 * The paging state of a query.
29- *
29+ * <p/>
3030 * This object represents the next page to be fetched if the query is
3131 * multi page. It can be saved and reused later on the same statement.
32- *
32+ * <p/>
3333 * The PagingState can be serialized and deserialized either as a String
3434 * or as a byte array.
3535 *
@@ -59,15 +59,15 @@
5959 int hashSize = pagingStateBB.getShort();
6060 if (pagingSize + hashSize != pagingStateBB.remaining() && pagingSize + hashSize + 2 != pagingStateBB.remaining()) {
6161 throw new PagingStateException("Cannot deserialize paging state, invalid format. "
62- + "The serialized form was corrupted, or not initially generated from a PagingState object.");
62+ + "The serialized form was corrupted, or not initially generated from a PagingState object.");
6363 }
6464 this.pagingState = new byte[pagingSize];
6565 pagingStateBB.get(this.pagingState);
6666 this.hash = new byte[hashSize];
6767 pagingStateBB.get(this.hash);
6868 this.protocolVersion = (pagingStateBB.remaining() > 0)
69- ? ProtocolVersion.fromInt(pagingStateBB.getShort())
70- : ProtocolVersion.V2;
69+ ? ProtocolVersion.fromInt(pagingStateBB.getShort())
70+ : ProtocolVersion.V2;
7171 }
7272
7373 private byte[] hash(Statement statement, ProtocolVersion protocolVersion) {
@@ -78,12 +78,12 @@
7878 try {
7979 md = MessageDigest.getInstance("MD5");
8080 if (statement instanceof BoundStatement) {
81- BoundStatement bs = ((BoundStatement)statement);
81+ BoundStatement bs = ((BoundStatement) statement);
8282 md.update(bs.preparedStatement().getQueryString().getBytes());
8383 values = bs.wrapper.values;
8484 } else {
8585 //it is a RegularStatement since Batch statements are not allowed
86- RegularStatement rs = (RegularStatement)statement;
86+ RegularStatement rs = (RegularStatement) statement;
8787 md.update(rs.getQueryString().getBytes());
8888 values = rs.getValues(protocolVersion);
8989 }
@@ -109,13 +109,13 @@
109109 private ByteBuffer generateCompleteOutput() {
110110 ByteBuffer res = ByteBuffer.allocate(pagingState.length + hash.length + 6);
111111
112- res.putShort((short)pagingState.length);
113- res.putShort((short)hash.length);
112+ res.putShort((short) pagingState.length);
113+ res.putShort((short) hash.length);
114114
115115 res.put(pagingState);
116116 res.put(hash);
117117
118- res.putShort((short)protocolVersion.toInt());
118+ res.putShort((short) protocolVersion.toInt());
119119
120120 res.rewind();
121121
@@ -136,7 +136,6 @@
136136 *
137137 * @param string the string value.
138138 * @return the PagingState object created.
139- *
140139 * @throws PagingStateException if the string does not have the correct format.
141140 */
142141 public static PagingState fromString(String string) {
@@ -145,7 +144,7 @@
145144 return new PagingState(complete);
146145 } catch (Exception e) {
147146 throw new PagingStateException("Cannot deserialize paging state, invalid format. "
148- + "The serialized form was corrupted, or not initially generated from a PagingState object.", e);
147+ + "The serialized form was corrupted, or not initially generated from a PagingState object.", e);
149148 }
150149 }
151150
@@ -163,7 +162,6 @@
163162 *
164163 * @param pagingState The byte array representation.
165164 * @return the PagingState object created.
166- *
167165 * @throws PagingStateException if the byte array does not have the correct format.
168166 */
169167 public static PagingState fromBytes(byte[] pagingState) {
modified driver-core/src/main/java/com/datastax/driver/core/ParseUtils.java +9 −10
@@ -20,13 +20,14 @@
2020 */
2121 abstract class ParseUtils {
2222
23- private ParseUtils() {}
23+ private ParseUtils() {
24+ }
2425
2526 /**
2627 * Returns the index of the first character in toParse from idx that is not a "space".
2728 *
2829 * @param toParse the string to skip space on.
29- * @param idx the index to start skipping space from.
30+ * @param idx the index to start skipping space from.
3031 * @return the index of the first character in toParse from idx that is not a "space.
3132 */
3233 public static int skipSpaces(String toParse, int idx) {
@@ -40,11 +41,10 @@
4041 * index of the first character after this value.
4142 *
4243 * @param toParse the string to skip a value form.
43- * @param idx the index to start parsing a value from.
44+ * @param idx the index to start parsing a value from.
4445 * @return the index ending the CQL value starting at {@code idx}.
45- *
4646 * @throws IllegalArgumentException if idx doesn't point to the start of a valid CQL
47- * value.
47+ * value.
4848 */
4949 public static int skipCQLValue(String toParse, int idx) {
5050 if (idx >= toParse.length())
@@ -116,11 +116,10 @@
116116 * index of the first character after this identifier.
117117 *
118118 * @param toParse the string to skip an identifier from.
119- * @param idx the index to start parsing an identifier from.
119+ * @param idx the index to start parsing an identifier from.
120120 * @return the index ending the CQL identifier starting at {@code idx}.
121- *
122121 * @throws IllegalArgumentException if idx doesn't point to the start of a valid CQL
123- * identifier.
122+ * identifier.
124123 */
125124 public static int skipCQLId(String toParse, int idx) {
126125 if (idx >= toParse.length())
@@ -152,8 +151,8 @@
152151 // [0..9a..zA..Z-+._&]
153152 public static boolean isIdentifierChar(int c) {
154153 return (c >= '0' && c <= '9')
155- || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
156- || c == '-' || c == '+' || c == '.' || c == '_' || c == '&';
154+ || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
155+ || c == '-' || c == '+' || c == '.' || c == '_' || c == '&';
157156 }
158157
159158 // [ \t\n]
modified driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java +31 −33
@@ -15,16 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Set;
19-import java.util.concurrent.ConcurrentMap;
20-import java.util.concurrent.ExecutionException;
21-import java.util.concurrent.TimeUnit;
22-import java.util.concurrent.TimeoutException;
23-
24-import static java.util.concurrent.TimeUnit.MILLISECONDS;
25-import static java.util.concurrent.TimeUnit.MINUTES;
26-import static java.util.concurrent.TimeUnit.NANOSECONDS;
27-
18+import com.datastax.driver.core.exceptions.*;
2819 import com.google.common.annotations.Beta;
2920 import com.google.common.collect.ImmutableSet;
3021 import com.google.common.collect.MapMaker;
@@ -36,14 +27,19 @@
3627 import org.slf4j.Logger;
3728 import org.slf4j.LoggerFactory;
3829
39-import static com.google.common.base.Preconditions.checkArgument;
30+import java.util.Set;
31+import java.util.concurrent.ConcurrentMap;
32+import java.util.concurrent.ExecutionException;
33+import java.util.concurrent.TimeUnit;
34+import java.util.concurrent.TimeoutException;
4035
41-import com.datastax.driver.core.exceptions.*;
36+import static com.google.common.base.Preconditions.checkArgument;
37+import static java.util.concurrent.TimeUnit.*;
4238
4339 /**
4440 * A {@link LatencyTracker} that records latencies for each host over a sliding time interval, and exposes an
4541 * API to retrieve the latency at a given percentile.
46- * <p>
42+ * <p/>
4743 * To use this class, build an instance with {@link #builderWithHighestTrackableLatencyMillis(long)} and register
4844 * it with your {@link com.datastax.driver.core.Cluster} instance:
4945 * <pre>
@@ -55,13 +51,13 @@
5551 * ...
5652 * tracker.getLatencyAtPercentile(host1, 99.0);
5753 * </pre>
58- * <p>
54+ * <p/>
5955 * This class uses <a href="http://hdrhistogram.github.io/HdrHistogram/">HdrHistogram</a> to record latencies:
6056 * for each host, there is a "live" histogram where current latencies are recorded, and a "cached", read-only histogram
6157 * that is used when clients call {@link #getLatencyAtPercentile(Host, double)}. Each time the cached histogram becomes
6258 * older than the interval, the two histograms are switched. Note that statistics will not be available during the first
6359 * interval at cluster startup, since we don't have a cached histogram yet.
64- * <p>
60+ * <p/>
6561 * Note that this class is currently marked "beta": it hasn't been extensively tested yet, and the API is still subject
6662 * to change.
6763 */
@@ -117,9 +113,9 @@
117113 /**
118114 * Sets the number of significant decimal digits to which histograms will maintain value
119115 * resolution and separation. This must be an integer between 0 and 5.
120- * <p>
116+ * <p/>
121117 * If not set explicitly, this value defaults to 3.
122- * <p>
118+ * <p/>
123119 * See <a href="http://hdrhistogram.github.io/HdrHistogram/JavaDoc/org/HdrHistogram/Histogram.html">the HdrHistogram Javadocs</a>
124120 * for a more detailed explanation on how this parameter affects the resolution of recorded samples.
125121 *
@@ -134,11 +130,11 @@
134130 /**
135131 * Sets the minimum number of values that must be recorded for a host before we consider
136132 * the sample size significant.
137- * <p>
133+ * <p/>
138134 * If this count is not reached during a given interval, {@link #getLatencyAtPercentile(Host, double)}
139135 * will return a negative value, indicating that statistics are not available. In particular, this is true
140136 * during the first interval.
141- * <p>
137+ * <p/>
142138 * If not set explicitly, this value default to 1000.
143139 *
144140 * @param minRecordedValues the new value.
@@ -151,9 +147,9 @@
151147
152148 /**
153149 * Sets the number of distinct hosts that the driver will ever connect to.
154- * <p>
150+ * <p/>
155151 * This parameter is only used to pre-size internal maps in order to avoid unnecessary rehashing.
156- * <p>
152+ * <p/>
157153 * If not set explicitly, this value defaults to 16.
158154 *
159155 * @param numberOfHosts the new value.
@@ -166,16 +162,16 @@
166162
167163 /**
168164 * Sets the time interval over which samples are recorded.
169- * <p>
165+ * <p/>
170166 * For each host, there is a "live" histogram where current latencies are recorded, and a "cached", read-only histogram
171167 * that is used when clients call {@link #getLatencyAtPercentile(Host, double)}. Each time the cached histogram becomes
172168 * older than the interval, the two histograms are switched. Note that statistics will not be available during the first
173169 * interval at cluster startup, since we don't have a cached histogram yet.
174- * <p>
170+ * <p/>
175171 * If not set explicitly, this value defaults to 5 minutes.
176172 *
177173 * @param interval the new interval.
178- * @param unit the unit that the interval is expressed in.
174+ * @param unit the unit that the interval is expressed in.
179175 * @return this builder.
180176 */
181177 public Builder withInterval(long interval, TimeUnit unit) {
@@ -203,20 +199,20 @@
203199 getRecorder(host).recordValue(latencyMs);
204200 } catch (ArrayIndexOutOfBoundsException e) {
205201 logger.warn("Got request with latency of {} ms, which exceeds the configured maximum trackable value {}",
206- latencyMs, highestTrackableLatencyMillis);
202+ latencyMs, highestTrackableLatencyMillis);
207203 }
208204 }
209205
210206 /**
211207 * Returns the request latency for a host at a given percentile.
212208 *
213- * @param host the host.
209+ * @param host the host.
214210 * @param percentile the percentile (for example, {@code 99.0} for the 99th percentile).
215211 * @return the latency (in milliseconds) at the given percentile, or a negative value if it's not available yet.
216212 */
217213 public long getLatencyAtPercentile(Host host, double percentile) {
218214 checkArgument(percentile >= 0.0 && percentile < 100,
219- "percentile must be between 0.0 and 100 (was %f)");
215+ "percentile must be between 0.0 and 100 (was %f)");
220216 Histogram histogram = getLastIntervalHistogram(host);
221217 if (histogram == null || histogram.getTotalCount() < minRecordedValues)
222218 return -1;
@@ -240,7 +236,9 @@
240236 return recorder;
241237 }
242238
243- /** @return null if no histogram is available yet (no entries recorded, or not for long enough) */
239+ /**
240+ * @return null if no histogram is available yet (no entries recorded, or not for long enough)
241+ */
244242 private Histogram getLastIntervalHistogram(Host host) {
245243 try {
246244 while (true) {
@@ -308,10 +306,10 @@
308306 * and tend to make the host's score look better than it actually is.
309307 */
310308 private static final Set<Class<? extends Exception>> EXCLUDED_EXCEPTIONS = ImmutableSet.<Class<? extends Exception>>of(
311- UnavailableException.class, // this is done via the snitch and is usually very fast
312- OverloadedException.class,
313- BootstrappingException.class,
314- UnpreparedException.class,
315- QueryValidationException.class // query validation also happens at early stages in the coordinator
309+ UnavailableException.class, // this is done via the snitch and is usually very fast
310+ OverloadedException.class,
311+ BootstrappingException.class,
312+ UnpreparedException.class,
313+ QueryValidationException.class // query validation also happens at early stages in the coordinator
316314 );
317315 }
modified driver-core/src/main/java/com/datastax/driver/core/PlainTextAuthProvider.java +8 −7
@@ -15,15 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.util.Map;
20-
2118 import com.google.common.base.Charsets;
2219 import com.google.common.collect.ImmutableMap;
2320
21+import java.net.InetSocketAddress;
22+import java.util.Map;
23+
2424 /**
2525 * A simple {@code AuthProvider} implementation.
26- * <p>
26+ * <p/>
2727 * This provider allows to programmatically define authentication
2828 * information that will then apply to all hosts. The
2929 * PlainTextAuthenticator instances it returns support SASL
@@ -38,6 +38,7 @@
3838 /**
3939 * Creates a new simple authentication information provider with the
4040 * supplied credentials.
41+ *
4142 * @param username to use for authentication requests
4243 * @param password to use for authentication requests
4344 */
@@ -48,7 +49,7 @@
4849
4950 /**
5051 * Changes the user name.
51- *
52+ * <p/>
5253 * The new credentials will be used for all connections initiated after this method was called.
5354 *
5455 * @param username the new name.
@@ -59,7 +60,7 @@
5960
6061 /**
6162 * Changes the password.
62- *
63+ * <p/>
6364 * The new credentials will be used for all connections initiated after this method was called.
6465 *
6566 * @param password the new password.
@@ -117,7 +118,7 @@
117118
118119 Map<String, String> getCredentials() {
119120 return ImmutableMap.of("username", new String(username, Charsets.UTF_8),
120- "password", new String(password, Charsets.UTF_8));
121+ "password", new String(password, Charsets.UTF_8));
121122 }
122123 }
123124 }
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +83 −96
@@ -15,35 +15,35 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Map;
19-import java.util.concurrent.Executor;
20-
2118 import com.google.common.base.Preconditions;
2219 import com.google.common.collect.ImmutableMap;
2320 import com.google.common.util.concurrent.MoreExecutors;
2421
22+import java.util.Map;
23+import java.util.concurrent.Executor;
24+
2525 import static com.datastax.driver.core.HostDistance.LOCAL;
2626 import static com.datastax.driver.core.HostDistance.REMOTE;
2727
2828 /**
2929 * Options related to connection pooling.
30- * <p>
30+ * <p/>
3131 * The driver uses connections in an asynchronous manner, meaning that
3232 * multiple requests can be submitted on the same connection at the same
3333 * time. Therefore only a relatively small number of connections is needed.
3434 * For each host, the driver uses a connection pool that may have a variable
3535 * size (it will automatically adjust to the current load).
36- * <p>
36+ * <p/>
3737 * With {@code ProtocolVersion#V2} or below, there are at most 128 simultaneous
3838 * requests per connection, so the pool defaults to a variable size. You will
3939 * typically raise the maximum capacity by adding more connections with
4040 * {@link #setMaxConnectionsPerHost(HostDistance, int)}.
41- * <p>
41+ * <p/>
4242 * With {@code ProtocolVersion#V3} or above, there are up to 32768 requests per
4343 * connection, and the pool defaults to a fixed size of 1. You will typically
4444 * raise the maximum capacity by allowing more simultaneous requests per connection
4545 * ({@link #setMaxRequestsPerConnection(HostDistance, int)}).
46- * <p>
46+ * <p/>
4747 * All parameters can be separately set for {@code LOCAL} and
4848 * {@code REMOTE} hosts ({@link HostDistance}). For {@code IGNORED} hosts,
4949 * no connections are created so these settings cannot be changed.
@@ -53,27 +53,27 @@
5353 static final int UNSET = Integer.MIN_VALUE;
5454
5555 private static final Map<ProtocolVersion, Map<String, Integer>> DEFAULTS = ImmutableMap.<ProtocolVersion, Map<String, Integer>>of(
56- ProtocolVersion.V2, ImmutableMap.<String, Integer>builder()
57- .put("corePoolLocal", 2)
58- .put("maxPoolLocal", 8)
59- .put("corePoolRemote", 1)
60- .put("maxPoolRemote", 2)
61- .put("newConnectionThresholdLocal", 100)
62- .put("newConnectionThresholdRemote", 100)
63- .put("maxRequestsPerConnectionLocal", 128)
64- .put("maxRequestsPerConnectionRemote", 128)
65- .build(),
66-
67- ProtocolVersion.V3, ImmutableMap.<String, Integer>builder()
68- .put("corePoolLocal", 1)
69- .put("maxPoolLocal", 1)
70- .put("corePoolRemote", 1)
71- .put("maxPoolRemote", 1)
72- .put("newConnectionThresholdLocal", 800)
73- .put("newConnectionThresholdRemote", 200)
74- .put("maxRequestsPerConnectionLocal", 1024)
75- .put("maxRequestsPerConnectionRemote", 256)
76- .build()
56+ ProtocolVersion.V2, ImmutableMap.<String, Integer>builder()
57+ .put("corePoolLocal", 2)
58+ .put("maxPoolLocal", 8)
59+ .put("corePoolRemote", 1)
60+ .put("maxPoolRemote", 2)
61+ .put("newConnectionThresholdLocal", 100)
62+ .put("newConnectionThresholdRemote", 100)
63+ .put("maxRequestsPerConnectionLocal", 128)
64+ .put("maxRequestsPerConnectionRemote", 128)
65+ .build(),
66+
67+ ProtocolVersion.V3, ImmutableMap.<String, Integer>builder()
68+ .put("corePoolLocal", 1)
69+ .put("maxPoolLocal", 1)
70+ .put("corePoolRemote", 1)
71+ .put("maxPoolRemote", 1)
72+ .put("newConnectionThresholdLocal", 800)
73+ .put("newConnectionThresholdRemote", 200)
74+ .put("maxRequestsPerConnectionLocal", 1024)
75+ .put("maxRequestsPerConnectionRemote", 256)
76+ .build()
7777 );
7878
7979 private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
@@ -87,9 +87,9 @@
8787
8888 // The defaults for these fields depend on the protocol version, which is only known after control connection initialization.
8989 // Yet if the user set them before initialization, we want to keep their values. So we use -1 to mean "uninitialized".
90- private final int[] coreConnections = new int[]{ UNSET, UNSET, 0 };
91- private final int[] maxConnections = new int[]{ UNSET, UNSET, 0 };
92- private final int[] newConnectionThreshold = new int[]{ UNSET, UNSET, 0 };
90+ private final int[] coreConnections = new int[]{UNSET, UNSET, 0};
91+ private final int[] maxConnections = new int[]{UNSET, UNSET, 0};
92+ private final int[] newConnectionThreshold = new int[]{UNSET, UNSET, 0};
9393 private volatile int maxRequestsPerConnectionLocal = UNSET;
9494 private volatile int maxRequestsPerConnectionRemote = UNSET;
9595
@@ -118,24 +118,22 @@
118118
119119 /**
120120 * Sets the core number of connections per host.
121- * <p>
121+ * <p/>
122122 * For the provided {@code distance}, this corresponds to the number of
123123 * connections initially created and kept open to each host of that
124124 * distance.
125- * <p>
125+ * <p/>
126126 * The default value is:
127127 * <ul>
128- * <li>with {@code ProtocolVersion#V2} or below: 2 for {@code LOCAL} hosts and 1 for {@code REMOTE} hosts.</li>
129- * <li>with {@code ProtocolVersion#V3} or above: 1 for all hosts.</li>
128+ * <li>with {@code ProtocolVersion#V2} or below: 2 for {@code LOCAL} hosts and 1 for {@code REMOTE} hosts.</li>
129+ * <li>with {@code ProtocolVersion#V3} or above: 1 for all hosts.</li>
130130 * </ul>
131131 *
132- * @param distance the {@code HostDistance} for which to set this threshold.
132+ * @param distance the {@code HostDistance} for which to set this threshold.
133133 * @param newCoreConnections the value to set
134134 * @return this {@code PoolingOptions}.
135- *
136135 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
137- * or if {@code newCoreConnections} is greater than the maximum value for this distance.
138- *
136+ * or if {@code newCoreConnections} is greater than the maximum value for this distance.
139137 * @see #setConnectionsPerHost(HostDistance, int, int)
140138 */
141139 public synchronized PoolingOptions setCoreConnectionsPerHost(HostDistance distance, int newCoreConnections) {
@@ -164,23 +162,21 @@
164162
165163 /**
166164 * Sets the maximum number of connections per host.
167- * <p>
165+ * <p/>
168166 * For the provided {@code distance}, this corresponds to the maximum
169167 * number of connections that can be created per host at that distance.
170- * <p>
168+ * <p/>
171169 * The default value is:
172170 * <ul>
173- * <li>with {@code ProtocolVersion#V2} or below: 8 for {@code LOCAL} hosts and 2 for {@code REMOTE} hosts.</li>
174- * <li>with {@code ProtocolVersion#V3} or above: 1 for all hosts.</li>
171+ * <li>with {@code ProtocolVersion#V2} or below: 8 for {@code LOCAL} hosts and 2 for {@code REMOTE} hosts.</li>
172+ * <li>with {@code ProtocolVersion#V3} or above: 1 for all hosts.</li>
175173 * </ul>
176174 *
177- * @param distance the {@code HostDistance} for which to set this threshold.
175+ * @param distance the {@code HostDistance} for which to set this threshold.
178176 * @param newMaxConnections the value to set
179177 * @return this {@code PoolingOptions}.
180- *
181178 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
182- * or if {@code newMaxConnections} is less than the core value for this distance.
183- *
179+ * or if {@code newMaxConnections} is less than the core value for this distance.
184180 * @see #setConnectionsPerHost(HostDistance, int, int)
185181 */
186182 public synchronized PoolingOptions setMaxConnectionsPerHost(HostDistance distance, int newMaxConnections) {
@@ -196,17 +192,16 @@
196192
197193 /**
198194 * Sets the core and maximum number of connections per host in one call.
199- * <p>
195+ * <p/>
200196 * This is a convenience method that is equivalent to calling {@link #setCoreConnectionsPerHost(HostDistance, int)}
201197 * and {@link #setMaxConnectionsPerHost(HostDistance, int)}.
202198 *
203199 * @param distance the {@code HostDistance} for which to set these threshold.
204- * @param core the core number of connections.
205- * @param max the max number of connections.
200+ * @param core the core number of connections.
201+ * @param max the max number of connections.
206202 * @return this {@code PoolingOptions}.
207- *
208203 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
209- * or if {@code core} > {@code max}.
204+ * or if {@code core} > {@code max}.
210205 */
211206 public synchronized PoolingOptions setConnectionsPerHost(HostDistance distance, int core, int max) {
212207 if (distance == HostDistance.IGNORED)
@@ -223,7 +218,6 @@
223218 *
224219 * @param distance the {@code HostDistance} for which to return this threshold.
225220 * @return the configured threshold, or the default one if none have been set.
226- *
227221 * @see #setNewConnectionThreshold(HostDistance, int)
228222 */
229223 public int getNewConnectionThreshold(HostDistance distance) {
@@ -232,29 +226,28 @@
232226
233227 /**
234228 * Sets the threshold that triggers the creation of a new connection to a host.
235- * <p>
229+ * <p/>
236230 * A new connection gets created if:
237231 * <ul>
238- * <li>N connections are open</li>
239- * <li><tt>N < {@link #getMaxConnectionsPerHost(HostDistance)}</tt></li>
240- * <li>the number of active requests is more than
241- * <tt>(N - 1) * {@link #getMaxRequestsPerConnection(HostDistance)} + {@link #getNewConnectionThreshold(HostDistance)}</tt>
242- * </li>
232+ * <li>N connections are open</li>
233+ * <li><tt>N < {@link #getMaxConnectionsPerHost(HostDistance)}</tt></li>
234+ * <li>the number of active requests is more than
235+ * <tt>(N - 1) * {@link #getMaxRequestsPerConnection(HostDistance)} + {@link #getNewConnectionThreshold(HostDistance)}</tt>
236+ * </li>
243237 * </ul>
244238 * In other words, if all but the last connection are full, and the last connection is above this threshold.
245- * <p>
239+ * <p/>
246240 * The default value is:
247241 * <ul>
248- * <li>with {@code ProtocolVersion#V2} or below: 100 for all hosts.</li>
249- * <li>with {@code ProtocolVersion#V3} or above: 800 for {@code LOCAL} hosts and 200 for {@code REMOTE} hosts.</li>
242+ * <li>with {@code ProtocolVersion#V2} or below: 100 for all hosts.</li>
243+ * <li>with {@code ProtocolVersion#V3} or above: 800 for {@code LOCAL} hosts and 200 for {@code REMOTE} hosts.</li>
250244 * </ul>
251245 *
252246 * @param distance the {@code HostDistance} for which to configure this threshold.
253247 * @param newValue the value to set (between 0 and 128).
254248 * @return this {@code PoolingOptions}.
255- *
256249 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code maxSimultaneousRequests}
257- * is not in range, or if {@code newValue} is less than the minimum value for this distance.
250+ * is not in range, or if {@code newValue} is less than the minimum value for this distance.
258251 */
259252 public synchronized PoolingOptions setNewConnectionThreshold(HostDistance distance, int newValue) {
260253 if (distance == HostDistance.IGNORED)
@@ -270,7 +263,6 @@
270263 *
271264 * @param distance the {@code HostDistance} for which to return this threshold.
272265 * @return the maximum number of requests per connection at distance {@code distance}.
273- *
274266 * @see #setMaxRequestsPerConnection(HostDistance, int)
275267 */
276268 public int getMaxRequestsPerConnection(HostDistance distance) {
@@ -286,24 +278,23 @@
286278
287279 /**
288280 * Sets the maximum number of requests per connection.
289- * <p>
281+ * <p/>
290282 * The default value is:
291283 * <ul>
292- * <li>with {@code ProtocolVersion#V2} or below: 128 for all hosts (there should not be any reason to change this).</li>
293- * <li>with {@code ProtocolVersion#V3} or above: 1024 for {@code LOCAL} hosts and 256 for {@code REMOTE} hosts.
294- * These values were chosen so that the default V2 and V3 configuration generate the same load on a Cassandra cluster.
295- * Protocol V3 can go much higher (up to 32768), so if your number of clients is low, don't hesitate to experiment with
296- * higher values. If you have more than one connection per host, consider also adjusting
297- * {@link #setNewConnectionThreshold(HostDistance, int)}.
298- * </li>
284+ * <li>with {@code ProtocolVersion#V2} or below: 128 for all hosts (there should not be any reason to change this).</li>
285+ * <li>with {@code ProtocolVersion#V3} or above: 1024 for {@code LOCAL} hosts and 256 for {@code REMOTE} hosts.
286+ * These values were chosen so that the default V2 and V3 configuration generate the same load on a Cassandra cluster.
287+ * Protocol V3 can go much higher (up to 32768), so if your number of clients is low, don't hesitate to experiment with
288+ * higher values. If you have more than one connection per host, consider also adjusting
289+ * {@link #setNewConnectionThreshold(HostDistance, int)}.
290+ * </li>
299291 * </ul>
300292 *
301- * @param distance the {@code HostDistance} for which to set this threshold.
293+ * @param distance the {@code HostDistance} for which to set this threshold.
302294 * @param newMaxRequests the value to set.
303295 * @return this {@code PoolingOptions}.
304- *
305296 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
306- * or if {@code newMaxConnections} is not within the allowed range.
297+ * or if {@code newMaxConnections} is not within the allowed range.
307298 */
308299 public PoolingOptions setMaxRequestsPerConnection(HostDistance distance, int newMaxRequests) {
309300 checkRequestsPerConnectionRange(newMaxRequests, "Max requests per connection", distance);
@@ -332,13 +323,12 @@
332323
333324 /**
334325 * Sets the timeout before an idle connection is removed.
335- * <p>
326+ * <p/>
336327 * The order of magnitude should be a few minutes (the default is 120 seconds). The
337328 * timeout that triggers the removal has a granularity of 10 seconds.
338329 *
339330 * @param idleTimeoutSeconds the new timeout in seconds.
340331 * @return this {@code PoolingOptions}.
341- *
342332 * @throws IllegalArgumentException if the timeout is negative.
343333 */
344334 public PoolingOptions setIdleTimeoutSeconds(int idleTimeoutSeconds) {
@@ -359,15 +349,14 @@
359349
360350 /**
361351 * Sets the timeout when trying to acquire a connection from a host's pool.
362- * <p>
352+ * <p/>
363353 * If no connection is available within that time, the driver will try the
364354 * next host from the query plan.
365- * <p>
355+ * <p/>
366356 * The default is 5 seconds. If this option is set to zero, the driver won't wait at all.
367357 *
368358 * @param poolTimeoutMillis the new value in milliseconds.
369359 * @return this {@code PoolingOptions}
370- *
371360 * @throws IllegalArgumentException if the timeout is negative.
372361 */
373362 public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) {
@@ -379,6 +368,7 @@
379368
380369 /**
381370 * Returns the heart beat interval, after which a message is sent on an idle connection to make sure it's still alive.
371+ *
382372 * @return the interval.
383373 */
384374 public int getHeartbeatIntervalSeconds() {
@@ -387,17 +377,16 @@
387377
388378 /**
389379 * Sets the heart beat interval, after which a message is sent on an idle connection to make sure it's still alive.
390- * <p>
380+ * <p/>
391381 * This is an application-level keep-alive, provided for convenience since adjusting the TCP keep-alive might not be
392382 * practical in all environments.
393- * <p>
383+ * <p/>
394384 * This option should be set higher than {@link SocketOptions#getReadTimeoutMillis()}.
395- * <p>
385+ * <p/>
396386 * The default value for this option is 30 seconds.
397387 *
398388 * @param heartbeatIntervalSeconds the new value in seconds. If set to 0, it will disable the feature.
399389 * @return this {@code PoolingOptions}
400- *
401390 * @throws IllegalArgumentException if the interval is negative.
402391 */
403392 public PoolingOptions setHeartbeatIntervalSeconds(int heartbeatIntervalSeconds) {
@@ -420,11 +409,11 @@
420409
421410 /**
422411 * Sets the executor to use for connection initialization.
423- * <p>
412+ * <p/>
424413 * Connections are open in a completely asynchronous manner. Since initializing the transport
425414 * requires separate CQL queries, the futures representing the completion of these queries are
426415 * transformed and chained. This executor is where these transformations happen.
427- * <p>
416+ * <p/>
428417 * <b>This is an advanced option, which should be rarely needed in practice.</b> It defaults to
429418 * Guava's {@code MoreExecutors.sameThreadExecutor()}, which results in running the transformations
430419 * on the network I/O threads; this is fine if the transformations are fast and not I/O bound
@@ -435,7 +424,6 @@
435424 *
436425 * @param initializationExecutor the executor to use
437426 * @return this {@code PoolingOptions}
438- *
439427 * @throws java.lang.NullPointerException if the executor is null
440428 */
441429 public PoolingOptions setInitializationExecutor(Executor initializationExecutor) {
@@ -448,8 +436,8 @@
448436 this.protocolVersion = protocolVersion;
449437
450438 ProtocolVersion referenceVersion = (protocolVersion.compareTo(ProtocolVersion.V2) <= 0)
451- ? ProtocolVersion.V2
452- : ProtocolVersion.V3;
439+ ? ProtocolVersion.V2
440+ : ProtocolVersion.V3;
453441 Map<String, Integer> defaults = DEFAULTS.get(referenceVersion);
454442
455443 if (coreConnections[LOCAL.ordinal()] == UNSET)
@@ -485,7 +473,7 @@
485473 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
486474 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
487475 * hosts and to drop/add connections to each hosts according to the computed distance.
488- * <p>
476+ * <p/>
489477 * Note that, due to backward compatibility issues, this method is not interruptible. If the
490478 * caller thread gets interrupted, the method will complete and only then re-interrupt the
491479 * thread (which you can check with {@code Thread.currentThread().isInterrupted()}).
@@ -498,7 +486,6 @@
498486 * Requests the driver to re-evaluate the {@link HostDistance} for a given node.
499487 *
500488 * @param host the host to refresh.
501- *
502489 * @see #refreshConnectedHosts()
503490 */
504491 public void refreshConnectedHost(Host host) {
@@ -508,18 +495,18 @@
508495 private void checkRequestsPerConnectionRange(int value, String description, HostDistance distance) {
509496 // If we don't know the protocol version yet, use the highest possible upper bound, this will get checked again when possible
510497 int max = (protocolVersion == null || protocolVersion.compareTo(ProtocolVersion.V3) >= 0)
511- ? StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3
512- : StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2;
498+ ? StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3
499+ : StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2;
513500
514501 if (value < 0 || value > max)
515502 throw new IllegalArgumentException(String.format("%s for %s hosts must be in the range (0, %d)",
516- description, distance, max));
503+ description, distance, max));
517504 }
518505
519506 private static void checkConnectionsPerHostOrder(int core, int max, HostDistance distance) {
520507 if (core > max)
521508 throw new IllegalArgumentException(String.format("Core connections for %s hosts must be less than max (%d > %d)",
522- distance, core, max));
509+ distance, core, max));
523510 }
524511
525512 /**
modified driver-core/src/main/java/com/datastax/driver/core/PreparedId.java +2 −4
@@ -18,8 +18,7 @@
1818 /**
1919 * Identifies a PreparedStatement.
2020 */
21-public class PreparedId
22-{
21+public class PreparedId {
2322 // This class is mostly here to group PreparedStatement data that are need for
2423 // execution but that we don't want to expose publicly (see JAVA-195)
2524 final MD5Digest id;
@@ -30,8 +29,7 @@
3029 final int[] routingKeyIndexes;
3130 final ProtocolVersion protocolVersion;
3231
33- PreparedId(MD5Digest id, ColumnDefinitions metadata, ColumnDefinitions resultSetMetadata, int[] routingKeyIndexes, ProtocolVersion protocolVersion)
34- {
32+ PreparedId(MD5Digest id, ColumnDefinitions metadata, ColumnDefinitions resultSetMetadata, int[] routingKeyIndexes, ProtocolVersion protocolVersion) {
3533 this.id = id;
3634 this.metadata = metadata;
3735 this.resultSetMetadata = resultSetMetadata;
modified driver-core/src/main/java/com/datastax/driver/core/PreparedStatement.java +26 −31
@@ -15,20 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-
2018 import com.datastax.driver.core.exceptions.InvalidTypeException;
2119 import com.datastax.driver.core.policies.RetryPolicy;
2220
21+import java.nio.ByteBuffer;
22+
2323 /**
2424 * Represents a prepared statement, a query with bound variables that has been
2525 * prepared (pre-parsed) by the database.
26- * <p>
26+ * <p/>
2727 * A prepared statement can be executed once concrete values have been provided
2828 * for the bound variables. A prepared statement and the values for its
2929 * bound variables constitute a BoundStatement and can be executed (by
3030 * {@link Session#execute}).
31- * <p>
31+ * <p/>
3232 * A {@code PreparedStatement} object allows you to define specific defaults
3333 * for the different properties of a {@link Statement} (Consistency level, tracing, ...),
3434 * in which case those properties will be inherited as default by every
@@ -50,35 +50,33 @@
5050 /**
5151 * Creates a new BoundStatement object and bind its variables to the
5252 * provided values.
53- * <p>
53+ * <p/>
5454 * While the number of {@code values} cannot be greater than the number of bound
5555 * variables, the number of {@code values} may be fewer than the number of bound
5656 * variables. In that case, the remaining variables will have to be bound
5757 * to values by another mean because the resulting {@code BoundStatement}
5858 * being executable.
59- * <p>
59+ * <p/>
6060 * This method is a convenience for {@code new BoundStatement(this).bind(...)}.
6161 *
6262 * @param values the values to bind to the variables of the newly created
63- * BoundStatement.
63+ * BoundStatement.
6464 * @return the newly created {@code BoundStatement} with its variables
6565 * bound to {@code values}.
66- *
6766 * @throws IllegalArgumentException if more {@code values} are provided
68- * than there is of bound variables in this statement.
69- * @throws InvalidTypeException if any of the provided value is not of
70- * correct type to be bound to the corresponding bind variable.
71- * @throws NullPointerException if one of {@code values} is a collection
72- * (List, Set or Map) containing a null value. Nulls are not supported in
73- * collections by CQL.
74- *
67+ * than there is of bound variables in this statement.
68+ * @throws InvalidTypeException if any of the provided value is not of
69+ * correct type to be bound to the corresponding bind variable.
70+ * @throws NullPointerException if one of {@code values} is a collection
71+ * (List, Set or Map) containing a null value. Nulls are not supported in
72+ * collections by CQL.
7573 * @see BoundStatement#bind
7674 */
7775 public BoundStatement bind(Object... values);
7876
7977 /**
8078 * Creates a new BoundStatement object for this prepared statement.
81- * <p>
79+ * <p/>
8280 * This method do not bind any values to any of the prepared variables. Said
8381 * values need to be bound on the resulting statement using BoundStatement's
8482 * setters methods ({@link BoundStatement#setInt}, {@link BoundStatement#setLong}, ...).
@@ -89,23 +87,22 @@
8987
9088 /**
9189 * Sets the routing key for this prepared statement.
92- * <p>
90+ * <p/>
9391 * While you can provide a fixed routing key for all executions of this prepared
9492 * statement with this method, it is not mandatory to provide
9593 * one through this method. This method should only be used
9694 * if the partition key of the prepared query is not part of the prepared
9795 * variables (that is if the partition key is fixed).
98- * <p>
96+ * <p/>
9997 * Note that if the partition key is part of the prepared variables, the
10098 * routing key will be automatically computed once those variables are bound.
101- * <p>
99+ * <p/>
102100 * If the partition key is neither fixed nor part of the prepared variables (e.g.
103101 * a composite partition key where only some of the components are bound), the
104102 * routing key can also be set on each bound statement.
105103 *
106104 * @param routingKey the raw (binary) value to use as routing key.
107105 * @return this {@code PreparedStatement} object.
108- *
109106 * @see Statement#getRoutingKey
110107 * @see BoundStatement#getRoutingKey
111108 */
@@ -113,15 +110,14 @@
113110
114111 /**
115112 * Sets the routing key for this query.
116- * <p>
113+ * <p/>
117114 * See {@link #setRoutingKey(ByteBuffer)} for more information. This
118115 * method is a variant for when the query partition key is composite and
119116 * the routing key must be built from multiple values.
120117 *
121118 * @param routingKeyComponents the raw (binary) values to compose to obtain
122- * the routing key.
119+ * the routing key.
123120 * @return this {@code PreparedStatement} object.
124- *
125121 * @see Statement#getRoutingKey
126122 */
127123 public PreparedStatement setRoutingKey(ByteBuffer... routingKeyComponents);
@@ -137,10 +133,10 @@
137133 /**
138134 * Sets a default consistency level for all bound statements
139135 * created from this prepared statement.
140- * <p>
136+ * <p/>
141137 * If no consistency level is set through this method, the bound statement
142138 * created from this object will use the default consistency level (ONE).
143- * <p>
139+ * <p/>
144140 * Changing the default consistency level is not retroactive, it only
145141 * applies to BoundStatement created after the change.
146142 *
@@ -161,18 +157,17 @@
161157 /**
162158 * Sets a default serial consistency level for all bound statements
163159 * created from this prepared statement.
164- * <p>
160+ * <p/>
165161 * If no serial consistency level is set through this method, the bound statement
166162 * created from this object will use the default serial consistency level (SERIAL).
167- * <p>
163+ * <p/>
168164 * Changing the default serial consistency level is not retroactive, it only
169165 * applies to BoundStatement created after the change.
170166 *
171167 * @param serialConsistency the default serial consistency level to set.
172168 * @return this {@code PreparedStatement} object.
173- *
174169 * @throws IllegalArgumentException if {@code serialConsistency} is not one of
175- * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
170+ * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
176171 */
177172 public PreparedStatement setSerialConsistencyLevel(ConsistencyLevel serialConsistency);
178173
@@ -188,7 +183,7 @@
188183 /**
189184 * Returns the string of the query that was prepared to yield this {@code
190185 * PreparedStatement}.
191- * <p>
186+ * <p/>
192187 * Note that a CQL3 query may be implicitly applied to the current keyspace
193188 * (that is, if the keyspace is not explicitly qualified in the query
194189 * itself). For prepared queries, the current keyspace used is the one at
@@ -241,7 +236,7 @@
241236 /**
242237 * Convenience method to set a default retry policy for the {@code BoundStatement}
243238 * created from this prepared statement.
244- * <p>
239+ * <p/>
245240 * Note that this method is completely optional. By default, the retry policy
246241 * used is the one returned {@link com.datastax.driver.core.policies.Policies#getRetryPolicy}
247242 * in the cluster configuration. This method is only useful if you want
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolEvent.java +6 −6
@@ -15,16 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-
2018 import io.netty.buffer.ByteBuf;
2119
20+import java.net.InetSocketAddress;
21+
2222 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
2323 import static com.datastax.driver.core.SchemaElement.TABLE;
2424
2525 class ProtocolEvent {
2626
27- public enum Type { TOPOLOGY_CHANGE, STATUS_CHANGE, SCHEMA_CHANGE }
27+ public enum Type {TOPOLOGY_CHANGE, STATUS_CHANGE, SCHEMA_CHANGE}
2828
2929 public final Type type;
3030
@@ -45,7 +45,7 @@
4545 }
4646
4747 public static class TopologyChange extends ProtocolEvent {
48- public enum Change { NEW_NODE, REMOVED_NODE, MOVED_NODE }
48+ public enum Change {NEW_NODE, REMOVED_NODE, MOVED_NODE}
4949
5050 public final Change change;
5151 public final InetSocketAddress node;
@@ -71,7 +71,7 @@
7171
7272 public static class StatusChange extends ProtocolEvent {
7373
74- public enum Status { UP, DOWN }
74+ public enum Status {UP, DOWN}
7575
7676 public final Status status;
7777 public final InetSocketAddress node;
@@ -97,7 +97,7 @@
9797
9898 public static class SchemaChange extends ProtocolEvent {
9999
100- public enum Change { CREATED, UPDATED, DROPPED }
100+ public enum Change {CREATED, UPDATED, DROPPED}
101101
102102 public final Change change;
103103 public final SchemaElement targetType;
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java +26 −20
@@ -26,21 +26,27 @@
2626 * Compression supported by the Cassandra binary protocol.
2727 */
2828 public enum Compression {
29- /** No compression */
29+ /**
30+ * No compression
31+ */
3032 NONE("") {
3133 @Override
3234 FrameCompressor compressor() {
3335 return null;
3436 }
3537 },
36- /** Snappy compression */
38+ /**
39+ * Snappy compression
40+ */
3741 SNAPPY("snappy") {
3842 @Override
3943 FrameCompressor compressor() {
4044 return FrameCompressor.SnappyCompressor.instance;
4145 }
4246 },
43- /** LZ4 compression */
47+ /**
48+ * LZ4 compression
49+ */
4450 LZ4("lz4") {
4551 @Override
4652 FrameCompressor compressor() {
@@ -68,7 +74,9 @@
6874 public String toString() {
6975 return protocolName;
7076 }
71- };
77+ }
78+
79+ ;
7280
7381 /**
7482 * The default port for Cassandra native binary protocol: 9042.
@@ -112,7 +120,7 @@
112120 /**
113121 * Creates a new {@code ProtocolOptions} instance using the provided port
114122 * (without SSL nor authentication).
115- * <p>
123+ * <p/>
116124 * This is a shortcut for {@code new ProtocolOptions(port, null, AuthProvider.NONE)}.
117125 *
118126 * @param port the port to use for the binary protocol.
@@ -125,14 +133,14 @@
125133 * Creates a new {@code ProtocolOptions} instance using the provided port
126134 * and SSL context.
127135 *
128- * @param port the port to use for the binary protocol.
136+ * @param port the port to use for the binary protocol.
129137 * @param protocolVersion the protocol version to use. This can be {@code null}, in which case the
130- * version used will be the biggest version supported by the <em>first</em> node the driver connects to.
131- * See {@link Cluster.Builder#withProtocolVersion} for more details.
132- * @param sslOptions the SSL options to use. Use {@code null} if SSL is not
133- * to be used.
134- * @param authProvider the {@code AuthProvider} to use for authentication against
135- * the Cassandra nodes.
138+ * version used will be the biggest version supported by the <em>first</em> node the driver connects to.
139+ * See {@link Cluster.Builder#withProtocolVersion} for more details.
140+ * @param sslOptions the SSL options to use. Use {@code null} if SSL is not
141+ * to be used.
142+ * @param authProvider the {@code AuthProvider} to use for authentication against
143+ * the Cassandra nodes.
136144 */
137145 public ProtocolOptions(int port, ProtocolVersion protocolVersion, int maxSchemaAgreementWaitSeconds, SSLOptions sslOptions, AuthProvider authProvider) {
138146 this.port = port;
@@ -144,7 +152,6 @@
144152
145153 /**
146154 * @throws IllegalArgumentException if {@code protocolVersion} does not correspond to any known version.
147- *
148155 * @deprecated This is provided for backward compatibility; use {@link #ProtocolOptions(int, ProtocolVersion, int, SSLOptions, AuthProvider))} instead.
149156 */
150157 @Deprecated
@@ -190,7 +197,7 @@
190197
191198 /**
192199 * Returns the compression used by the protocol.
193- * <p>
200+ * <p/>
194201 * By default, compression is not used.
195202 *
196203 * @return the compression used.
@@ -201,18 +208,17 @@
201208
202209 /**
203210 * Sets the compression to use.
204- * <p>
211+ * <p/>
205212 * Note that while this setting can be changed at any time, it will
206213 * only apply to newly created connections.
207214 *
208215 * @param compression the compression algorithm to use (or {@code
209- * Compression.NONE} to disable compression).
216+ * Compression.NONE} to disable compression).
210217 * @return this {@code ProtocolOptions} object.
211- *
212218 * @throws IllegalStateException if the compression requested is not
213- * available. Most compression algorithms require that the relevant be
214- * present in the classpath. If not, the compression will be
215- * unavailable.
219+ * available. Most compression algorithms require that the relevant be
220+ * present in the classpath. If not, the compression will be
221+ * unavailable.
216222 */
217223 public ProtocolOptions setCompression(Compression compression) {
218224 if (compression != Compression.NONE && compression.compressor() == null)
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolV1Authenticator.java +2 −2
@@ -19,10 +19,10 @@
1919
2020 /**
2121 * Parent class for {@link Authenticator} implementations that support native protocol v1 authentication.
22- *
22+ * <p/>
2323 * Protocol v1 uses simple, credentials-based authentication (as opposed to SASL for later protocol versions).
2424 * In order to support protocol v1, an authenticator must extend this class.
25- *
25+ * <p/>
2626 * We use an abstract class instead of an interface because we don't want to expose {@link #getCredentials()}.
2727 *
2828 * @see <a href="https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v1.spec">Native protocol v1 specification</a>
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolVersion.java +7 −8
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Map;
19-
20-import com.google.common.collect.ImmutableMap.Builder;
18+import com.datastax.driver.core.exceptions.DriverInternalError;
2119 import com.google.common.collect.ImmutableMap;
20+import com.google.common.collect.ImmutableMap.Builder;
2221
23-import com.datastax.driver.core.exceptions.DriverInternalError;
22+import java.util.Map;
2423
2524 /**
2625 * Versions of the native protocol supported by the driver.
@@ -29,8 +28,7 @@
2928
3029 V1("1.2.0", 1),
3130 V2("2.0.0", 2),
32- V3("2.1.0", 3),
33- ;
31+ V3("2.1.0", 3),;
3432
3533 /**
3634 * The most recent protocol version supported by the driver.
@@ -47,7 +45,7 @@
4745
4846 boolean isSupportedBy(Host host) {
4947 return host.getCassandraVersion() == null ||
50- isSupportedBy(host.getCassandraVersion());
48+ isSupportedBy(host.getCassandraVersion());
5149 }
5250
5351 VersionNumber minCassandraVersion() {
@@ -67,6 +65,7 @@
6765 * This is for use internally by Cassandra to ensure that the
6866 * correct version is specified when serializing and deserializing
6967 * using classes from the imported driver library.
68+ *
7069 * @return the protocol version as an int
7170 */
7271 public int toInt() {
@@ -74,6 +73,7 @@
7473 }
7574
7675 private static final Map<Integer, ProtocolVersion> INT_TO_VERSION;
76+
7777 static {
7878 Builder<Integer, ProtocolVersion> builder = ImmutableMap.builder();
7979 for (ProtocolVersion version : values()) {
@@ -87,7 +87,6 @@
8787 *
8888 * @param i the version as an integer.
8989 * @return the matching enum value.
90- *
9190 * @throws IllegalArgumentException if the argument doesn't match any known version.
9291 */
9392 public static ProtocolVersion fromInt(int i) {
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +65 −64
@@ -15,22 +15,22 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.List;
20-
21-import static java.util.concurrent.TimeUnit.NANOSECONDS;
22-
2318 import com.google.common.annotations.Beta;
2419 import com.google.common.annotations.VisibleForTesting;
2520 import org.slf4j.Logger;
2621 import org.slf4j.LoggerFactory;
2722
23+import java.nio.ByteBuffer;
24+import java.util.List;
25+
26+import static java.util.concurrent.TimeUnit.NANOSECONDS;
27+
2828 /**
2929 * A configurable {@link LatencyTracker} that logs all executed statements.
30- * <p>
30+ * <p/>
3131 * Typically, client applications would instantiate one single query logger (using its {@link Builder}),
3232 * configure it and register it on the relevant {@link Cluster} instance, e.g.:
33- *
33+ * <p/>
3434 * <pre>
3535 * Cluster cluster = ...
3636 * QueryLogger queryLogger = QueryLogger.builder(cluster)
@@ -39,55 +39,55 @@
3939 * .build();
4040 * cluster.register(queryLogger);
4141 * </pre>
42- *
42+ * <p/>
4343 * Refer to the {@link Builder} documentation for more information on
4444 * configuration settings for the query logger.
45- * <p>
45+ * <p/>
4646 * Once registered, the query logger will log every {@link RegularStatement}, {@link BoundStatement} or {@link BatchStatement}
4747 * executed by the driver;
4848 * note that it will never log other types of statement, null statements nor any special statement used internally by the driver.
49- * <p>
49+ * <p/>
5050 * There is one log for each request to a Cassandra node; because the driver sometimes retries the same statement on multiple nodes,
5151 * a single statement execution (for example, a single call to {@link Session#execute(Statement)}) can produce multiple logs on
5252 * different nodes.
53- * <p>
53+ * <p/>
5454 * For more flexibility, the query logger uses 3 different {@link Logger} instances:
55- *
55+ * <p/>
5656 * <ol>
57- * <li>{@link #NORMAL_LOGGER}: used to log normal queries, i.e., queries that completed successfully
58- * within a configurable threshold in milliseconds.</li>
59- * <li>{@link #SLOW_LOGGER}: used to log slow queries, i.e., queries that completed successfully
60- * but that took longer than a configurable threshold in milliseconds to complete.</li>
61- * <li>{@link #ERROR_LOGGER}: used to log unsuccessful queries, i.e.,
62- * queries that did not completed normally and threw an exception.
63- * Note this this logger will also print the full stack trace of the reported exception.</li>
57+ * <li>{@link #NORMAL_LOGGER}: used to log normal queries, i.e., queries that completed successfully
58+ * within a configurable threshold in milliseconds.</li>
59+ * <li>{@link #SLOW_LOGGER}: used to log slow queries, i.e., queries that completed successfully
60+ * but that took longer than a configurable threshold in milliseconds to complete.</li>
61+ * <li>{@link #ERROR_LOGGER}: used to log unsuccessful queries, i.e.,
62+ * queries that did not completed normally and threw an exception.
63+ * Note this this logger will also print the full stack trace of the reported exception.</li>
6464 * </ol>
65- *
66- * <p>
65+ * <p/>
66+ * <p/>
6767 * The appropriate logger is chosen according to the following algorithm:
6868 * <ol>
69- * <li>if an exception has been thrown: use {@link #ERROR_LOGGER};</li>
70- * <li>otherwise, if the reported latency is greater than the configured threshold in milliseconds: use {@link #SLOW_LOGGER};</li>
71- * <li>otherwise, use {@link #NORMAL_LOGGER}.</li>
69+ * <li>if an exception has been thrown: use {@link #ERROR_LOGGER};</li>
70+ * <li>otherwise, if the reported latency is greater than the configured threshold in milliseconds: use {@link #SLOW_LOGGER};</li>
71+ * <li>otherwise, use {@link #NORMAL_LOGGER}.</li>
7272 * </ol>
73- *
74- * <p>
73+ * <p/>
74+ * <p/>
7575 * All loggers are activated by setting their levels to {@code DEBUG} or {@code TRACE} (including {@link #ERROR_LOGGER}).
7676 * If the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
7777 * then the query parameters (if any) will be logged as well (names and actual values).
78- *
79- * <p>
78+ * <p/>
79+ * <p/>
8080 * <strong>Constant thresholds vs. Dynamic thresholds</strong>
81- * <p>
81+ * <p/>
8282 * Currently the QueryLogger can track slow queries in two different ways:
8383 * using a constant threshold in milliseconds (which is the default behavior),
8484 * or using a dynamic threshold based on per-host percentiles computed by
8585 * {@link PerHostPercentileTracker}.
86- * <p>
86+ * <p/>
8787 * <b>Note that the dynamic threshold version is currently provided as a beta preview: it hasn't been extensively
8888 * tested yet, and the API is still subject to change.</b> To use it, you must first obtain and register
8989 * an instance of {@link PerHostPercentileTracker}, then create your QueryLogger as follows:
90- *
90+ * <p/>
9191 * <pre>
9292 * Cluster cluster = ...
9393 * // create an instance of PerHostPercentileTracker and register it
@@ -100,8 +100,8 @@
100100 * .build();
101101 * cluster.register(queryLogger);
102102 * </pre>
103-
104- * <p>
103+ * <p/>
104+ * <p/>
105105 * This class is thread-safe.
106106 *
107107 * @since 2.0.10
@@ -146,11 +146,11 @@
146146 /**
147147 * The logger used to log normal queries, i.e., queries that completed successfully
148148 * within a configurable threshold in milliseconds.
149- * <p>
149+ * <p/>
150150 * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
151151 * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
152152 * then the query parameters (if any) will be logged as well (names and actual values).
153- * <p>
153+ * <p/>
154154 * The name of this logger is {@code com.datastax.driver.core.QueryLogger.NORMAL}.
155155 */
156156 public static final Logger NORMAL_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.NORMAL");
@@ -158,23 +158,23 @@
158158 /**
159159 * The logger used to log slow queries, i.e., queries that completed successfully
160160 * but whose execution time exceeded a configurable threshold in milliseconds.
161- * <p>
161+ * <p/>
162162 * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
163163 * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
164164 * then the query parameters (if any) will be logged as well (names and actual values).
165- * <p>
165+ * <p/>
166166 * The name of this logger is {@code com.datastax.driver.core.QueryLogger.SLOW}.
167167 */
168168 public static final Logger SLOW_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.SLOW");
169169
170170 /**
171171 * The logger used to log unsuccessful queries, i.e., queries that did not complete normally and threw an exception.
172- * <p>
172+ * <p/>
173173 * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
174174 * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
175175 * then the query parameters (if any) will be logged as well (names and actual values).
176176 * Note this this logger will also print the full stack trace of the reported exception.
177- * <p>
177+ * <p/>
178178 * The name of this logger is {@code com.datastax.driver.core.QueryLogger.ERROR}.
179179 */
180180 public static final Logger ERROR_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.ERROR");
@@ -217,7 +217,7 @@
217217
218218 /**
219219 * Creates a new {@link QueryLogger.Builder} instance.
220- * <p>
220+ * <p/>
221221 * This is a convenience method for {@code new QueryLogger.Builder()}.
222222 *
223223 * @param cluster the {@link Cluster} this QueryLogger will be attached to.
@@ -225,7 +225,7 @@
225225 * @throws NullPointerException if {@code cluster} is {@code null}.
226226 */
227227 public static QueryLogger.Builder builder(Cluster cluster) {
228- if(cluster == null) throw new NullPointerException("QueryLogger.Builder: cluster parameter cannot be null");
228+ if (cluster == null) throw new NullPointerException("QueryLogger.Builder: cluster parameter cannot be null");
229229 return new QueryLogger.Builder(cluster);
230230 }
231231
@@ -290,10 +290,10 @@
290290 /**
291291 * A QueryLogger that uses a dynamic threshold in milliseconds
292292 * to track slow queries.
293- * <p>
293+ * <p/>
294294 * Dynamic thresholds are based on per-host latency percentiles, as computed
295295 * by {@link PerHostPercentileTracker}.
296- * <p>
296+ * <p/>
297297 * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
298298 * to change.</b>
299299 */
@@ -350,7 +350,7 @@
350350 * and logged as such by the driver.
351351 *
352352 * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
353- * It must be comprised between 0 inclusive and 100 exclusive.
353+ * It must be comprised between 0 inclusive and 100 exclusive.
354354 * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdPercentile < 0 || slowQueryLatencyThresholdPercentile >= 100}.
355355 */
356356 public void setSlowQueryLatencyThresholdPercentile(double slowQueryLatencyThresholdPercentile) {
@@ -404,7 +404,7 @@
404404
405405 /**
406406 * Enables slow query latency tracking based on constant thresholds.
407- * <p>
407+ * <p/>
408408 * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
409409 * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
410410 * not both.
@@ -422,22 +422,22 @@
422422
423423 /**
424424 * Enables slow query latency tracking based on dynamic thresholds.
425- * <p>
425+ * <p/>
426426 * Dynamic thresholds are based on per-host latency percentiles, as computed
427427 * by {@link PerHostPercentileTracker}.
428- * <p>
428+ * <p/>
429429 * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
430430 * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
431431 * not both.
432- * <p>
432+ * <p/>
433433 * <b>This feature is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
434434 * to change.</b>
435435 *
436- * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
437- * Cannot be {@code null}.
436+ * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
437+ * Cannot be {@code null}.
438438 * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
439- * It must be comprised between 0 inclusive and 100 exclusive.
440- * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}
439+ * It must be comprised between 0 inclusive and 100 exclusive.
440+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}
441441 * @return this {@link Builder} instance (for method chaining).
442442 */
443443 @Beta
@@ -503,11 +503,12 @@
503503
504504 /**
505505 * Build the {@link QueryLogger} instance.
506+ *
506507 * @return the {@link QueryLogger} instance.
507508 * @throws IllegalArgumentException if the builder is unable to build a valid instance due to incorrect settings.
508509 */
509510 public QueryLogger build() {
510- if(constantThreshold) {
511+ if (constantThreshold) {
511512 return new ConstantThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdMillis);
512513 } else {
513514 return new DynamicThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdPercentile, perHostPercentileLatencyTracker);
@@ -644,13 +645,13 @@
644645 if (showParameterValues) {
645646 StringBuilder params = new StringBuilder();
646647 if (statement instanceof BoundStatement) {
647- appendParameters((BoundStatement)statement, params, maxLoggedParameters);
648+ appendParameters((BoundStatement) statement, params, maxLoggedParameters);
648649 } else if (statement instanceof BatchStatement) {
649- BatchStatement batchStatement = (BatchStatement)statement;
650+ BatchStatement batchStatement = (BatchStatement) statement;
650651 int remaining = maxLoggedParameters;
651652 for (Statement inner : batchStatement.getStatements()) {
652653 if (inner instanceof BoundStatement) {
653- remaining = appendParameters((BoundStatement)inner, params, remaining);
654+ remaining = appendParameters((BoundStatement) inner, params, remaining);
654655 }
655656 }
656657 }
@@ -665,12 +666,12 @@
665666 protected String statementAsString(Statement statement) {
666667 StringBuilder sb = new StringBuilder();
667668 if (statement instanceof BatchStatement) {
668- BatchStatement bs = (BatchStatement)statement;
669+ BatchStatement bs = (BatchStatement) statement;
669670 int statements = bs.getStatements().size();
670671 int boundValues = countBoundValues(bs);
671672 sb.append("[" + statements + " statements, " + boundValues + " bound values] ");
672673 } else if (statement instanceof BoundStatement) {
673- int boundValues = ((BoundStatement)statement).wrapper.values.length;
674+ int boundValues = ((BoundStatement) statement).wrapper.values.length;
674675 sb.append("[" + boundValues + " bound values] ");
675676 }
676677
@@ -682,7 +683,7 @@
682683 int count = 0;
683684 for (Statement s : bs.getStatements()) {
684685 if (s instanceof BoundStatement)
685- count += ((BoundStatement)s).wrapper.values.length;
686+ count += ((BoundStatement) s).wrapper.values.length;
686687 }
687688 return count;
688689 }
@@ -727,7 +728,7 @@
727728 int maxBufferLength = Math.max(2, (maxParameterValueLength - 2) / 2);
728729 boolean bufferTooLarge = raw.remaining() > maxBufferLength;
729730 if (bufferTooLarge) {
730- raw = (ByteBuffer)raw.duplicate().limit(maxBufferLength);
731+ raw = (ByteBuffer) raw.duplicate().limit(maxBufferLength);
731732 }
732733 Object value = type.deserialize(raw, protocolVersion());
733734 valueStr = type.format(value);
@@ -759,14 +760,14 @@
759760
760761 protected int append(Statement statement, StringBuilder buffer, int remaining) {
761762 if (statement instanceof StatementWrapper)
762- statement = ((StatementWrapper)statement).getWrappedStatement();
763+ statement = ((StatementWrapper) statement).getWrappedStatement();
763764
764765 if (statement instanceof RegularStatement) {
765- remaining = append(((RegularStatement)statement).getQueryString().trim(), buffer, remaining);
766+ remaining = append(((RegularStatement) statement).getQueryString().trim(), buffer, remaining);
766767 } else if (statement instanceof BoundStatement) {
767- remaining = append(((BoundStatement)statement).preparedStatement().getQueryString().trim(), buffer, remaining);
768+ remaining = append(((BoundStatement) statement).preparedStatement().getQueryString().trim(), buffer, remaining);
768769 } else if (statement instanceof BatchStatement) {
769- BatchStatement batchStatement = (BatchStatement)statement;
770+ BatchStatement batchStatement = (BatchStatement) statement;
770771 remaining = append("BEGIN", buffer, remaining);
771772 switch (batchStatement.batchType) {
772773 case UNLOGGED:
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +43 −46
@@ -77,7 +77,8 @@
7777 * Creates a new {@link QueryOptions} instance using the {@link #DEFAULT_CONSISTENCY_LEVEL},
7878 * {@link #DEFAULT_SERIAL_CONSISTENCY_LEVEL} and {@link #DEFAULT_FETCH_SIZE}.
7979 */
80- public QueryOptions() {}
80+ public QueryOptions() {
81+ }
8182
8283 void register(Cluster.Manager manager) {
8384 this.manager = manager;
@@ -85,7 +86,7 @@
8586
8687 /**
8788 * Sets the default consistency level to use for queries.
88- * <p>
89+ * <p/>
8990 * The consistency level set through this method will be use for queries
9091 * that don't explicitly have a consistency level, i.e. when {@link Statement#getConsistencyLevel}
9192 * returns {@code null}.
@@ -109,7 +110,7 @@
109110
110111 /**
111112 * Sets the default serial consistency level to use for queries.
112- * <p>
113+ * <p/>
113114 * The serial consistency level set through this method will be use for queries
114115 * that don't explicitly have a serial consistency level, i.e. when {@link Statement#getSerialConsistencyLevel}
115116 * returns {@code null}.
@@ -133,21 +134,20 @@
133134
134135 /**
135136 * Sets the default fetch size to use for SELECT queries.
136- * <p>
137+ * <p/>
137138 * The fetch size set through this method will be use for queries
138139 * that don't explicitly have a fetch size, i.e. when {@link Statement#getFetchSize}
139140 * is less or equal to 0.
140141 *
141142 * @param fetchSize the new fetch size to set as default. It must be
142- * strictly positive but you can use {@code Integer.MAX_VALUE} to disable
143- * paging.
143+ * strictly positive but you can use {@code Integer.MAX_VALUE} to disable
144+ * paging.
144145 * @return this {@code QueryOptions} instance.
145- *
146- * @throws IllegalArgumentException if {@code fetchSize &lte; 0}.
146+ * @throws IllegalArgumentException if {@code fetchSize &lte; 0}.
147147 * @throws UnsupportedFeatureException if version 1 of the native protocol is in
148- * use and {@code fetchSize != Integer.MAX_VALUE} as paging is not supported by
149- * version 1 of the protocol. See {@link Cluster.Builder#withProtocolVersion}
150- * for more details on protocol versions.
148+ * use and {@code fetchSize != Integer.MAX_VALUE} as paging is not supported by
149+ * version 1 of the protocol. See {@link Cluster.Builder#withProtocolVersion}
150+ * for more details on protocol versions.
151151 */
152152 public QueryOptions setFetchSize(int fetchSize) {
153153 if (fetchSize <= 0)
@@ -172,7 +172,7 @@
172172
173173 /**
174174 * Sets the default idempotence for queries.
175- * <p>
175+ * <p/>
176176 * This will be used for statements for which {@link com.datastax.driver.core.Statement#isIdempotent()}
177177 * returns {@code null}.
178178 *
@@ -186,7 +186,7 @@
186186
187187 /**
188188 * The default idempotence for queries.
189- * <p>
189+ * <p/>
190190 * It defaults to {@link #DEFAULT_IDEMPOTENCE}.
191191 *
192192 * @return the default idempotence for queries.
@@ -197,20 +197,20 @@
197197
198198 /**
199199 * Set whether the driver should prepare statements on all hosts in the cluster.
200- * <p>
200+ * <p/>
201201 * A statement is normally prepared in two steps:
202202 * <ol>
203- * <li>prepare the query on a single host in the cluster;</li>
204- * <li>if that succeeds, prepare on all other hosts.</li>
203+ * <li>prepare the query on a single host in the cluster;</li>
204+ * <li>if that succeeds, prepare on all other hosts.</li>
205205 * </ol>
206206 * This option controls whether step 2 is executed. It is enabled by default.
207- * <p>
207+ * <p/>
208208 * The reason why you might want to disable it is to optimize network usage if you
209209 * have a large number of clients preparing the same set of statements at startup.
210210 * If your load balancing policy distributes queries randomly, each client will pick
211211 * a different host to prepare its statements, and on the whole each host has a good
212212 * chance of having been hit by at least one client for each statement.
213- * <p>
213+ * <p/>
214214 * On the other hand, if that assumption turns out to be wrong and one host hasn't
215215 * prepared a given statement, it needs to be re-prepared on the fly the first time
216216 * it gets executed; this causes a performance penalty (one extra roundtrip to resend
@@ -229,7 +229,6 @@
229229 * Returns whether the driver should prepare statements on all hosts in the cluster.
230230 *
231231 * @return the value.
232- *
233232 * @see #setPrepareOnAllHosts(boolean)
234233 */
235234 public boolean isPrepareOnAllHosts() {
@@ -239,14 +238,14 @@
239238 /**
240239 * Set whether the driver should re-prepare all cached prepared statements on a host
241240 * when it marks it back up.
242- * <p>
241+ * <p/>
243242 * This option is enabled by default.
244- * <p>
243+ * <p/>
245244 * The reason why you might want to disable it is to optimize reconnection time when
246245 * you believe hosts often get marked down because of temporary network issues, rather
247246 * than the host really crashing. In that case, the host still has prepared statements
248247 * in its cache when the driver reconnects, so re-preparing is redundant.
249- * <p>
248+ * <p/>
250249 * On the other hand, if that assumption turns out to be wrong and the host had
251250 * really restarted, its prepared statement cache is empty, and statements need to be
252251 * re-prepared on the fly the first time they get executed; this causes a performance
@@ -256,7 +255,7 @@
256255 * @param reprepareOnUp whether the driver should re-prepare when marking a node up.
257256 * @return this {@code QueryOptions} instance.
258257 */
259- public QueryOptions setReprepareOnUp(boolean reprepareOnUp){
258+ public QueryOptions setReprepareOnUp(boolean reprepareOnUp) {
260259 this.reprepareOnUp = reprepareOnUp;
261260 return this;
262261 }
@@ -266,7 +265,6 @@
266265 * when its marks that host back up.
267266 *
268267 * @return the value.
269- *
270268 * @see #setReprepareOnUp(boolean)
271269 */
272270 public boolean isReprepareOnUp() {
@@ -275,23 +273,23 @@
275273
276274 /**
277275 * Toggle client-side token and schema metadata.
278- * <p>
276+ * <p/>
279277 * This feature is enabled by default. Some applications might wish to disable it
280278 * in order to eliminate the overhead of querying the metadata and building its
281279 * client-side representation. However, take note that doing so will have important
282280 * consequences:
283281 * <ul>
284- * <li>most schema- or token-related methods in {@link Metadata} will return stale
285- * or null/empty results (see the javadoc of each method for details);</li>
286- * <li>{@link Metadata#newToken(String)} and
287- * {@link Metadata#newTokenRange(Token, Token)} will throw an exception if metadata
288- * was disabled before startup;</li>
289- * <li>token-aware routing will not work properly: if metadata was never initialized,
290- * {@link com.datastax.driver.core.policies.TokenAwarePolicy} will always delegate
291- * to its child policy. Otherwise, it might not pick the best coordinator (i.e. chose
292- * a host that is not a replica for the statement's routing key). In addition, statements
293- * prepared while the metadata was disabled might also be sent to a non-optimal coordinator,
294- * even if metadata was re-enabled later.</li>
282+ * <li>most schema- or token-related methods in {@link Metadata} will return stale
283+ * or null/empty results (see the javadoc of each method for details);</li>
284+ * <li>{@link Metadata#newToken(String)} and
285+ * {@link Metadata#newTokenRange(Token, Token)} will throw an exception if metadata
286+ * was disabled before startup;</li>
287+ * <li>token-aware routing will not work properly: if metadata was never initialized,
288+ * {@link com.datastax.driver.core.policies.TokenAwarePolicy} will always delegate
289+ * to its child policy. Otherwise, it might not pick the best coordinator (i.e. chose
290+ * a host that is not a replica for the statement's routing key). In addition, statements
291+ * prepared while the metadata was disabled might also be sent to a non-optimal coordinator,
292+ * even if metadata was re-enabled later.</li>
295293 * </ul>
296294 *
297295 * @param enabled whether metadata is enabled.
@@ -310,7 +308,6 @@
310308 * Whether client-side token and schema metadata is enabled.
311309 *
312310 * @return the value.
313- *
314311 * @see #setMetadataEnabled(boolean)
315312 */
316313 public boolean isMetadataEnabled() {
@@ -319,7 +316,7 @@
319316
320317 /**
321318 * Sets the default window size in milliseconds used to debounce node list refresh requests.
322- * <p>
319+ * <p/>
323320 * When the control connection receives a new schema refresh request,
324321 * it puts it on hold and starts a timer, cancelling any previous running timer;
325322 * when a timer expires, then the pending requests are coalesced and executed
@@ -344,14 +341,14 @@
344341 /**
345342 * Sets the maximum number of schema refresh requests that the control connection can accumulate
346343 * before executing them.
347- * <p>
344+ * <p/>
348345 * When the control connection receives a new schema refresh request,
349346 * it puts it on hold and starts a timer, cancelling any previous running timer;
350347 * if the control connection receives too many events, is parameter allows to trigger
351348 * execution of pending requests, event if the last timer is still running.
352349 *
353350 * @param maxPendingRefreshSchemaRequests The maximum number of schema refresh requests that the control connection can accumulate
354- * before executing them.
351+ * before executing them.
355352 */
356353 public QueryOptions setMaxPendingRefreshSchemaRequests(int maxPendingRefreshSchemaRequests) {
357354 this.maxPendingRefreshSchemaRequests = maxPendingRefreshSchemaRequests;
@@ -371,7 +368,7 @@
371368
372369 /**
373370 * Sets the default window size in milliseconds used to debounce node list refresh requests.
374- * <p>
371+ * <p/>
375372 * When the control connection receives a new node list refresh request,
376373 * it puts it on hold and starts a timer, cancelling any previous running timer;
377374 * when a timer expires, then the pending requests are coalesced and executed
@@ -396,14 +393,14 @@
396393 /**
397394 * Sets the maximum number of node list refresh requests that the control connection can accumulate
398395 * before executing them.
399- * <p>
396+ * <p/>
400397 * When the control connection receives a new node list refresh request,
401398 * it puts it on hold and starts a timer, cancelling any previous running timer;
402399 * if the control connection receives too many events, is parameter allows to trigger
403400 * execution of pending requests, event if the last timer is still running.
404401 *
405402 * @param maxPendingRefreshNodeListRequests The maximum number of node list refresh requests that the control connection can accumulate
406- * before executing them.
403+ * before executing them.
407404 */
408405 public QueryOptions setMaxPendingRefreshNodeListRequests(int maxPendingRefreshNodeListRequests) {
409406 this.maxPendingRefreshNodeListRequests = maxPendingRefreshNodeListRequests;
@@ -423,7 +420,7 @@
423420
424421 /**
425422 * Sets the default window size in milliseconds used to debounce node refresh requests.
426- * <p>
423+ * <p/>
427424 * When the control connection receives a new node refresh request,
428425 * it puts it on hold and starts a timer, cancelling any previous running timer;
429426 * when a timer expires, then the pending requests are coalesced and executed
@@ -448,14 +445,14 @@
448445 /**
449446 * Sets the maximum number of node refresh requests that the control connection can accumulate
450447 * before executing them.
451- * <p>
448+ * <p/>
452449 * When the control connection receives a new node refresh request,
453450 * it puts it on hold and starts a timer, cancelling any previous running timer;
454451 * if the control connection receives too many events, is parameter allows to trigger
455452 * execution of pending requests, event if the last timer is still running.
456453 *
457454 * @param maxPendingRefreshNodeRequests The maximum number of node refresh requests that the control connection can accumulate
458- * before executing them.
455+ * before executing them.
459456 */
460457 public QueryOptions setMaxPendingRefreshNodeRequests(int maxPendingRefreshNodeRequests) {
461458 this.maxPendingRefreshNodeRequests = maxPendingRefreshNodeRequests;
modified driver-core/src/main/java/com/datastax/driver/core/QueryTrace.java +18 −25
@@ -15,25 +15,24 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.TraceRetrievalException;
19+import com.google.common.util.concurrent.Uninterruptibles;
20+
1821 import java.net.InetAddress;
1922 import java.util.*;
2023 import java.util.concurrent.TimeUnit;
2124 import java.util.concurrent.locks.Lock;
2225 import java.util.concurrent.locks.ReentrantLock;
2326
24-import com.google.common.util.concurrent.Uninterruptibles;
25-
26-import com.datastax.driver.core.exceptions.TraceRetrievalException;
27-
2827 /**
2928 * The Cassandra trace for a query.
30- * <p>
29+ * <p/>
3130 * A trace is generated by Cassandra when query tracing is enabled for the
3231 * query. The trace itself is stored in Cassandra in the {@code sessions} and
3332 * {@code events} table in the {@code system_traces} keyspace and can be
3433 * retrieve manually using the trace identifier (the one returned by
3534 * {@link #getTraceId}).
36- * <p>
35+ * <p/>
3736 * This class provides facilities to fetch the traces from Cassandra. Please
3837 * note that the writing of the trace is done asynchronously in Cassandra. So
3938 * accessing the trace too soon after the query may result in the trace being
@@ -68,7 +67,7 @@
6867
6968 /**
7069 * Returns the identifier of this trace.
71- * <p>
70+ * <p/>
7271 * Note that contrary to the other methods in this class, this
7372 * does not entail fetching query trace details from Cassandra.
7473 *
@@ -83,9 +82,8 @@
8382 *
8483 * @return the type of request or {@code null} if the request
8584 * type is not yet available.
86- *
8785 * @throws TraceRetrievalException if the trace details cannot be retrieve
88- * from Cassandra successfully.
86+ * from Cassandra successfully.
8987 */
9088 public String getRequestType() {
9189 maybeFetchTrace();
@@ -98,9 +96,8 @@
9896 * @return the (server side) duration of the query in microseconds. This
9997 * method will return {@code Integer.MIN_VALUE} if the duration is not yet
10098 * available.
101- *
10299 * @throws TraceRetrievalException if the trace details cannot be retrieve
103- * from Cassandra successfully.
100+ * from Cassandra successfully.
104101 */
105102 public int getDurationMicros() {
106103 maybeFetchTrace();
@@ -112,9 +109,8 @@
112109 *
113110 * @return the coordinator host of the query or {@code null}
114111 * if the coordinator is not yet available.
115- *
116112 * @throws TraceRetrievalException if the trace details cannot be retrieve
117- * from Cassandra successfully.
113+ * from Cassandra successfully.
118114 */
119115 public InetAddress getCoordinator() {
120116 maybeFetchTrace();
@@ -126,9 +122,8 @@
126122 *
127123 * @return the parameters attached to this trace. or
128124 * {@code null} if the coordinator is not yet available.
129- *
130125 * @throws TraceRetrievalException if the trace details cannot be retrieve
131- * from Cassandra successfully.
126+ * from Cassandra successfully.
132127 */
133128 public Map<String, String> getParameters() {
134129 maybeFetchTrace();
@@ -140,9 +135,8 @@
140135 *
141136 * @return the server side timestamp of the start of this query or
142137 * 0 if the start timestamp is not available.
143- *
144138 * @throws TraceRetrievalException if the trace details cannot be retrieve
145- * from Cassandra successfully.
139+ * from Cassandra successfully.
146140 */
147141 public long getStartedAt() {
148142 maybeFetchTrace();
@@ -151,7 +145,7 @@
151145
152146 /**
153147 * Returns the events contained in this trace.
154- * <p>
148+ * <p/>
155149 * Query tracing is asynchronous in Cassandra. Hence, it
156150 * is possible for the list returned to be missing some events for some of
157151 * the replica involved in the query if the query trace is requested just
@@ -160,9 +154,8 @@
160154 * the query).
161155 *
162156 * @return the events contained in this trace.
163- *
164157 * @throws TraceRetrievalException if the trace details cannot be retrieve
165- * from Cassandra successfully.
158+ * from Cassandra successfully.
166159 */
167160 public List<Event> getEvents() {
168161 maybeFetchTrace();
@@ -211,10 +204,10 @@
211204 events = new ArrayList<Event>();
212205 for (Row evRow : eventsFuture.get()) {
213206 events.add(new Event(evRow.getString("activity"),
214- evRow.getUUID("event_id").timestamp(),
215- evRow.getInet("source"),
216- evRow.getInt("source_elapsed"),
217- evRow.getString("thread")));
207+ evRow.getUUID("event_id").timestamp(),
208+ evRow.getInet("source"),
209+ evRow.getInt("source_elapsed"),
210+ evRow.getString("thread")));
218211 }
219212 events = Collections.unmodifiableList(events);
220213
@@ -237,7 +230,7 @@
237230
238231 /**
239232 * A trace event.
240- * <p>
233+ * <p/>
241234 * A query trace is composed of a list of trace events.
242235 */
243236 public static class Event {
modified driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java +5 −6
@@ -19,7 +19,7 @@
1919
2020 /**
2121 * A regular (non-prepared and non batched) CQL statement.
22- * <p>
22+ * <p/>
2323 * This class represents a query string along with query options (and optionally
2424 * binary values, see {@code getValues}). It can be extended but {@link SimpleStatement}
2525 * is provided as a simple implementation to build a {@code RegularStatement} directly
@@ -30,7 +30,8 @@
3030 /**
3131 * Creates a new RegularStatement.
3232 */
33- protected RegularStatement() {}
33+ protected RegularStatement() {
34+ }
3435
3536 /**
3637 * Returns the query string for this statement.
@@ -41,7 +42,7 @@
4142
4243 /**
4344 * The values to use for this statement.
44- * <p>
45+ * <p/>
4546 * Note: Values for a RegularStatement (i.e. if this method does not return
4647 * {@code null}) are not supported with the native protocol version 1: you
4748 * will get an {@link UnsupportedProtocolVersionException} when submitting
@@ -50,10 +51,9 @@
5051 * Cassandra 1.2).
5152 *
5253 * @param protocolVersion the protocol version in which the returned values
53- * must be serialized for.
54+ * must be serialized for.
5455 * @return the values to use for this statement or {@code null} if there is
5556 * no such values.
56- *
5757 * @see SimpleStatement#SimpleStatement(String, Object...)
5858 */
5959 public abstract ByteBuffer[] getValues(ProtocolVersion protocolVersion);
@@ -62,7 +62,6 @@
6262 * The values to use for this statement, for the given numeric protocol version.
6363 *
6464 * @throws IllegalArgumentException if {@code protocolVersion} does not correspond to any known version.
65- *
6665 * @deprecated This method is provided for backward compatibility. Use
6766 * {@link #getValues(ProtocolVersion)} instead.
6867 */
modified driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +12 −13
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
2018 import com.google.common.collect.ImmutableSet;
2119 import com.google.common.collect.Maps;
2220 import com.google.common.collect.Sets;
2321 import org.slf4j.Logger;
2422 import org.slf4j.LoggerFactory;
2523
24+import java.util.*;
25+
2626 /*
2727 * Computes the token->list<replica> association, given the token ring and token->primary token map.
2828 *
@@ -42,8 +42,7 @@
4242 return repFactorString == null ? null : new SimpleStrategy(Integer.parseInt(repFactorString));
4343 } else if (strategyClass.contains("NetworkTopologyStrategy")) {
4444 Map<String, Integer> dcRfs = new HashMap<String, Integer>();
45- for (Map.Entry<String, String> entry : replicationOptions.entrySet())
46- {
45+ for (Map.Entry<String, String> entry : replicationOptions.entrySet()) {
4746 if (entry.getKey().equals("class"))
4847 continue;
4948
@@ -83,7 +82,7 @@
8382 // Consecutive sections of the ring can assigned to the same host
8483 Set<Host> replicas = new LinkedHashSet<Host>();
8584 for (int j = 0; j < ring.size() && replicas.size() < rf; j++)
86- replicas.add(tokenToPrimary.get(getTokenWrapping(i+j, ring)));
85+ replicas.add(tokenToPrimary.get(getTokenWrapping(i + j, ring)));
8786 replicaMap.put(ring.get(i), ImmutableSet.copyOf(replicas));
8887 }
8988 return replicaMap;
@@ -96,7 +95,7 @@
9695 if (o == null || getClass() != o.getClass())
9796 return false;
9897
99- SimpleStrategy that = (SimpleStrategy)o;
98+ SimpleStrategy that = (SimpleStrategy) o;
10099
101100 return replicationFactor == that.replicationFactor;
102101
@@ -119,7 +118,7 @@
119118
120119 Map<Token, Set<Host>> computeTokenToReplicaMap(String keyspaceName, Map<Token, Host> tokenToPrimary, List<Token> ring) {
121120
122- // This is essentially a copy of org.apache.cassandra.locator.NetworkTopologyStrategy
121+ // This is essentially a copy of org.apache.cassandra.locator.NetworkTopologyStrategy
123122 Map<String, Set<String>> racks = getRacksInDcs(tokenToPrimary.values());
124123 Map<Token, Set<Host>> replicaMap = new HashMap<Token, Set<Host>>(tokenToPrimary.size());
125124 Map<String, Integer> dcHostCount = Maps.newHashMapWithExpectedSize(replicationFactors.size());
@@ -127,7 +126,7 @@
127126 // find maximum number of nodes in each DC
128127 for (Host host : Sets.newHashSet(tokenToPrimary.values())) {
129128 String dc = host.getDatacenter();
130- if(dcHostCount.get(dc) == null) {
129+ if (dcHostCount.get(dc) == null) {
131130 dcHostCount.put(dc, 0);
132131 }
133132 dcHostCount.put(dc, dcHostCount.get(dc) + 1);
@@ -190,9 +189,9 @@
190189 int achievedFactor = entry.getValue().size();
191190 if (achievedFactor < expectedFactor && !warnedDcs.contains(dcName)) {
192191 logger.warn("Error while computing token map for keyspace {} with datacenter {}: "
193- + "could not achieve replication factor {} (found {} replicas only), "
194- + "check your keyspace replication settings.",
195- keyspaceName, dcName, expectedFactor, achievedFactor);
192+ + "could not achieve replication factor {} (found {} replicas only), "
193+ + "check your keyspace replication settings.",
194+ keyspaceName, dcName, expectedFactor, achievedFactor);
196195 // only warn once per DC
197196 warnedDcs.add(dcName);
198197 }
@@ -206,7 +205,7 @@
206205 private boolean allDone(Map<String, Set<Host>> map, Map<String, Integer> dcHostCount) {
207206 for (Map.Entry<String, Set<Host>> entry : map.entrySet()) {
208207 String dc = entry.getKey();
209- int dcCount = dcHostCount.get(dc) == null? 0 : dcHostCount.get(dc);
208+ int dcCount = dcHostCount.get(dc) == null ? 0 : dcHostCount.get(dc);
210209 if (entry.getValue().size() < Math.min(replicationFactors.get(dc), dcCount))
211210 return false;
212211 }
@@ -233,7 +232,7 @@
233232 if (o == null || getClass() != o.getClass())
234233 return false;
235234
236- NetworkTopologyStrategy that = (NetworkTopologyStrategy)o;
235+ NetworkTopologyStrategy that = (NetworkTopologyStrategy) o;
237236
238237 return replicationFactors.equals(that.replicationFactors);
239238
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +68 −66
@@ -15,6 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.codahale.metrics.Timer;
19+import com.datastax.driver.core.exceptions.*;
20+import com.datastax.driver.core.policies.RetryPolicy;
21+import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type;
22+import com.datastax.driver.core.policies.SpeculativeExecutionPolicy.SpeculativeExecutionPlan;
23+import com.google.common.collect.Sets;
24+import io.netty.util.Timeout;
25+import io.netty.util.TimerTask;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+
1829 import java.net.InetSocketAddress;
1930 import java.util.*;
2031 import java.util.concurrent.ConcurrentHashMap;
@@ -25,18 +36,6 @@
2536 import java.util.concurrent.atomic.AtomicInteger;
2637 import java.util.concurrent.atomic.AtomicReference;
2738
28-import com.codahale.metrics.Timer;
29-import com.google.common.collect.Sets;
30-import io.netty.util.Timeout;
31-import io.netty.util.TimerTask;
32-import org.slf4j.Logger;
33-import org.slf4j.LoggerFactory;
34-
35-import com.datastax.driver.core.exceptions.*;
36-import com.datastax.driver.core.policies.RetryPolicy;
37-import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type;
38-import com.datastax.driver.core.policies.SpeculativeExecutionPolicy.SpeculativeExecutionPlan;
39-
4039 /**
4140 * Handles a request to cassandra, dealing with host failover and retries on
4241 * unavailable/timeout.
@@ -69,7 +68,7 @@
6968
7069 public RequestHandler(SessionManager manager, Callback callback, Statement statement) {
7170 this.id = Long.toString(System.identityHashCode(this));
72- if(logger.isTraceEnabled())
71+ if (logger.isTraceEnabled())
7372 logger.trace("[{}] {}", id, statement);
7473 this.manager = manager;
7574 this.callback = callback;
@@ -80,12 +79,12 @@
8079 this.queryPlan = new QueryPlan(manager.loadBalancingPolicy().newQueryPlan(manager.poolsState.keyspace, statement));
8180 this.speculativeExecutionPlan = manager.speculativeRetryPolicy().newPlan(manager.poolsState.keyspace, statement);
8281 this.allowSpeculativeExecutions = statement != Statement.DEFAULT
83- && statement.isIdempotentWithDefault(manager.configuration().getQueryOptions());
82+ && statement.isIdempotentWithDefault(manager.configuration().getQueryOptions());
8483 this.statement = statement;
8584
8685 this.timerContext = metricsEnabled()
87- ? metrics().getRequestsTimer().time()
88- : null;
86+ ? metrics().getRequestsTimer().time()
87+ : null;
8988 this.startTime = System.nanoTime();
9089 }
9190
@@ -120,7 +119,7 @@
120119 private void scheduleExecution(long delayMillis) {
121120 if (isDone.get() || delayMillis <= 0)
122121 return;
123- if(logger.isTraceEnabled())
122+ if (logger.isTraceEnabled())
124123 logger.trace("[{}] Schedule next speculative execution in {} ms", id, delayMillis);
125124 scheduledExecutions.add(scheduler.newTimeout(newExecutionTask, delayMillis, TimeUnit.MILLISECONDS));
126125 }
@@ -159,12 +158,12 @@
159158
160159 private void setFinalResult(SpeculativeExecution execution, Connection connection, Message.Response response) {
161160 if (!isDone.compareAndSet(false, true)) {
162- if(logger.isTraceEnabled())
161+ if (logger.isTraceEnabled())
163162 logger.trace("[{}] Got beaten to setting the result", execution.id);
164163 return;
165164 }
166165
167- if(logger.isTraceEnabled())
166+ if (logger.isTraceEnabled())
168167 logger.trace("[{}] Setting final result", execution.id);
169168
170169 cancelPendingExecutions(execution);
@@ -183,19 +182,19 @@
183182 callback.onSet(connection, response, info, statement, System.nanoTime() - startTime);
184183 } catch (Exception e) {
185184 callback.onException(connection,
186- new DriverInternalError("Unexpected exception while setting final result from " + response, e),
187- System.nanoTime() - startTime, /*unused*/0);
185+ new DriverInternalError("Unexpected exception while setting final result from " + response, e),
186+ System.nanoTime() - startTime, /*unused*/0);
188187 }
189188 }
190189
191190 private void setFinalException(SpeculativeExecution execution, Connection connection, Exception exception) {
192191 if (!isDone.compareAndSet(false, true)) {
193- if(logger.isTraceEnabled())
192+ if (logger.isTraceEnabled())
194193 logger.trace("[{}] Got beaten to setting final exception", execution.id);
195194 return;
196195 }
197196
198- if(logger.isTraceEnabled())
197+ if (logger.isTraceEnabled())
199198 logger.trace("[{}] Setting final exception", execution.id);
200199
201200 cancelPendingExecutions(execution);
@@ -214,7 +213,7 @@
214213 runningExecutions.remove(execution);
215214 if (runningExecutions.isEmpty())
216215 setFinalException(execution, null, new NoHostAvailableException(
217- errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors));
216+ errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors));
218217 }
219218
220219 private boolean metricsEnabled() {
@@ -227,6 +226,7 @@
227226
228227 interface Callback extends Connection.ResponseCallback {
229228 void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency);
229+
230230 void register(RequestHandler handler);
231231 }
232232
@@ -260,7 +260,7 @@
260260 this.id = RequestHandler.this.id + "-" + position;
261261 this.request = request;
262262 this.queryStateRef = new AtomicReference<QueryState>(QueryState.INITIAL);
263- if(logger.isTraceEnabled())
263+ if (logger.isTraceEnabled())
264264 logger.trace("[{}] Starting", id);
265265 }
266266
@@ -268,7 +268,7 @@
268268 try {
269269 Host host;
270270 while (!isDone.get() && (host = queryPlan.next()) != null && !queryStateRef.get().isCancelled()) {
271- if(logger.isTraceEnabled())
271+ if (logger.isTraceEnabled())
272272 logger.trace("[{}] Querying node {}", id, host);
273273 if (query(host))
274274 return;
@@ -387,7 +387,7 @@
387387 if (previous.isCancelled()) {
388388 return;
389389 } else if (previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_IN_PROGRESS)) {
390- if(logger.isTraceEnabled())
390+ if (logger.isTraceEnabled())
391391 logger.trace("[{}] Cancelled while in progress", id);
392392 // The connectionHandler should be non-null, but we might miss the update if we're racing with write().
393393 // If it's still null, this will be handled by re-checking queryStateRef at the end of write().
@@ -395,7 +395,7 @@
395395 connectionHandler.connection.release();
396396 return;
397397 } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) {
398- if(logger.isTraceEnabled())
398+ if (logger.isTraceEnabled())
399399 logger.trace("[{}] Cancelled while complete", id);
400400 return;
401401 }
@@ -414,9 +414,9 @@
414414 public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
415415 QueryState queryState = queryStateRef.get();
416416 if (!queryState.isInProgressAt(retryCount) ||
417- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
417+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
418418 logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
419- retryCount, queryState, queryStateRef.get());
419+ retryCount, queryState, queryStateRef.get());
420420 return;
421421 }
422422
@@ -429,12 +429,12 @@
429429 setFinalResult(connection, response);
430430 break;
431431 case ERROR:
432- Responses.Error err = (Responses.Error)response;
432+ Responses.Error err = (Responses.Error) response;
433433 exceptionToReport = err.asException(connection.address);
434434 RetryPolicy.RetryDecision retry = null;
435435 RetryPolicy retryPolicy = statement.getRetryPolicy() == null
436- ? manager.configuration().getPolicies().getRetryPolicy()
437- : statement.getRetryPolicy();
436+ ? manager.configuration().getPolicies().getRetryPolicy()
437+ : statement.getRetryPolicy();
438438 switch (err.code) {
439439 case READ_TIMEOUT:
440440 connection.release();
@@ -442,13 +442,13 @@
442442 if (metricsEnabled())
443443 metrics().getErrorMetrics().getReadTimeouts().inc();
444444
445- ReadTimeoutException rte = (ReadTimeoutException)err.infos;
445+ ReadTimeoutException rte = (ReadTimeoutException) err.infos;
446446 retry = retryPolicy.onReadTimeout(statement,
447- rte.getConsistencyLevel(),
448- rte.getRequiredAcknowledgements(),
449- rte.getReceivedAcknowledgements(),
450- rte.wasDataRetrieved(),
451- retriesByPolicy);
447+ rte.getConsistencyLevel(),
448+ rte.getRequiredAcknowledgements(),
449+ rte.getReceivedAcknowledgements(),
450+ rte.wasDataRetrieved(),
451+ retriesByPolicy);
452452
453453 if (metricsEnabled()) {
454454 if (retry.getType() == Type.RETRY)
@@ -463,13 +463,13 @@
463463 if (metricsEnabled())
464464 metrics().getErrorMetrics().getWriteTimeouts().inc();
465465
466- WriteTimeoutException wte = (WriteTimeoutException)err.infos;
466+ WriteTimeoutException wte = (WriteTimeoutException) err.infos;
467467 retry = retryPolicy.onWriteTimeout(statement,
468- wte.getConsistencyLevel(),
469- wte.getWriteType(),
470- wte.getRequiredAcknowledgements(),
471- wte.getReceivedAcknowledgements(),
472- retriesByPolicy);
468+ wte.getConsistencyLevel(),
469+ wte.getWriteType(),
470+ wte.getRequiredAcknowledgements(),
471+ wte.getReceivedAcknowledgements(),
472+ retriesByPolicy);
473473
474474 if (metricsEnabled()) {
475475 if (retry.getType() == Type.RETRY)
@@ -484,12 +484,12 @@
484484 if (metricsEnabled())
485485 metrics().getErrorMetrics().getUnavailables().inc();
486486
487- UnavailableException ue = (UnavailableException)err.infos;
487+ UnavailableException ue = (UnavailableException) err.infos;
488488 retry = retryPolicy.onUnavailable(statement,
489- ue.getConsistencyLevel(),
490- ue.getRequiredReplicas(),
491- ue.getAliveReplicas(),
492- retriesByPolicy);
489+ ue.getConsistencyLevel(),
490+ ue.getRequiredReplicas(),
491+ ue.getAliveReplicas(),
492+ retriesByPolicy);
493493
494494 if (metricsEnabled()) {
495495 if (retry.getType() == Type.RETRY)
@@ -532,7 +532,7 @@
532532 case UNPREPARED:
533533 // Do not release connection yet, because we might reuse it to send the PREPARE message (see write() call below)
534534 assert err.infos instanceof MD5Digest;
535- MD5Digest id = (MD5Digest)err.infos;
535+ MD5Digest id = (MD5Digest) err.infos;
536536 PreparedStatement toPrepare = manager.cluster.manager.preparedQueries.get(id);
537537 if (toPrepare == null) {
538538 // This shouldn't happen
@@ -552,12 +552,12 @@
552552 // that's shared with other requests).
553553 connection.release();
554554 throw new IllegalStateException(String.format("Statement was prepared on keyspace %s, can't execute it on %s (%s)",
555- toPrepare.getQueryKeyspace(), connection.keyspace(), toPrepare.getQueryString()));
555+ toPrepare.getQueryKeyspace(), connection.keyspace(), toPrepare.getQueryString()));
556556 }
557557
558558 logger.info("Query {} is not prepared on {}, preparing before retrying executing. "
559- + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems",
560- toPrepare.getQueryString(), connection.address);
559+ + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems",
560+ toPrepare.getQueryString(), connection.address);
561561
562562 write(connection, prepareAndRetry(toPrepare.getQueryString()));
563563 // we're done for now, the prepareAndRetry callback will handle the rest
@@ -625,9 +625,9 @@
625625 public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
626626 QueryState queryState = queryStateRef.get();
627627 if (!queryState.isInProgressAt(retryCount) ||
628- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
628+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
629629 logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
630- retryCount, queryState, queryStateRef.get());
630+ retryCount, queryState, queryStateRef.get());
631631 return;
632632 }
633633
@@ -636,7 +636,7 @@
636636 // TODO should we check the response ?
637637 switch (response.type) {
638638 case RESULT:
639- if (((Responses.Result)response).kind == Responses.Result.Kind.PREPARED) {
639+ if (((Responses.Result) response).kind == Responses.Result.Kind.PREPARED) {
640640 logger.debug("Scheduling retry now that query is prepared");
641641 retry(true, null);
642642 } else {
@@ -666,9 +666,9 @@
666666 public boolean onTimeout(Connection connection, long latency, int retryCount) {
667667 QueryState queryState = queryStateRef.get();
668668 if (!queryState.isInProgressAt(retryCount) ||
669- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
669+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
670670 logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
671- retryCount, queryState, queryStateRef.get());
671+ retryCount, queryState, queryStateRef.get());
672672 return false;
673673 }
674674 connection.release();
@@ -683,9 +683,9 @@
683683 public void onException(Connection connection, Exception exception, long latency, int retryCount) {
684684 QueryState queryState = queryStateRef.get();
685685 if (!queryState.isInProgressAt(retryCount) ||
686- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
686+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
687687 logger.debug("onException triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
688- retryCount, queryState, queryStateRef.get());
688+ retryCount, queryState, queryStateRef.get());
689689 return;
690690 }
691691
@@ -696,7 +696,7 @@
696696 if (exception instanceof ConnectionException) {
697697 if (metricsEnabled())
698698 metrics().getErrorMetrics().getConnectionErrors().inc();
699- ConnectionException ce = (ConnectionException)exception;
699+ ConnectionException ce = (ConnectionException) exception;
700700 logError(ce.address, ce);
701701 retry(false, null);
702702 return;
@@ -715,9 +715,9 @@
715715 public boolean onTimeout(Connection connection, long latency, int retryCount) {
716716 QueryState queryState = queryStateRef.get();
717717 if (!queryState.isInProgressAt(retryCount) ||
718- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
718+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
719719 logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
720- retryCount, queryState, queryStateRef.get());
720+ retryCount, queryState, queryStateRef.get());
721721 return false;
722722 }
723723
@@ -754,7 +754,7 @@
754754
755755 /**
756756 * The state of a SpeculativeExecution.
757- *
757+ * <p/>
758758 * This is used to prevent races between request completion (either success or error) and timeout.
759759 * A retry is in progress once we have written the request to the connection and until we get back a response (see onSet
760760 * or onException) or a timeout (see onTimeout).
@@ -808,7 +808,9 @@
808808 this.iterator = iterator;
809809 }
810810
811- /** @return null if there are no more hosts */
811+ /**
812+ * @return null if there are no more hosts
813+ */
812814 synchronized Host next() {
813815 return iterator.hasNext() ? iterator.next() : null;
814816 }
modified driver-core/src/main/java/com/datastax/driver/core/Requests.java +35 −30
@@ -15,18 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.collect.ImmutableMap;
19+import io.netty.buffer.ByteBuf;
20+
1821 import java.nio.ByteBuffer;
1922 import java.util.Collections;
2023 import java.util.EnumSet;
2124 import java.util.List;
2225 import java.util.Map;
2326
24-import com.google.common.collect.ImmutableMap;
25-import io.netty.buffer.ByteBuf;
26-
2727 class Requests {
2828
29- private Requests() {}
29+ private Requests() {
30+ }
3031
3132 public static class Startup extends Message.Request {
3233 private static final String CQL_VERSION_OPTION = "CQL_VERSION";
@@ -88,9 +89,9 @@
8889
8990 public static class Options extends Message.Request {
9091
91- public static final Message.Coder<Options> coder = new Message.Coder<Options>()
92- {
93- public void encode(Options msg, ByteBuf dest, ProtocolVersion version) {}
92+ public static final Message.Coder<Options> coder = new Message.Coder<Options>() {
93+ public void encode(Options msg, ByteBuf dest, ProtocolVersion version) {
94+ }
9495
9596 public int encodedSize(Options msg, ProtocolVersion version) {
9697 return 0;
@@ -117,7 +118,7 @@
117118
118119 public int encodedSize(Query msg, ProtocolVersion version) {
119120 return CBUtil.sizeOfLongString(msg.query)
120- + msg.options.encodedSize(version);
121+ + msg.options.encodedSize(version);
121122 }
122123 };
123124
@@ -160,7 +161,7 @@
160161
161162 public int encodedSize(Execute msg, ProtocolVersion version) {
162163 return CBUtil.sizeOfBytes(msg.statementId.bytes)
163- + msg.options.encodedSize(version);
164+ + msg.options.encodedSize(version);
164165 }
165166 };
166167
@@ -202,8 +203,7 @@
202203 public static EnumSet<QueryFlag> deserialize(int flags) {
203204 EnumSet<QueryFlag> set = EnumSet.noneOf(QueryFlag.class);
204205 QueryFlag[] values = QueryFlag.values();
205- for (int n = 0; n < values.length; n++)
206- {
206+ for (int n = 0; n < values.length; n++) {
207207 if ((flags & (1 << n)) != 0)
208208 set.add(values[n]);
209209 }
@@ -221,12 +221,12 @@
221221 public static class QueryProtocolOptions {
222222
223223 public static final QueryProtocolOptions DEFAULT = new QueryProtocolOptions(ConsistencyLevel.ONE,
224- Collections.<ByteBuffer>emptyList(),
225- false,
226- -1,
227- null,
228- ConsistencyLevel.SERIAL,
229- Long.MIN_VALUE);
224+ Collections.<ByteBuffer>emptyList(),
225+ false,
226+ -1,
227+ null,
228+ ConsistencyLevel.SERIAL,
229+ Long.MIN_VALUE);
230230
231231 private final EnumSet<QueryFlag> flags = EnumSet.noneOf(QueryFlag.class);
232232 public final ConsistencyLevel consistency;
@@ -282,7 +282,7 @@
282282 case V2:
283283 case V3:
284284 CBUtil.writeConsistencyLevel(consistency, dest);
285- dest.writeByte((byte)QueryFlag.serialize(flags));
285+ dest.writeByte((byte) QueryFlag.serialize(flags));
286286 if (flags.contains(QueryFlag.VALUES))
287287 CBUtil.writeValueList(values, dest);
288288 if (flags.contains(QueryFlag.PAGE_SIZE))
@@ -303,7 +303,7 @@
303303 switch (version) {
304304 case V1:
305305 return CBUtil.sizeOfValueList(values)
306- + CBUtil.sizeOfConsistencyLevel(consistency);
306+ + CBUtil.sizeOfConsistencyLevel(consistency);
307307 case V2:
308308 case V3:
309309 int size = 0;
@@ -343,11 +343,11 @@
343343
344344 for (int i = 0; i < queries; i++) {
345345 Object q = msg.queryOrIdList.get(i);
346- dest.writeByte((byte)(q instanceof String ? 0 : 1));
346+ dest.writeByte((byte) (q instanceof String ? 0 : 1));
347347 if (q instanceof String)
348- CBUtil.writeLongString((String)q, dest);
348+ CBUtil.writeLongString((String) q, dest);
349349 else
350- CBUtil.writeBytes(((MD5Digest)q).bytes, dest);
350+ CBUtil.writeBytes(((MD5Digest) q).bytes, dest);
351351
352352 CBUtil.writeValueList(msg.values.get(i), dest);
353353 }
@@ -360,8 +360,8 @@
360360 for (int i = 0; i < msg.queryOrIdList.size(); i++) {
361361 Object q = msg.queryOrIdList.get(i);
362362 size += 1 + (q instanceof String
363- ? CBUtil.sizeOfLongString((String)q)
364- : CBUtil.sizeOfBytes(((MD5Digest)q).bytes));
363+ ? CBUtil.sizeOfLongString((String) q)
364+ : CBUtil.sizeOfBytes(((MD5Digest) q).bytes));
365365
366366 size += CBUtil.sizeOfValueList(msg.values.get(i));
367367 }
@@ -371,10 +371,14 @@
371371
372372 private byte fromType(BatchStatement.Type type) {
373373 switch (type) {
374- case LOGGED: return 0;
375- case UNLOGGED: return 1;
376- case COUNTER: return 2;
377- default: throw new AssertionError();
374+ case LOGGED:
375+ return 0;
376+ case UNLOGGED:
377+ return 1;
378+ case COUNTER:
379+ return 2;
380+ default:
381+ throw new AssertionError();
378382 }
379383 }
380384 };
@@ -401,6 +405,7 @@
401405 Request copy(ConsistencyLevel newConsistencyLevel) {
402406 return new Batch(type, queryOrIdList, values, options.copy(newConsistencyLevel), isTracingRequested());
403407 }
408+
404409 @Override
405410 public String toString() {
406411 StringBuilder sb = new StringBuilder();
@@ -442,7 +447,7 @@
442447 break;
443448 case V3:
444449 CBUtil.writeConsistencyLevel(consistency, dest);
445- dest.writeByte((byte)QueryFlag.serialize(flags));
450+ dest.writeByte((byte) QueryFlag.serialize(flags));
446451 if (flags.contains(QueryFlag.SERIAL_CONSISTENCY))
447452 CBUtil.writeConsistencyLevel(serialConsistency, dest);
448453 if (flags.contains(QueryFlag.DEFAULT_TIMESTAMP))
@@ -474,7 +479,7 @@
474479 @Override
475480 public String toString() {
476481 return String.format("[cl=%s, serialCl=%s, defaultTs=%d]",
477- consistency, serialConsistency, defaultTimestamp);
482+ consistency, serialConsistency, defaultTimestamp);
478483 }
479484 }
480485
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +47 −32
@@ -15,22 +15,22 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.nio.ByteBuffer;
20-import java.util.*;
21-
22-import io.netty.buffer.ByteBuf;
23-
2418 import com.datastax.driver.core.Responses.Result.Rows.Metadata;
2519 import com.datastax.driver.core.exceptions.*;
2620 import com.datastax.driver.core.utils.Bytes;
21+import io.netty.buffer.ByteBuf;
22+
23+import java.net.InetSocketAddress;
24+import java.nio.ByteBuffer;
25+import java.util.*;
2726
2827 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
2928 import static com.datastax.driver.core.SchemaElement.TABLE;
3029
3130 class Responses {
3231
33- private Responses() {}
32+ private Responses() {
33+ }
3434
3535 public static class Error extends Message.Response {
3636
@@ -88,22 +88,38 @@
8888
8989 public DriverException asException(InetSocketAddress host) {
9090 switch (code) {
91- case SERVER_ERROR: return new ServerError(host, message);
92- case PROTOCOL_ERROR: return new ProtocolError(host, message);
93- case BAD_CREDENTIALS: return new AuthenticationException(host, message);
94- case UNAVAILABLE: return ((UnavailableException)infos).copy(host); // We copy to have a nice stack trace
95- case OVERLOADED: return new OverloadedException(host, message);
96- case IS_BOOTSTRAPPING: return new BootstrappingException(host, message);
97- case TRUNCATE_ERROR: return new TruncateException(host, message);
98- case WRITE_TIMEOUT: return ((WriteTimeoutException)infos).copy(host);
99- case READ_TIMEOUT: return ((ReadTimeoutException)infos).copy(host);
100- case SYNTAX_ERROR: return new SyntaxError(host, message);
101- case UNAUTHORIZED: return new UnauthorizedException(host, message);
102- case INVALID: return new InvalidQueryException(host, message);
103- case CONFIG_ERROR: return new InvalidConfigurationInQueryException(host, message);
104- case ALREADY_EXISTS: return ((AlreadyExistsException)infos).copy(host);
105- case UNPREPARED: return new UnpreparedException(host, message);
106- default: return new DriverInternalError(String.format("Unknown protocol error code %s returned by %s. The error message was: %s", code, host, message));
91+ case SERVER_ERROR:
92+ return new ServerError(host, message);
93+ case PROTOCOL_ERROR:
94+ return new ProtocolError(host, message);
95+ case BAD_CREDENTIALS:
96+ return new AuthenticationException(host, message);
97+ case UNAVAILABLE:
98+ return ((UnavailableException) infos).copy(host); // We copy to have a nice stack trace
99+ case OVERLOADED:
100+ return new OverloadedException(host, message);
101+ case IS_BOOTSTRAPPING:
102+ return new BootstrappingException(host, message);
103+ case TRUNCATE_ERROR:
104+ return new TruncateException(host, message);
105+ case WRITE_TIMEOUT:
106+ return ((WriteTimeoutException) infos).copy(host);
107+ case READ_TIMEOUT:
108+ return ((ReadTimeoutException) infos).copy(host);
109+ case SYNTAX_ERROR:
110+ return new SyntaxError(host, message);
111+ case UNAUTHORIZED:
112+ return new UnauthorizedException(host, message);
113+ case INVALID:
114+ return new InvalidQueryException(host, message);
115+ case CONFIG_ERROR:
116+ return new InvalidConfigurationInQueryException(host, message);
117+ case ALREADY_EXISTS:
118+ return ((AlreadyExistsException) infos).copy(host);
119+ case UNPREPARED:
120+ return new UnpreparedException(host, message);
121+ default:
122+ return new DriverInternalError(String.format("Unknown protocol error code %s returned by %s. The error message was: %s", code, host, message));
107123 }
108124 }
109125
@@ -201,16 +217,17 @@
201217 };
202218
203219 public enum Kind {
204- VOID (1, Void.subcodec),
205- ROWS (2, Rows.subcodec),
206- SET_KEYSPACE (3, SetKeyspace.subcodec),
207- PREPARED (4, Prepared.subcodec),
220+ VOID(1, Void.subcodec),
221+ ROWS(2, Rows.subcodec),
222+ SET_KEYSPACE(3, SetKeyspace.subcodec),
223+ PREPARED(4, Prepared.subcodec),
208224 SCHEMA_CHANGE(5, SchemaChange.subcodec);
209225
210226 private final int id;
211227 final Message.Decoder<Result> subDecoder;
212228
213229 private static final Kind[] ids;
230+
214231 static {
215232 int maxId = -1;
216233 for (Kind k : Kind.values())
@@ -286,8 +303,7 @@
286303
287304 public static class Metadata {
288305
289- private static enum Flag
290- {
306+ private static enum Flag {
291307 // The order of that enum matters!!
292308 GLOBAL_TABLES_SPEC,
293309 HAS_MORE_PAGES,
@@ -474,7 +490,7 @@
474490
475491 public static class SchemaChange extends Result {
476492
477- public enum Change { CREATED, UPDATED, DROPPED }
493+ public enum Change {CREATED, UPDATED, DROPPED}
478494
479495 public final Change change;
480496 public final SchemaElement targetType;
@@ -482,8 +498,7 @@
482498 public final String targetName;
483499
484500 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
485- public Result decode(ByteBuf body, ProtocolVersion version)
486- {
501+ public Result decode(ByteBuf body, ProtocolVersion version) {
487502 // Note: the CREATE KEYSPACE/TABLE/TYPE SCHEMA_CHANGE response is different from the SCHEMA_CHANGE EVENT type
488503 Change change;
489504 SchemaElement target;
modified driver-core/src/main/java/com/datastax/driver/core/ResultSet.java +18 −19
@@ -16,14 +16,14 @@
1616 package com.datastax.driver.core;
1717
1818
19+import com.google.common.util.concurrent.ListenableFuture;
20+
1921 import java.util.Iterator;
2022 import java.util.List;
2123
22-import com.google.common.util.concurrent.ListenableFuture;
23-
2424 /**
2525 * The result of a query.
26- * <p>
26+ * <p/>
2727 * The retrieval of the rows of a ResultSet is generally paged (a first page
2828 * of result is fetched and the next one is only fetched once all the results
2929 * of the first one has been consumed). The size of the pages can be configured
@@ -36,7 +36,7 @@
3636 * through {@link Cluster.Builder#withProtocolVersion}). If the protocol version 1
3737 * is in use, a ResultSet is always fetched in it's entirely and it's up to the
3838 * client to make sure that no query can yield ResultSet that won't hold in memory.
39- * <p>
39+ * <p/>
4040 * Note that this class is not thread-safe.
4141 */
4242 public interface ResultSet extends Iterable<Row> {
@@ -65,7 +65,7 @@
6565
6666 /**
6767 * Returns all the remaining rows in this ResultSet as a list.
68- * <p>
68+ * <p/>
6969 * Note that, contrary to {@code iterator()} or successive calls to
7070 * {@code one()}, this method forces fetching the full content of the ResultSet
7171 * at once, holding it all in memory in particular. It is thus recommended
@@ -80,11 +80,11 @@
8080
8181 /**
8282 * Returns an iterator over the rows contained in this ResultSet.
83- *
83+ * <p/>
8484 * The {@link Iterator#next} method is equivalent to calling {@link #one}.
8585 * So this iterator will consume results from this ResultSet and after a
8686 * full iteration, the ResultSet will be empty.
87- *
87+ * <p/>
8888 * The returned iterator does not support the {@link Iterator#remove} method.
8989 *
9090 * @return an iterator that will consume and return the remaining rows of
@@ -106,7 +106,7 @@
106106 /**
107107 * Whether all results from this result set have been fetched from the
108108 * database.
109- * <p>
109+ * <p/>
110110 * Note that if {@code isFullyFetched()}, then {@link #getAvailableWithoutFetching}
111111 * will return how many rows remain in the result set before exhaustion. But
112112 * please note that {@code !isFullyFetched()} never guarantees that the result set
@@ -118,12 +118,12 @@
118118
119119 /**
120120 * Force fetching the next page of results for this result set, if any.
121- * <p>
121+ * <p/>
122122 * This method is entirely optional. It will be called automatically while
123123 * the result set is consumed (through {@link #one}, {@link #all} or iteration)
124124 * when needed (i.e. when {@code getAvailableWithoutFetching() == 0} and
125125 * {@code isFullyFetched() == false}).
126- * <p>
126+ * <p/>
127127 * You can however call this method manually to force the fetching of the
128128 * next page of results. This can allow to prefetch results before they are
129129 * strictly needed. For instance, if you want to prefetch the next page of
@@ -143,7 +143,7 @@
143143 * fetchMoreResults} will not block the processing of the 100 currently available
144144 * rows (but {@code iter.hasNext()} will block once those rows have been processed
145145 * until the fetch query returns, if it hasn't yet).
146- * <p>
146+ * <p/>
147147 * Only one page of results (for a given result set) can be
148148 * fetched at any given time. If this method is called twice and the query
149149 * triggered by the first call has not returned yet when the second one is
@@ -160,12 +160,12 @@
160160
161161 /**
162162 * Returns information on the execution of the last query made for this ResultSet.
163- * <p>
163+ * <p/>
164164 * Note that in most cases, a ResultSet is fetched with only one query, but large
165165 * result sets can be paged and thus be retrieved by multiple queries. In that
166166 * case this method return the {@code ExecutionInfo} for the last query
167167 * performed. To retrieve the information for all queries, use {@link #getAllExecutionInfo}.
168- * <p>
168+ * <p/>
169169 * The returned object includes basic information such as the queried hosts,
170170 * but also the Cassandra query trace if tracing was enabled for the query.
171171 *
@@ -176,7 +176,7 @@
176176 /**
177177 * Return the execution information for all queries made to retrieve this
178178 * ResultSet.
179- * <p>
179+ * <p/>
180180 * Unless the ResultSet is large enough to get paged underneath, the returned
181181 * list will be singleton. If paging has been used however, the returned list
182182 * contains the {@code ExecutionInfo} for all the queries done to obtain this
@@ -189,26 +189,25 @@
189189 /**
190190 * If the query that produced this ResultSet was a conditional update,
191191 * return whether it was successfully applied.
192- * <p>
192+ * <p/>
193193 * This is equivalent to calling:
194- *
194+ * <p/>
195195 * <pre>
196196 * rs.one().getBool("[applied]");
197197 * </pre>
198- * <p>
198+ * <p/>
199199 * For consistency, this method always returns {@code true} for
200200 * non-conditional queries (although there is no reason to call the method
201201 * in that case). This is also the case for conditional DDL statements
202202 * ({@code CREATE KEYSPACE... IF NOT EXISTS}, {@code CREATE TABLE... IF NOT EXISTS}),
203203 * for which Cassandra doesn't return an {@code [applied]} column.
204- * <p>
204+ * <p/>
205205 * Note that, for versions of Cassandra strictly lower than 2.0.9 and 2.1.0-rc2,
206206 * a server-side bug (CASSANDRA-7337) causes this method to always return
207207 * {@code true} for batches containing conditional queries.
208208 *
209209 * @return if the query was a conditional update, whether it was applied.
210210 * {@code true} for other types of queries.
211- *
212211 * @see <a href="https://issues.apache.org/jira/browse/CASSANDRA-7337">CASSANDRA-7337</a>
213212 */
214213 public boolean wasApplied();
modified driver-core/src/main/java/com/datastax/driver/core/ResultSetFuture.java +32 −35
@@ -15,18 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.TimeUnit;
19-import java.util.concurrent.TimeoutException;
20-
21-import com.google.common.util.concurrent.ListenableFuture;
22-
2318 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2419 import com.datastax.driver.core.exceptions.QueryExecutionException;
2520 import com.datastax.driver.core.exceptions.QueryValidationException;
21+import com.google.common.util.concurrent.ListenableFuture;
22+
23+import java.util.concurrent.TimeUnit;
24+import java.util.concurrent.TimeoutException;
2625
2726 /**
2827 * A future on a {@link ResultSet}.
29- *
28+ * <p/>
3029 * Note that this class implements <a href="http://code.google.com/p/guava-libraries/">Guava</a>'s {@code
3130 * ListenableFuture} and can so be used with Guava's future utilities.
3231 */
@@ -34,67 +33,65 @@
3433
3534 /**
3635 * Waits for the query to return and return its result.
37- *
36+ * <p/>
3837 * This method is usually more convenient than {@link #get} because it:
3938 * <ul>
40- * <li>Waits for the result uninterruptibly, and so doesn't throw
41- * {@link InterruptedException}.</li>
42- * <li>Returns meaningful exceptions, instead of having to deal
43- * with ExecutionException.</li>
39+ * <li>Waits for the result uninterruptibly, and so doesn't throw
40+ * {@link InterruptedException}.</li>
41+ * <li>Returns meaningful exceptions, instead of having to deal
42+ * with ExecutionException.</li>
4443 * </ul>
4544 * As such, it is the preferred way to get the future result.
4645 *
4746 * @return the query result set.
48- *
4947 * @throws NoHostAvailableException if no host in the cluster can be
50- * contacted successfully to execute this query.
51- * @throws QueryExecutionException if the query triggered an execution
52- * exception, that is an exception thrown by Cassandra when it cannot execute
53- * the query with the requested consistency level successfully.
48+ * contacted successfully to execute this query.
49+ * @throws QueryExecutionException if the query triggered an execution
50+ * exception, that is an exception thrown by Cassandra when it cannot execute
51+ * the query with the requested consistency level successfully.
5452 * @throws QueryValidationException if the query is invalid (syntax error,
55- * unauthorized or any other validation problem).
53+ * unauthorized or any other validation problem).
5654 */
5755 public ResultSet getUninterruptibly();
5856
5957 /**
6058 * Waits for the provided time for the query to return and return its
6159 * result if available.
62- *
60+ * <p/>
6361 * This method is usually more convenient than {@link #get} because it:
6462 * <ul>
65- * <li>Waits for the result uninterruptibly, and so doesn't throw
66- * {@link InterruptedException}.</li>
67- * <li>Returns meaningful exceptions, instead of having to deal
68- * with ExecutionException.</li>
63+ * <li>Waits for the result uninterruptibly, and so doesn't throw
64+ * {@link InterruptedException}.</li>
65+ * <li>Returns meaningful exceptions, instead of having to deal
66+ * with ExecutionException.</li>
6967 * </ul>
7068 * As such, it is the preferred way to get the future result.
7169 *
7270 * @param timeout the time to wait for the query to return.
73- * @param unit the unit for {@code timeout}.
71+ * @param unit the unit for {@code timeout}.
7472 * @return the query result set.
75- *
7673 * @throws NoHostAvailableException if no host in the cluster can be
77- * contacted successfully to execute this query.
78- * @throws QueryExecutionException if the query triggered an execution
79- * exception, that is an exception thrown by Cassandra when it cannot execute
80- * the query with the requested consistency level successfully.
74+ * contacted successfully to execute this query.
75+ * @throws QueryExecutionException if the query triggered an execution
76+ * exception, that is an exception thrown by Cassandra when it cannot execute
77+ * the query with the requested consistency level successfully.
8178 * @throws QueryValidationException if the query if invalid (syntax error,
82- * unauthorized or any other validation problem).
83- * @throws TimeoutException if the wait timed out (Note that this is
84- * different from a Cassandra timeout, which is a {@code
85- * QueryExecutionException}).
79+ * unauthorized or any other validation problem).
80+ * @throws TimeoutException if the wait timed out (Note that this is
81+ * different from a Cassandra timeout, which is a {@code
82+ * QueryExecutionException}).
8683 */
8784 public ResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException;
8885
8986 /**
9087 * Attempts to cancel the execution of the request corresponding to this
9188 * future. This attempt will fail if the request has already returned.
92- * <p>
89+ * <p/>
9390 * Please note that this only cancel the request driver side, but nothing
9491 * is done to interrupt the execution of the request Cassandra side (and that even
9592 * if {@code mayInterruptIfRunning} is true) since Cassandra does not
9693 * support such interruption.
97- * <p>
94+ * <p/>
9895 * This method can be used to ensure no more work is performed driver side
9996 * (which, while it doesn't include stopping a request already submitted
10097 * to a Cassandra node, may include not retrying another Cassandra host on
@@ -114,7 +111,7 @@
114111 * </pre>
115112 *
116113 * @param mayInterruptIfRunning the value of this parameter is currently
117- * ignored.
114+ * ignored.
118115 * @return {@code false} if the future could not be cancelled (it has already
119116 * completed normally); {@code true} otherwise.
120117 */
modified driver-core/src/main/java/com/datastax/driver/core/Row.java +94 −131
@@ -15,17 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+
1820 import java.math.BigDecimal;
1921 import java.math.BigInteger;
2022 import java.net.InetAddress;
2123 import java.nio.ByteBuffer;
2224 import java.util.*;
2325
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
25-
2626 /**
2727 * A CQL Row returned in a {@link ResultSet}.
28- * <p>
28+ * <p/>
2929 * The values of a CQL Row can be retrieve by either index (index starts at 0)
3030 * or name. When setting them by name, names follow the case insensitivity
3131 * rules explained in {@link ColumnDefinitions}.
@@ -45,7 +45,6 @@
4545 *
4646 * @param i the index ({@code 0 <= i < size()}) of the column to check.
4747 * @return whether the {@code i}th value of this row is NULL.
48- *
4948 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
5049 */
5150 @Override
@@ -56,9 +55,8 @@
5655 *
5756 * @param name the name of the column to check.
5857 * @return whether the value of column {@code name} is NULL.
59- *
6058 * @throws IllegalArgumentException if {@code name} is not part of the
61- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
59+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
6260 */
6361 @Override
6462 public boolean isNull(String name);
@@ -69,9 +67,8 @@
6967 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
7068 * @return the boolean value of the {@code i}th column in this row. If the
7169 * value is NULL, {@code false} is returned.
72- *
7370 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
74- * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
71+ * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
7572 */
7673 @Override
7774 public boolean getBool(int i);
@@ -82,10 +79,9 @@
8279 * @param name the name of the column to retrieve.
8380 * @return the boolean value of column {@code name}. If the value is NULL,
8481 * {@code false} is returned.
85- *
8682 * @throws IllegalArgumentException if {@code name} is not part of the
87- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
88- * @throws InvalidTypeException if column {@code name} is not of type BOOLEAN.
83+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
84+ * @throws InvalidTypeException if column {@code name} is not of type BOOLEAN.
8985 */
9086 @Override
9187 public boolean getBool(String name);
@@ -96,9 +92,8 @@
9692 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
9793 * @return the value of the {@code i}th column in this row as an integer. If the
9894 * value is NULL, {@code 0} is returned.
99- *
10095 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
101- * @throws InvalidTypeException if column {@code i} is not of type INT.
96+ * @throws InvalidTypeException if column {@code i} is not of type INT.
10297 */
10398 @Override
10499 public int getInt(int i);
@@ -109,10 +104,9 @@
109104 * @param name the name of the column to retrieve.
110105 * @return the value of column {@code name} as an integer. If the value is NULL,
111106 * {@code 0} is returned.
112- *
113107 * @throws IllegalArgumentException if {@code name} is not part of the
114- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
115- * @throws InvalidTypeException if column {@code name} is not of type INT.
108+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
109+ * @throws InvalidTypeException if column {@code name} is not of type INT.
116110 */
117111 @Override
118112 public int getInt(String name);
@@ -123,9 +117,8 @@
123117 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
124118 * @return the value of the {@code i}th column in this row as a long. If the
125119 * value is NULL, {@code 0L} is returned.
126- *
127120 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
128- * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
121+ * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
129122 */
130123 @Override
131124 public long getLong(int i);
@@ -136,10 +129,9 @@
136129 * @param name the name of the column to retrieve.
137130 * @return the value of column {@code name} as a long. If the value is NULL,
138131 * {@code 0L} is returned.
139- *
140132 * @throws IllegalArgumentException if {@code name} is not part of the
141- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
142- * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
133+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
134+ * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
143135 */
144136 @Override
145137 public long getLong(String name);
@@ -150,9 +142,8 @@
150142 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
151143 * @return the value of the {@code i}th column in this row as a data. If the
152144 * value is NULL, {@code null} is returned.
153- *
154145 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
155- * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
146+ * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
156147 */
157148 @Override
158149 public Date getDate(int i);
@@ -163,10 +154,9 @@
163154 * @param name the name of the column to retrieve.
164155 * @return the value of column {@code name} as a date. If the value is NULL,
165156 * {@code null} is returned.
166- *
167157 * @throws IllegalArgumentException if {@code name} is not part of the
168- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
169- * @throws InvalidTypeException if column {@code name} is not of type TIMESTAMP.
158+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
159+ * @throws InvalidTypeException if column {@code name} is not of type TIMESTAMP.
170160 */
171161 @Override
172162 public Date getDate(String name);
@@ -177,9 +167,8 @@
177167 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
178168 * @return the value of the {@code i}th column in this row as a float. If the
179169 * value is NULL, {@code 0.0f} is returned.
180- *
181170 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
182- * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
171+ * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
183172 */
184173 @Override
185174 public float getFloat(int i);
@@ -190,10 +179,9 @@
190179 * @param name the name of the column to retrieve.
191180 * @return the value of column {@code name} as a float. If the value is NULL,
192181 * {@code 0.0f} is returned.
193- *
194182 * @throws IllegalArgumentException if {@code name} is not part of the
195- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
196- * @throws InvalidTypeException if column {@code name} is not of type FLOAT.
183+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
184+ * @throws InvalidTypeException if column {@code name} is not of type FLOAT.
197185 */
198186 @Override
199187 public float getFloat(String name);
@@ -204,9 +192,8 @@
204192 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
205193 * @return the value of the {@code i}th column in this row as a double. If the
206194 * value is NULL, {@code 0.0} is returned.
207- *
208195 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
209- * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
196+ * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
210197 */
211198 @Override
212199 public double getDouble(int i);
@@ -217,17 +204,16 @@
217204 * @param name the name of the column to retrieve.
218205 * @return the value of column {@code name} as a double. If the value is NULL,
219206 * {@code 0.0} is returned.
220- *
221207 * @throws IllegalArgumentException if {@code name} is not part of the
222- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
223- * @throws InvalidTypeException if column {@code name} is not of type DOUBLE.
208+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
209+ * @throws InvalidTypeException if column {@code name} is not of type DOUBLE.
224210 */
225211 @Override
226212 public double getDouble(String name);
227213
228214 /**
229215 * Returns the {@code i}th value of this row as a ByteBuffer.
230- *
216+ * <p/>
231217 * Note: this method always return the bytes composing the value, even if
232218 * the column is not of type BLOB. That is, this method never throw an
233219 * InvalidTypeException. However, if the type is not BLOB, it is up to the
@@ -236,7 +222,6 @@
236222 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
237223 * @return the value of the {@code i}th column in this row as a ByteBuffer. If the
238224 * value is NULL, {@code null} is returned.
239- *
240225 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
241226 */
242227 @Override
@@ -244,7 +229,7 @@
244229
245230 /**
246231 * Returns the value of column {@code name} as a ByteBuffer.
247- *
232+ * <p/>
248233 * Note: this method always return the bytes composing the value, even if
249234 * the column is not of type BLOB. That is, this method never throw an
250235 * InvalidTypeException. However, if the type is not BLOB, it is up to the
@@ -253,42 +238,39 @@
253238 * @param name the name of the column to retrieve.
254239 * @return the value of column {@code name} as a ByteBuffer. If the value is NULL,
255240 * {@code null} is returned.
256- *
257241 * @throws IllegalArgumentException if {@code name} is not part of the
258- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
242+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
259243 */
260244 @Override
261245 public ByteBuffer getBytesUnsafe(String name);
262246
263247 /**
264248 * Returns the {@code i}th value of this row as a byte array.
265- * <p>
249+ * <p/>
266250 * Note that this method validate that the column is of type BLOB. If you want to retrieve
267251 * the bytes for any type of columns, use {@link #getBytesUnsafe(int)} instead.
268252 *
269253 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
270254 * @return the value of the {@code i}th column in this row as a byte array. If the
271255 * value is NULL, {@code null} is returned.
272- *
273256 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
274- * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
257+ * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
275258 */
276259 @Override
277260 public ByteBuffer getBytes(int i);
278261
279262 /**
280263 * Returns the value of column {@code name} as a byte array.
281- * <p>
264+ * <p/>
282265 * Note that this method validate that the column is of type BLOB. If you want to retrieve
283266 * the bytes for any type of columns, use {@link #getBytesUnsafe(String)} instead.
284267 *
285268 * @param name the name of the column to retrieve.
286269 * @return the value of column {@code name} as a byte array. If the value is NULL,
287270 * {@code null} is returned.
288- *
289271 * @throws IllegalArgumentException if {@code name} is not part of the
290- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
291- * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
272+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
273+ * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
292274 */
293275 @Override
294276 public ByteBuffer getBytes(String name);
@@ -299,10 +281,9 @@
299281 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
300282 * @return the value of the {@code i}th column in this row as a string. If the
301283 * value is NULL, {@code null} is returned.
302- *
303284 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
304- * @throws InvalidTypeException if column {@code i} type is none of:
305- * VARCHAR, TEXT or ASCII.
285+ * @throws InvalidTypeException if column {@code i} type is none of:
286+ * VARCHAR, TEXT or ASCII.
306287 */
307288 @Override
308289 public String getString(int i);
@@ -313,11 +294,10 @@
313294 * @param name the name of the column to retrieve.
314295 * @return the value of column {@code name} as a string. If the value is NULL,
315296 * {@code null} is returned.
316- *
317297 * @throws IllegalArgumentException if {@code name} is not part of the
318- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
319- * @throws InvalidTypeException if column {@code name} type is none of:
320- * VARCHAR, TEXT or ASCII.
298+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
299+ * @throws InvalidTypeException if column {@code name} type is none of:
300+ * VARCHAR, TEXT or ASCII.
321301 */
322302 @Override
323303 public String getString(String name);
@@ -328,9 +308,8 @@
328308 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
329309 * @return the value of the {@code i}th column in this row as a variable
330310 * length integer. If the value is NULL, {@code null} is returned.
331- *
332311 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
333- * @throws InvalidTypeException if column {@code i} is not of type VARINT.
312+ * @throws InvalidTypeException if column {@code i} is not of type VARINT.
334313 */
335314 @Override
336315 public BigInteger getVarint(int i);
@@ -341,10 +320,9 @@
341320 * @param name the name of the column to retrieve.
342321 * @return the value of column {@code name} as a variable length integer.
343322 * If the value is NULL, {@code null} is returned.
344- *
345323 * @throws IllegalArgumentException if {@code name} is not part of the
346- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
347- * @throws InvalidTypeException if column {@code name} is not of type VARINT.
324+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
325+ * @throws InvalidTypeException if column {@code name} is not of type VARINT.
348326 */
349327 @Override
350328 public BigInteger getVarint(String name);
@@ -355,9 +333,8 @@
355333 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
356334 * @return the value of the {@code i}th column in this row as a variable
357335 * length decimal. If the value is NULL, {@code null} is returned.
358- *
359336 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
360- * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
337+ * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
361338 */
362339 @Override
363340 public BigDecimal getDecimal(int i);
@@ -368,10 +345,9 @@
368345 * @param name the name of the column to retrieve.
369346 * @return the value of column {@code name} as a variable length decimal.
370347 * If the value is NULL, {@code null} is returned.
371- *
372348 * @throws IllegalArgumentException if {@code name} is not part of the
373- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
374- * @throws InvalidTypeException if column {@code name} is not of type DECIMAL.
349+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
350+ * @throws InvalidTypeException if column {@code name} is not of type DECIMAL.
375351 */
376352 @Override
377353 public BigDecimal getDecimal(String name);
@@ -382,10 +358,9 @@
382358 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
383359 * @return the value of the {@code i}th column in this row as a UUID.
384360 * If the value is NULL, {@code null} is returned.
385- *
386361 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
387- * @throws InvalidTypeException if column {@code i} is not of type UUID
388- * or TIMEUUID.
362+ * @throws InvalidTypeException if column {@code i} is not of type UUID
363+ * or TIMEUUID.
389364 */
390365 @Override
391366 public UUID getUUID(int i);
@@ -396,11 +371,10 @@
396371 * @param name the name of the column to retrieve.
397372 * @return the value of column {@code name} as a UUID.
398373 * If the value is NULL, {@code null} is returned.
399- *
400374 * @throws IllegalArgumentException if {@code name} is not part of the
401- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
402- * @throws InvalidTypeException if column {@code name} is not of type
403- * UUID or TIMEUUID.
375+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
376+ * @throws InvalidTypeException if column {@code name} is not of type
377+ * UUID or TIMEUUID.
404378 */
405379 @Override
406380 public UUID getUUID(String name);
@@ -411,9 +385,8 @@
411385 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
412386 * @return the value of the {@code i}th column in this row as an InetAddress.
413387 * If the value is NULL, {@code null} is returned.
414- *
415388 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
416- * @throws InvalidTypeException if column {@code i} is not of type INET.
389+ * @throws InvalidTypeException if column {@code i} is not of type INET.
417390 */
418391 @Override
419392 public InetAddress getInet(int i);
@@ -424,49 +397,46 @@
424397 * @param name the name of the column to retrieve.
425398 * @return the value of column {@code name} as an InetAddress.
426399 * If the value is NULL, {@code null} is returned.
427- *
428400 * @throws IllegalArgumentException if {@code name} is not part of the
429- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
430- * @throws InvalidTypeException if column {@code name} is not of type
431- * INET.
401+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
402+ * @throws InvalidTypeException if column {@code name} is not of type
403+ * INET.
432404 */
433405 @Override
434406 public InetAddress getInet(String name);
435407
436408 /**
437409 * Returns the {@code i}th value of this row as a {@link Token}.
438- * <p>
410+ * <p/>
439411 * {@link #getPartitionKeyToken()} should generally be preferred to this method (unless the
440412 * token column is aliased).
441413 *
442414 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
443415 * @return the value of the {@code i}th column in this row as an Token.
444- *
445416 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
446- * @throws InvalidTypeException if column {@code i} is not of the type of token values
447- * for this cluster (this depends on the configured partitioner).
417+ * @throws InvalidTypeException if column {@code i} is not of the type of token values
418+ * for this cluster (this depends on the configured partitioner).
448419 */
449420 public Token getToken(int i);
450421
451422 /**
452423 * Returns the value of column {@code name} as a {@link Token}.
453- * <p>
424+ * <p/>
454425 * {@link #getPartitionKeyToken()} should generally be preferred to this method (unless the
455426 * token column is aliased).
456427 *
457428 * @param name the name of the column to retrieve.
458429 * @return the value of column {@code name} as a Token.
459- *
460430 * @throws IllegalArgumentException if {@code name} is not part of the
461- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
462- * @throws InvalidTypeException if column {@code name} is not of the type of token values
463- * for this cluster (this depends on the configured partitioner).
431+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
432+ * @throws InvalidTypeException if column {@code name} is not of the type of token values
433+ * for this cluster (this depends on the configured partitioner).
464434 */
465435 public Token getToken(String name);
466436
467437 /**
468438 * Returns the value of the first column containing a {@link Token}.
469- * <p>
439+ * <p/>
470440 * This method is a shorthand for queries returning a single token in an unaliased
471441 * column. It will look for the first name matching {@code token(...)}:
472442 * <pre>
@@ -479,28 +449,26 @@
479449 * {@link #getToken(int)} or {@link #getToken(String)}.
480450 *
481451 * @return the value of column {@code name} as a Token.
482- *
483452 * @throws IllegalStateException if no column named {@code token(...)} exists in this
484- * ResultSet.
485- * @throws InvalidTypeException if the first column named {@code token(...)} is not of
486- * the type of token values for this cluster (this depends on the configured partitioner).
453+ * ResultSet.
454+ * @throws InvalidTypeException if the first column named {@code token(...)} is not of
455+ * the type of token values for this cluster (this depends on the configured partitioner).
487456 */
488457 public Token getPartitionKeyToken();
489458
490459 /**
491460 * Returns the {@code i}th value of this row as a list.
492461 *
493- * @param <T> the type of the elements of the list to return.
494- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
462+ * @param <T> the type of the elements of the list to return.
463+ * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
495464 * @param elementsClass the class for the elements of the list to retrieve.
496465 * @return the value of the {@code i}th column in this row as a list of
497466 * {@code elementsClass} objects. If the value is NULL, an empty list is
498467 * returned (note that Cassandra makes no difference between an empty list
499468 * and column of type list that is not set). The returned list is immutable.
500- *
501469 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
502- * @throws InvalidTypeException if column {@code i} is not a list or if its
503- * elements are not of class {@code elementsClass}.
470+ * @throws InvalidTypeException if column {@code i} is not a list or if its
471+ * elements are not of class {@code elementsClass}.
504472 */
505473 @Override
506474 public <T> List<T> getList(int i, Class<T> elementsClass);
@@ -508,18 +476,17 @@
508476 /**
509477 * Returns the value of column {@code name} as a list.
510478 *
511- * @param <T> the type of the elements of the list to return.
512- * @param name the name of the column to retrieve.
479+ * @param <T> the type of the elements of the list to return.
480+ * @param name the name of the column to retrieve.
513481 * @param elementsClass the class for the elements of the list to retrieve.
514482 * @return the value of the {@code i}th column in this row as a list of
515483 * {@code elementsClass} objects. If the value is NULL, an empty list is
516484 * returned (note that Cassandra makes no difference between an empty list
517485 * and column of type list that is not set). The returned list is immutable.
518- *
519486 * @throws IllegalArgumentException if {@code name} is not part of the
520- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
521- * @throws InvalidTypeException if column {@code name} is not a list or if its
522- * elements are not of class {@code elementsClass}.
487+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
488+ * @throws InvalidTypeException if column {@code name} is not a list or if its
489+ * elements are not of class {@code elementsClass}.
523490 */
524491 @Override
525492 public <T> List<T> getList(String name, Class<T> elementsClass);
@@ -527,17 +494,16 @@
527494 /**
528495 * Returns the {@code i}th value of this row as a set.
529496 *
530- * @param <T> the type of the elements of the set to return.
531- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
497+ * @param <T> the type of the elements of the set to return.
498+ * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
532499 * @param elementsClass the class for the elements of the set to retrieve.
533500 * @return the value of the {@code i}th column in this row as a set of
534501 * {@code elementsClass} objects. If the value is NULL, an empty set is
535502 * returned (note that Cassandra makes no difference between an empty set
536503 * and column of type set that is not set). The returned set is immutable.
537- *
538504 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
539- * @throws InvalidTypeException if column {@code i} is not a set or if its
540- * elements are not of class {@code elementsClass}.
505+ * @throws InvalidTypeException if column {@code i} is not a set or if its
506+ * elements are not of class {@code elementsClass}.
541507 */
542508 @Override
543509 public <T> Set<T> getSet(int i, Class<T> elementsClass);
@@ -545,18 +511,17 @@
545511 /**
546512 * Returns the value of column {@code name} as a set.
547513 *
548- * @param <T> the type of the elements of the set to return.
549- * @param name the name of the column to retrieve.
514+ * @param <T> the type of the elements of the set to return.
515+ * @param name the name of the column to retrieve.
550516 * @param elementsClass the class for the elements of the set to retrieve.
551517 * @return the value of the {@code i}th column in this row as a set of
552518 * {@code elementsClass} objects. If the value is NULL, an empty set is
553519 * returned (note that Cassandra makes no difference between an empty set
554520 * and column of type set that is not set). The returned set is immutable.
555- *
556521 * @throws IllegalArgumentException if {@code name} is not part of the
557- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
558- * @throws InvalidTypeException if column {@code name} is not a set or if its
559- * elements are not of class {@code elementsClass}.
522+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
523+ * @throws InvalidTypeException if column {@code name} is not a set or if its
524+ * elements are not of class {@code elementsClass}.
560525 */
561526 @Override
562527 public <T> Set<T> getSet(String name, Class<T> elementsClass);
@@ -564,21 +529,20 @@
564529 /**
565530 * Returns the {@code i}th value of this row as a map.
566531 *
567- * @param <K> the type of the keys of the map to return.
568- * @param <V> the type of the values of the map to return.
569- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
570- * @param keysClass the class for the keys of the map to retrieve.
532+ * @param <K> the type of the keys of the map to return.
533+ * @param <V> the type of the values of the map to return.
534+ * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
535+ * @param keysClass the class for the keys of the map to retrieve.
571536 * @param valuesClass the class for the values of the map to retrieve.
572537 * @return the value of the {@code i}th column in this row as a map of
573538 * {@code keysClass} to {@code valuesClass} objects. If the value is NULL,
574539 * an empty map is returned (note that Cassandra makes no difference
575540 * between an empty map and column of type map that is not set). The
576541 * returned map is immutable.
577- *
578542 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
579- * @throws InvalidTypeException if column {@code i} is not a map, if its
580- * keys are not of class {@code keysClass} or if its values are not of
581- * class {@code valuesClass}.
543+ * @throws InvalidTypeException if column {@code i} is not a map, if its
544+ * keys are not of class {@code keysClass} or if its values are not of
545+ * class {@code valuesClass}.
582546 */
583547 @Override
584548 public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass);
@@ -586,22 +550,21 @@
586550 /**
587551 * Returns the value of column {@code name} as a map.
588552 *
589- * @param <K> the type of the keys of the map to return.
590- * @param <V> the type of the values of the map to return.
591- * @param name the name of the column to retrieve.
592- * @param keysClass the class for the keys of the map to retrieve.
553+ * @param <K> the type of the keys of the map to return.
554+ * @param <V> the type of the values of the map to return.
555+ * @param name the name of the column to retrieve.
556+ * @param keysClass the class for the keys of the map to retrieve.
593557 * @param valuesClass the class for the values of the map to retrieve.
594558 * @return the value of the {@code i}th column in this row as a map of
595559 * {@code keysClass} to {@code valuesClass} objects. If the value is NULL,
596560 * an empty map is returned (note that Cassandra makes no difference
597561 * between an empty map and column of type map that is not set). The
598562 * returned map is immutable.
599- *
600563 * @throws IllegalArgumentException if {@code name} is not part of the
601- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
602- * @throws InvalidTypeException if column {@code name} is not a map, if its
603- * keys are not of class {@code keysClass} or if its values are not of
604- * class {@code valuesClass}.
564+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
565+ * @throws InvalidTypeException if column {@code name} is not a map, if its
566+ * keys are not of class {@code keysClass} or if its values are not of
567+ * class {@code valuesClass}.
605568 */
606569 @Override
607570 public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass);
modified driver-core/src/main/java/com/datastax/driver/core/SSLOptions.java +4 −5
@@ -16,7 +16,6 @@
1616 package com.datastax.driver.core;
1717
1818 import javax.net.ssl.SSLContext;
19-import java.security.KeyManagementException;
2019 import java.security.NoSuchAlgorithmException;
2120
2221 /**
@@ -27,19 +26,19 @@
2726 /**
2827 * The default SSL cipher suites.
2928 */
30- public static final String[] DEFAULT_SSL_CIPHER_SUITES = { "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA" };
29+ public static final String[] DEFAULT_SSL_CIPHER_SUITES = {"TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"};
3130
3231 final SSLContext context;
3332 final String[] cipherSuites;
3433
3534 /**
3635 * Creates default SSL options.
37- * <p>
36+ * <p/>
3837 * The resulting options will use the default JSSE options, and you can use the default
3938 * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization">JSSE System properties</a>
4039 * to customize it's behavior. This may in particular involve
4140 * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore">creating a simple keyStore and trustStore</a>.
42- * <p>
41+ * <p/>
4342 * The cipher suites used by this default instance are the one defined by
4443 * {@code DEFAULT_SSL_CIPHER_SUITES} and match the default cipher suites
4544 * supported by Cassandra server side.
@@ -51,7 +50,7 @@
5150 /**
5251 * Creates SSL options that uses the provided SSL context and cipher suites.
5352 *
54- * @param context the {@code SSLContext} to use.
53+ * @param context the {@code SSLContext} to use.
5554 * @param cipherSuites the cipher suites to use.
5655 */
5756 public SSLOptions(SSLContext context, String[] cipherSuites) {
modified driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListener.java +5 −5
@@ -17,10 +17,10 @@
1717
1818 /**
1919 * Interface for objects that are interested in tracking schema change events in the cluster.
20- * <p>
20+ * <p/>
2121 * An implementation of this interface can be registered against a Cluster
2222 * object through the {@link com.datastax.driver.core.Cluster#register(SchemaChangeListener)} method.
23- * <p>
23+ * <p/>
2424 * Note that the methods defined by this interface will be executed by internal driver threads, and are
2525 * therefore expected to have short execution times. If you need to perform long computations or blocking
2626 * calls in response to schema change events, it is strongly recommended to schedule them asynchronously
@@ -45,7 +45,7 @@
4545 /**
4646 * Called when a keyspace has changed.
4747 *
48- * @param current the keyspace that has changed, in its current form (after the change).
48+ * @param current the keyspace that has changed, in its current form (after the change).
4949 * @param previous the keyspace that has changed, in its previous form (before the change).
5050 */
5151 void onKeyspaceChanged(KeyspaceMetadata current, KeyspaceMetadata previous);
@@ -67,7 +67,7 @@
6767 /**
6868 * Called when a table has changed.
6969 *
70- * @param current the table that has changed, in its current form (after the change).
70+ * @param current the table that has changed, in its current form (after the change).
7171 * @param previous the table that has changed, in its previous form (before the change).
7272 */
7373 void onTableChanged(TableMetadata current, TableMetadata previous);
@@ -89,7 +89,7 @@
8989 /**
9090 * Called when a user-defined type has changed.
9191 *
92- * @param current the type that has changed, in its current form (after the change).
92+ * @param current the type that has changed, in its current form (after the change).
9393 * @param previous the type that has changed, in its previous form (before the change).
9494 */
9595 void onUserTypeChanged(UserType current, UserType previous);
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +82 −93
@@ -15,21 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.io.Closeable;
19-import java.util.Collection;
20-
18+import com.datastax.driver.core.exceptions.*;
2119 import com.google.common.util.concurrent.ListenableFuture;
2220
23-import com.datastax.driver.core.exceptions.*;
21+import java.io.Closeable;
22+import java.util.Collection;
2423
2524 /**
2625 * A session holds connections to a Cassandra cluster, allowing it to be queried.
27- *
26+ * <p/>
2827 * Each session maintains multiple connections to the cluster nodes,
2928 * provides policies to choose which node to use for each query (round-robin on
3029 * all nodes of the cluster by default), and handles retries for failed query (when
3130 * it makes sense), etc...
32- * <p>
31+ * <p/>
3332 * Session instances are thread-safe and usually a single instance is enough
3433 * per application. As a given session can only be "logged" into one keyspace at
3534 * a time (where the "logged" keyspace is the one used by query if the query doesn't
@@ -42,7 +41,7 @@
4241
4342 /**
4443 * The keyspace to which this Session is currently logged in, if any.
45- * <p>
44+ * <p/>
4645 * This correspond to the name passed to {@link Cluster#connect(String)}, or to the
4746 * last keyspace logged into through a "USE" CQL query if one was used.
4847 *
@@ -54,7 +53,7 @@
5453 /**
5554 * Force the initialization of this Session instance if it hasn't been
5655 * initialized yet.
57- * <p>
56+ * <p/>
5857 * Please note first that most use won't need to call this method
5958 * explicitly. If you use the {@link Cluster#connect} method {@code Cluster}
6059 * to create your Session, the returned session will be already
@@ -63,73 +62,70 @@
6362 * initialized the first time that session is used for querying. This method
6463 * is thus only useful if you use {@link Cluster#newSession} and want to
6564 * explicitly force initialization without querying.
66- * <p>
65+ * <p/>
6766 * Session initialization consists in connecting the Session to the known
6867 * Cassandra hosts (at least those that should not be ignored due to
6968 * the {@code LoadBalancingPolicy} in place).
70- * <p>
69+ * <p/>
7170 * If the Cluster instance this Session depends on is not itself
7271 * initialized, it will be initialized by this method.
73- * <p>
72+ * <p/>
7473 * If the session is already initialized, this method is a no-op.
7574 *
7675 * @return this {@code Session} object.
77- *
7876 * @throws NoHostAvailableException if this initialization triggers the
79- * Cluster initialization and no host amongst the contact points can be
80- * reached.
81- * @throws AuthenticationException if this initialization triggers the
82- * Cluster initialization and an authentication error occurs while contacting
83- * the initial contact points.
77+ * Cluster initialization and no host amongst the contact points can be
78+ * reached.
79+ * @throws AuthenticationException if this initialization triggers the
80+ * Cluster initialization and an authentication error occurs while contacting
81+ * the initial contact points.
8482 */
8583 public Session init();
8684
8785 /**
8886 * Executes the provided query.
89- *
87+ * <p/>
9088 * This is a convenience method for {@code execute(new SimpleStatement(query))}.
9189 *
9290 * @param query the CQL query to execute.
9391 * @return the result of the query. That result will never be null but can
9492 * be empty (and will be for any non SELECT query).
95- *
9693 * @throws NoHostAvailableException if no host in the cluster can be
97- * contacted successfully to execute this query.
98- * @throws QueryExecutionException if the query triggered an execution
99- * exception, i.e. an exception thrown by Cassandra when it cannot execute
100- * the query with the requested consistency level successfully.
94+ * contacted successfully to execute this query.
95+ * @throws QueryExecutionException if the query triggered an execution
96+ * exception, i.e. an exception thrown by Cassandra when it cannot execute
97+ * the query with the requested consistency level successfully.
10198 * @throws QueryValidationException if the query if invalid (syntax error,
102- * unauthorized or any other validation problem).
99+ * unauthorized or any other validation problem).
103100 */
104101 public ResultSet execute(String query);
105102
106103 /**
107104 * Executes the provided query using the provided value.
108- *
105+ * <p/>
109106 * This is a convenience method for {@code execute(new SimpleStatement(query, values))}.
110107 *
111- * @param query the CQL query to execute.
108+ * @param query the CQL query to execute.
112109 * @param values values required for the execution of {@code query}. See
113- * {@link SimpleStatement#SimpleStatement(String, Object...)} for more detail.
110+ * {@link SimpleStatement#SimpleStatement(String, Object...)} for more detail.
114111 * @return the result of the query. That result will never be null but can
115112 * be empty (and will be for any non SELECT query).
116- *
117- * @throws NoHostAvailableException if no host in the cluster can be
118- * contacted successfully to execute this query.
119- * @throws QueryExecutionException if the query triggered an execution
120- * exception, i.e. an exception thrown by Cassandra when it cannot execute
121- * the query with the requested consistency level successfully.
122- * @throws QueryValidationException if the query if invalid (syntax error,
123- * unauthorized or any other validation problem).
113+ * @throws NoHostAvailableException if no host in the cluster can be
114+ * contacted successfully to execute this query.
115+ * @throws QueryExecutionException if the query triggered an execution
116+ * exception, i.e. an exception thrown by Cassandra when it cannot execute
117+ * the query with the requested consistency level successfully.
118+ * @throws QueryValidationException if the query if invalid (syntax error,
119+ * unauthorized or any other validation problem).
124120 * @throws UnsupportedFeatureException if version 1 of the protocol
125- * is in use (i.e. if you've force version 1 through {@link Cluster.Builder#withProtocolVersion}
126- * or you use Cassandra 1.2).
121+ * is in use (i.e. if you've force version 1 through {@link Cluster.Builder#withProtocolVersion}
122+ * or you use Cassandra 1.2).
127123 */
128124 public ResultSet execute(String query, Object... values);
129125
130126 /**
131127 * Executes the provided query.
132- *
128+ * <p/>
133129 * This method blocks until at least some result has been received from the
134130 * database. However, for SELECT queries, it does not guarantee that the
135131 * result has been received in full. But it does guarantee that some
@@ -140,24 +136,23 @@
140136 * @param statement the CQL query to execute (that can be any {@code Statement}).
141137 * @return the result of the query. That result will never be null but can
142138 * be empty (and will be for any non SELECT query).
143- *
144- * @throws NoHostAvailableException if no host in the cluster can be
145- * contacted successfully to execute this query.
146- * @throws QueryExecutionException if the query triggered an execution
147- * exception, i.e. an exception thrown by Cassandra when it cannot execute
148- * the query with the requested consistency level successfully.
149- * @throws QueryValidationException if the query if invalid (syntax error,
150- * unauthorized or any other validation problem).
139+ * @throws NoHostAvailableException if no host in the cluster can be
140+ * contacted successfully to execute this query.
141+ * @throws QueryExecutionException if the query triggered an execution
142+ * exception, i.e. an exception thrown by Cassandra when it cannot execute
143+ * the query with the requested consistency level successfully.
144+ * @throws QueryValidationException if the query if invalid (syntax error,
145+ * unauthorized or any other validation problem).
151146 * @throws UnsupportedFeatureException if the protocol version 1 is in use and
152- * a feature not supported has been used. Features that are not supported by
153- * the version protocol 1 include: BatchStatement, ResultSet paging and binary
154- * values in RegularStatement.
147+ * a feature not supported has been used. Features that are not supported by
148+ * the version protocol 1 include: BatchStatement, ResultSet paging and binary
149+ * values in RegularStatement.
155150 */
156151 public ResultSet execute(Statement statement);
157152
158153 /**
159154 * Executes the provided query asynchronously.
160- * <p>
155+ * <p/>
161156 * This is a convenience method for {@code executeAsync(new SimpleStatement(query))}.
162157 *
163158 * @param query the CQL query to execute.
@@ -167,40 +162,38 @@
167162
168163 /**
169164 * Executes the provided query asynchronously using the provided values.
170- *
165+ * <p/>
171166 * This is a convenience method for {@code executeAsync(new SimpleStatement(query, values))}.
172167 *
173- * @param query the CQL query to execute.
168+ * @param query the CQL query to execute.
174169 * @param values values required for the execution of {@code query}. See
175- * {@link SimpleStatement#SimpleStatement(String, Object...)} for more detail.
170+ * {@link SimpleStatement#SimpleStatement(String, Object...)} for more detail.
176171 * @return a future on the result of the query.
177- *
178172 * @throws UnsupportedFeatureException if version 1 of the protocol
179- * is in use (i.e. if you've force version 1 through {@link Cluster.Builder#withProtocolVersion}
180- * or you use Cassandra 1.2).
173+ * is in use (i.e. if you've force version 1 through {@link Cluster.Builder#withProtocolVersion}
174+ * or you use Cassandra 1.2).
181175 */
182176 public ResultSetFuture executeAsync(String query, Object... values);
183177
184178 /**
185179 * Executes the provided query asynchronously.
186- *
180+ * <p/>
187181 * This method does not block. It returns as soon as the query has been
188182 * passed to the underlying network stack. In particular, returning from
189183 * this method does not guarantee that the query is valid or has even been
190184 * submitted to a live node. Any exception pertaining to the failure of the
191185 * query will be thrown when accessing the {@link ResultSetFuture}.
192- * <p>
186+ * <p/>
193187 * Note that for queries that doesn't return a result (INSERT, UPDATE and
194188 * DELETE), you will need to access the ResultSetFuture (that is call one of
195189 * its get method to make sure the query was successful.
196190 *
197191 * @param statement the CQL query to execute (that can be either any {@code Statement}.
198192 * @return a future on the result of the query.
199- *
200193 * @throws UnsupportedFeatureException if the protocol version 1 is in use and
201- * a feature not supported has been used. Features that are not supported by
202- * the version protocol 1 include: BatchStatement, ResultSet paging and binary
203- * values in RegularStatement.
194+ * a feature not supported has been used. Features that are not supported by
195+ * the version protocol 1 include: BatchStatement, ResultSet paging and binary
196+ * values in RegularStatement.
204197 */
205198 public ResultSetFuture executeAsync(Statement statement);
206199
@@ -209,15 +202,14 @@
209202 *
210203 * @param query the CQL query string to prepare
211204 * @return the prepared statement corresponding to {@code query}.
212- *
213205 * @throws NoHostAvailableException if no host in the cluster can be
214- * contacted successfully to prepare this query.
206+ * contacted successfully to prepare this query.
215207 */
216208 public PreparedStatement prepare(String query);
217209
218210 /**
219211 * Prepares the provided query.
220- * <p>
212+ * <p/>
221213 * This method is essentially a shortcut for {@code prepare(statement.getQueryString())},
222214 * but note that the resulting {@code PreparedStatement} will inherit the query properties
223215 * set on {@code statement}. Concretely, this means that in the following code:
@@ -227,7 +219,7 @@
227219 * session.execute(prepared.bind("someValue"));
228220 * </pre>
229221 * the final execution will be performed with Quorum consistency.
230- * <p>
222+ * <p/>
231223 * Please note that if the same CQL statement is prepared more than once, all
232224 * calls to this method will return the same {@code PreparedStatement} object
233225 * but the method will still apply the properties of the prepared
@@ -235,19 +227,18 @@
235227 *
236228 * @param statement the statement to prepare
237229 * @return the prepared statement corresponding to {@code statement}.
238- *
239230 * @throws NoHostAvailableException if no host in the cluster can be
240- * contacted successfully to prepare this statement.
231+ * contacted successfully to prepare this statement.
241232 * @throws IllegalArgumentException if {@code statement.getValues() != null}
242- * (values for executing a prepared statement should be provided after preparation
243- * though the {@link PreparedStatement#bind} method or through a corresponding
244- * {@link BoundStatement}).
233+ * (values for executing a prepared statement should be provided after preparation
234+ * though the {@link PreparedStatement#bind} method or through a corresponding
235+ * {@link BoundStatement}).
245236 */
246237 public PreparedStatement prepare(RegularStatement statement);
247238
248239 /**
249240 * Prepares the provided query string asynchronously.
250- * <p>
241+ * <p/>
251242 * This method is equivalent to {@link #prepare(String)} except that it
252243 * does not block but return a future instead. Any error during preparation will
253244 * be thrown when accessing the future, not by this method itself.
@@ -259,11 +250,11 @@
259250
260251 /**
261252 * Prepares the provided query asynchronously.
262- * <p>
253+ * <p/>
263254 * This method is essentially a shortcut for {@code prepareAsync(statement.getQueryString())},
264255 * but with the additional effect that the resulting {@code
265256 * PreparedStatement} will inherit the query properties set on {@code statement}.
266- * <p>
257+ * <p/>
267258 * Please note that if the same CQL statement is prepared more than once, all
268259 * calls to this method will return the same {@code PreparedStatement} object
269260 * but the method will still apply the properties of the prepared
@@ -271,31 +262,29 @@
271262 *
272263 * @param statement the statement to prepare
273264 * @return a future on the prepared statement corresponding to {@code statement}.
274- *
275- * @see Session#prepare(RegularStatement)
276- *
277265 * @throws IllegalArgumentException if {@code statement.getValues() != null}
278- * (values for executing a prepared statement should be provided after preparation
279- * though the {@link PreparedStatement#bind} method or through a corresponding
280- * {@link BoundStatement}).
266+ * (values for executing a prepared statement should be provided after preparation
267+ * though the {@link PreparedStatement#bind} method or through a corresponding
268+ * {@link BoundStatement}).
269+ * @see Session#prepare(RegularStatement)
281270 */
282271 public ListenableFuture<PreparedStatement> prepareAsync(RegularStatement statement);
283272
284273 /**
285274 * Initiates a shutdown of this session instance.
286- * <p>
275+ * <p/>
287276 * This method is asynchronous and return a future on the completion
288277 * of the shutdown process. As soon a the session is shutdown, no
289278 * new request will be accepted, but already submitted queries are
290279 * allowed to complete. This method closes all connections of this
291280 * session and reclaims all resources used by it.
292- * <p>
281+ * <p/>
293282 * If for some reason you wish to expedite this process, the
294283 * {@link CloseFuture#force} can be called on the result future.
295- * <p>
284+ * <p/>
296285 * This method has no particular effect if the session was already closed
297286 * (in which case the returned future will return immediately).
298- * <p>
287+ * <p/>
299288 * Note that this method does not close the corresponding {@code Cluster}
300289 * instance (which holds additional resources, in particular internal
301290 * executors that must be shut down in order for the client program to
@@ -310,9 +299,9 @@
310299 /**
311300 * Initiates a shutdown of this session instance and blocks until
312301 * that shutdown completes.
313- * <p>
302+ * <p/>
314303 * This method is a shortcut for {@code closeAsync().get()}.
315- * <p>
304+ * <p/>
316305 * Note that this method does not close the corresponding {@code Cluster}
317306 * instance (which holds additional resources, in particular internal
318307 * executors that must be shut down in order for the client program to
@@ -324,7 +313,7 @@
324313
325314 /**
326315 * Whether this Session instance has been closed.
327- * <p>
316+ * <p/>
328317 * Note that this method returns true as soon as one closing this Session
329318 * has started but it does not guarantee that the closing is done. If you
330319 * want to guarantee that the closing is done, you can call {@code close()}
@@ -345,7 +334,7 @@
345334
346335 /**
347336 * Return a snapshot of the state of this Session.
348- * <p>
337+ * <p/>
349338 * The returned object provides information on which hosts the session is
350339 * connected to, how many connections are opened to each host, etc...
351340 * The returned object is immutable, it is a snapshot of the Session State
@@ -357,7 +346,7 @@
357346
358347 /**
359348 * The state of a Session.
360- * <p>
349+ * <p/>
361350 * This mostly exposes information on the connections maintained by a Session:
362351 * which host it is connected to, how many connection is has for each host, etc...
363352 */
@@ -372,7 +361,7 @@
372361 /**
373362 * The hosts to which the session is currently connected (more precisely, at the time
374363 * this State has been grabbed).
375- * <p>
364+ * <p/>
376365 * Please note that this method really returns the hosts for which the session currently
377366 * holds a connection pool. A such, it's unlikely but not impossible for a host to be listed
378367 * in the output of this method but to have {@code getOpenConnections} return 0, if the
@@ -384,7 +373,7 @@
384373
385374 /**
386375 * The number of open connections to a given host.
387- * <p>
376+ * <p/>
388377 * Note that this refers to <em>active</em> connections. The actual number of connections also
389378 * includes {@link #getTrashedConnections(Host)}.
390379 *
@@ -396,7 +385,7 @@
396385
397386 /**
398387 * The number of "trashed" connections to a given host.
399- * <p>
388+ * <p/>
400389 * When the load to a host decreases, the driver will reclaim some connections in order to save
401390 * resources. No requests are sent to these connections anymore, but they are kept open for an
402391 * additional amount of time ({@link PoolingOptions#getIdleTimeoutSeconds()}), in case the load
@@ -410,7 +399,7 @@
410399
411400 /**
412401 * The number of queries that are currently being executed though a given host.
413- * <p>
402+ * <p/>
414403 * This correspond to the number of queries that have been sent (by the session this
415404 * is a State of) to the Cassandra Host on one of its connection but haven't yet returned.
416405 * In that sense this provide a sort of measure of how busy the connections to that node
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +45 −43
@@ -15,19 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.nio.ByteBuffer;
20-import java.util.*;
21-import java.util.concurrent.*;
22-import java.util.concurrent.atomic.AtomicReference;
23-
24-import com.google.common.base.Functions;
25-import com.google.common.collect.ImmutableList;
26-import com.google.common.collect.Lists;
27-import com.google.common.util.concurrent.*;
28-import org.slf4j.Logger;
29-import org.slf4j.LoggerFactory;
30-
3118 import com.datastax.driver.core.Message.Response;
3219 import com.datastax.driver.core.exceptions.DriverInternalError;
3320 import com.datastax.driver.core.exceptions.InvalidQueryException;
@@ -36,6 +23,21 @@
3623 import com.datastax.driver.core.policies.ReconnectionPolicy;
3724 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
3825 import com.datastax.driver.core.utils.MoreFutures;
26+import com.google.common.base.Functions;
27+import com.google.common.collect.ImmutableList;
28+import com.google.common.collect.Lists;
29+import com.google.common.util.concurrent.*;
30+import org.slf4j.Logger;
31+import org.slf4j.LoggerFactory;
32+
33+import java.net.InetSocketAddress;
34+import java.nio.ByteBuffer;
35+import java.util.*;
36+import java.util.concurrent.ConcurrentHashMap;
37+import java.util.concurrent.ConcurrentMap;
38+import java.util.concurrent.ExecutionException;
39+import java.util.concurrent.TimeUnit;
40+import java.util.concurrent.atomic.AtomicReference;
3941
4042 /**
4143 * Driver implementation of the Session interface.
@@ -83,14 +85,14 @@
8385 Collection<Host> hosts = cluster.getMetadata().allHosts();
8486 ListenableFuture<?> allPoolsCreatedFuture = createPools(hosts);
8587 ListenableFuture<?> allPoolsUpdatedFuture = Futures.transform(allPoolsCreatedFuture,
86- new AsyncFunction<Object, Object>() {
87- @Override
88- @SuppressWarnings("unchecked")
89- public ListenableFuture<Object> apply(Object input) throws Exception {
90- isInit = true;
91- return (ListenableFuture<Object>)updateCreatedPools();
92- }
93- });
88+ new AsyncFunction<Object, Object>() {
89+ @Override
90+ @SuppressWarnings("unchecked")
91+ public ListenableFuture<Object> apply(Object input) throws Exception {
92+ isInit = true;
93+ return (ListenableFuture<Object>) updateCreatedPools();
94+ }
95+ });
9496
9597 Futures.addCallback(allPoolsUpdatedFuture, new FutureCallback<Object>() {
9698 @Override
@@ -162,8 +164,8 @@
162164 future = new CloseFuture.Forwarding(futures);
163165
164166 return closeFuture.compareAndSet(null, future)
165- ? future
166- : closeFuture.get(); // We raced, it's ok, return the future that was actually set
167+ ? future
168+ : closeFuture.get(); // We raced, it's ok, return the future that was actually set
167169 }
168170
169171 public boolean isClosed() {
@@ -183,10 +185,10 @@
183185 public ListenableFuture<PreparedStatement> apply(Response response) {
184186 switch (response.type) {
185187 case RESULT:
186- Responses.Result rm = (Responses.Result)response;
188+ Responses.Result rm = (Responses.Result) response;
187189 switch (rm.kind) {
188190 case PREPARED:
189- Responses.Result.Prepared pmsg = (Responses.Result.Prepared)rm;
191+ Responses.Result.Prepared pmsg = (Responses.Result.Prepared) rm;
190192 PreparedStatement stmt = DefaultPreparedStatement.fromMessage(pmsg, cluster.getMetadata(), cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(), query, poolsState.keyspace);
191193 stmt = cluster.manager.addPrepared(stmt);
192194 if (cluster.getConfiguration().getQueryOptions().isPrepareOnAllHosts()) {
@@ -198,14 +200,14 @@
198200 }
199201 default:
200202 return Futures.immediateFailedFuture(
201- new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind)));
203+ new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind)));
202204 }
203205 case ERROR:
204206 return Futures.immediateFailedFuture(
205- ((Responses.Error)response).asException(future.getAddress()));
207+ ((Responses.Error) response).asException(future.getAddress()));
206208 default:
207209 return Futures.immediateFailedFuture(
208- new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type)));
210+ new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type)));
209211 }
210212 }
211213 });
@@ -353,10 +355,10 @@
353355 @Override
354356 public void onFailure(Throwable t) {
355357 if (t instanceof UnsupportedProtocolVersionException) {
356- cluster.manager.logUnsupportedVersionProtocol(host, ((UnsupportedProtocolVersionException)t).unsupportedVersion);
358+ cluster.manager.logUnsupportedVersionProtocol(host, ((UnsupportedProtocolVersionException) t).unsupportedVersion);
357359 cluster.manager.triggerOnDown(host, false);
358360 } else if (t instanceof ClusterNameMismatchException) {
359- ClusterNameMismatchException e = (ClusterNameMismatchException)t;
361+ ClusterNameMismatchException e = (ClusterNameMismatchException) t;
360362 cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
361363 cluster.manager.triggerOnDown(host, false);
362364 } else {
@@ -373,8 +375,8 @@
373375 CloseFuture removePool(Host host) {
374376 final HostConnectionPool pool = pools.remove(host);
375377 return pool == null
376- ? CloseFuture.immediateFuture()
377- : pool.closeAsync();
378+ ? CloseFuture.immediateFuture()
379+ : pool.closeAsync();
378380 }
379381
380382 /*
@@ -516,16 +518,16 @@
516518 }
517519
518520 if (statement instanceof StatementWrapper)
519- statement = ((StatementWrapper)statement).getWrappedStatement();
521+ statement = ((StatementWrapper) statement).getWrappedStatement();
520522
521523 if (statement instanceof RegularStatement) {
522- RegularStatement rs = (RegularStatement)statement;
524+ RegularStatement rs = (RegularStatement) statement;
523525
524526 // It saddens me that we special case for the query builder here, but for now this is simpler.
525527 // We could provide a general API in RegularStatement instead at some point but it's unclear what's
526528 // the cleanest way to do that is right now (and it's probably not really that useful anyway).
527529 if (version == ProtocolVersion.V1 && rs instanceof com.datastax.driver.core.querybuilder.BuiltStatement)
528- ((com.datastax.driver.core.querybuilder.BuiltStatement)rs).setForceNoValues(true);
530+ ((com.datastax.driver.core.querybuilder.BuiltStatement) rs).setForceNoValues(true);
529531
530532 ByteBuffer[] rawValues = rs.getValues(version);
531533
@@ -535,18 +537,18 @@
535537 List<ByteBuffer> values = rawValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawValues);
536538 String qString = rs.getQueryString();
537539 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, values, false,
538- fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
540+ fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
539541 return new Requests.Query(qString, options, statement.isTracing());
540542 } else if (statement instanceof BoundStatement) {
541- BoundStatement bs = (BoundStatement)statement;
543+ BoundStatement bs = (BoundStatement) statement;
542544 if (!cluster.manager.preparedQueries.containsKey(bs.statement.getPreparedId().id)) {
543545 throw new InvalidQueryException(String.format("Tried to execute unknown prepared query : %s. "
544- + "You may have used a PreparedStatement that was created with another Cluster instance.", bs.statement.getPreparedId().id));
546+ + "You may have used a PreparedStatement that was created with another Cluster instance.", bs.statement.getPreparedId().id));
545547 }
546548 bs.ensureAllSet();
547549 boolean skipMetadata = version != ProtocolVersion.V1 && bs.statement.getPreparedId().resultSetMetadata != null;
548550 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, Arrays.asList(bs.wrapper.values), skipMetadata,
549- fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
551+ fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
550552 return new Requests.Execute(bs.statement.getPreparedId().id, options, statement.isTracing());
551553 } else {
552554 assert statement instanceof BatchStatement : statement;
@@ -555,7 +557,7 @@
555557 if (version == ProtocolVersion.V1)
556558 throw new UnsupportedFeatureException(version, "Protocol level batching is not supported");
557559
558- BatchStatement bs = (BatchStatement)statement;
560+ BatchStatement bs = (BatchStatement) statement;
559561 bs.ensureAllSet();
560562 BatchStatement.IdAndValues idAndVals = bs.getIdAndValues(version);
561563 Requests.BatchProtocolOptions options = new Requests.BatchProtocolOptions(consistency, serialConsistency, defaultTimestamp);
@@ -565,7 +567,7 @@
565567
566568 /**
567569 * Execute the provided request.
568- *
570+ * <p/>
569571 * This method will find a suitable node to connect to using the
570572 * {@link LoadBalancingPolicy} and handle host failover.
571573 */
@@ -612,8 +614,8 @@
612614 }
613615 // Return the statement when all futures are done
614616 return Futures.transform(
615- Futures.successfulAsList(futures),
616- Functions.constant(statement));
617+ Futures.successfulAsList(futures),
618+ Functions.constant(statement));
617619 }
618620
619621 ResultSetFuture executeQuery(Message.Request msg, Statement statement) {
modified driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java +42 −60
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+
1820 import java.math.BigDecimal;
1921 import java.math.BigInteger;
2022 import java.net.InetAddress;
2123 import java.nio.ByteBuffer;
2224 import java.util.*;
2325
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
25-
2626 /**
2727 * Collection of (typed) CQL values that can set by index (starting a 0).
2828 */
@@ -34,9 +34,8 @@
3434 * @param i the index of the value to set.
3535 * @param v the value to set.
3636 * @return this object.
37- *
3837 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
39- * @throws InvalidTypeException if value {@code i} is not of type BOOLEAN.
38+ * @throws InvalidTypeException if value {@code i} is not of type BOOLEAN.
4039 */
4140 public T setBool(int i, boolean v);
4241
@@ -46,9 +45,8 @@
4645 * @param i the index of the value to set.
4746 * @param v the value to set.
4847 * @return this object.
49- *
5048 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
51- * @throws InvalidTypeException if value {@code i} is not of type INT.
49+ * @throws InvalidTypeException if value {@code i} is not of type INT.
5250 */
5351 public T setInt(int i, int v);
5452
@@ -58,9 +56,8 @@
5856 * @param i the index of the value to set.
5957 * @param v the value to set.
6058 * @return this object.
61- *
6259 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
63- * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
60+ * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
6461 */
6562 public T setLong(int i, long v);
6663
@@ -70,9 +67,8 @@
7067 * @param i the index of the value to set.
7168 * @param v the value to set.
7269 * @return this object.
73- *
7470 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
75- * @throws InvalidTypeException if value {@code i} is not of type TIMESTAMP.
71+ * @throws InvalidTypeException if value {@code i} is not of type TIMESTAMP.
7672 */
7773 public T setDate(int i, Date v);
7874
@@ -82,9 +78,8 @@
8278 * @param i the index of the value to set.
8379 * @param v the value to set.
8480 * @return this object.
85- *
8681 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
87- * @throws InvalidTypeException if value {@code i} is not of type FLOAT.
82+ * @throws InvalidTypeException if value {@code i} is not of type FLOAT.
8883 */
8984 public T setFloat(int i, float v);
9085
@@ -94,9 +89,8 @@
9489 * @param i the index of the value to set.
9590 * @param v the value to set.
9691 * @return this object.
97- *
9892 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
99- * @throws InvalidTypeException if value {@code i} is not of type DOUBLE.
93+ * @throws InvalidTypeException if value {@code i} is not of type DOUBLE.
10094 */
10195 public T setDouble(int i, double v);
10296
@@ -106,16 +100,15 @@
106100 * @param i the index of the value to set.
107101 * @param v the value to set.
108102 * @return this object.
109- *
110103 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
111- * @throws InvalidTypeException if value {@code i} is of neither of the
112- * following types: VARCHAR, TEXT or ASCII.
104+ * @throws InvalidTypeException if value {@code i} is of neither of the
105+ * following types: VARCHAR, TEXT or ASCII.
113106 */
114107 public T setString(int i, String v);
115108
116109 /**
117110 * Sets the {@code i}th value to the provided byte buffer.
118- *
111+ * <p/>
119112 * This method validate that the type of the column set is BLOB. If you
120113 * want to insert manually serialized data into columns of another type,
121114 * use {@link #setBytesUnsafe} instead.
@@ -123,15 +116,14 @@
123116 * @param i the index of the value to set.
124117 * @param v the value to set.
125118 * @return this object.
126- *
127119 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
128- * @throws InvalidTypeException if value {@code i} is not of type BLOB.
120+ * @throws InvalidTypeException if value {@code i} is not of type BLOB.
129121 */
130122 public T setBytes(int i, ByteBuffer v);
131123
132124 /**
133125 * Sets the {@code i}th value to the provided byte buffer.
134- *
126+ * <p/>
135127 * Contrary to {@link #setBytes}, this method does not check the
136128 * type of the column set. If you insert data that is not compatible with
137129 * the type of the column, you will get an {@code InvalidQueryException} at
@@ -140,7 +132,6 @@
140132 * @param i the index of the value to set.
141133 * @param v the value to set.
142134 * @return this object.
143- *
144135 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
145136 */
146137 public T setBytesUnsafe(int i, ByteBuffer v);
@@ -151,9 +142,8 @@
151142 * @param i the index of the value to set.
152143 * @param v the value to set.
153144 * @return this object.
154- *
155145 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
156- * @throws InvalidTypeException if value {@code i} is not of type VARINT.
146+ * @throws InvalidTypeException if value {@code i} is not of type VARINT.
157147 */
158148 public T setVarint(int i, BigInteger v);
159149
@@ -163,9 +153,8 @@
163153 * @param i the index of the value to set.
164154 * @param v the value to set.
165155 * @return this object.
166- *
167156 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
168- * @throws InvalidTypeException if value {@code i} is not of type DECIMAL.
157+ * @throws InvalidTypeException if value {@code i} is not of type DECIMAL.
169158 */
170159 public T setDecimal(int i, BigDecimal v);
171160
@@ -175,11 +164,10 @@
175164 * @param i the index of the value to set.
176165 * @param v the value to set.
177166 * @return this object.
178- *
179167 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
180- * @throws InvalidTypeException if value {@code i} is not of type UUID or
181- * TIMEUUID, or if value {@code i} is of type TIMEUUID but {@code v} is
182- * not a type 1 UUID.
168+ * @throws InvalidTypeException if value {@code i} is not of type UUID or
169+ * TIMEUUID, or if value {@code i} is of type TIMEUUID but {@code v} is
170+ * not a type 1 UUID.
183171 */
184172 public T setUUID(int i, UUID v);
185173
@@ -189,63 +177,59 @@
189177 * @param i the index of the value to set.
190178 * @param v the value to set.
191179 * @return this object.
192- *
193180 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
194- * @throws InvalidTypeException if value {@code i} is not of type INET.
181+ * @throws InvalidTypeException if value {@code i} is not of type INET.
195182 */
196183 public T setInet(int i, InetAddress v);
197184
198185 /**
199186 * Sets the {@code i}th value to the provided list.
200- * <p>
187+ * <p/>
201188 * Please note that {@code null} values are not supported inside collection by CQL.
202189 *
203190 * @param i the index of the value to set.
204191 * @param v the value to set.
205192 * @return this object.
206- *
207193 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
208- * @throws InvalidTypeException if value {@code i} is not a list type or
209- * if the elements of {@code v} are not of the type of the elements of
210- * column {@code i}.
211- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
212- * by CQL.
194+ * @throws InvalidTypeException if value {@code i} is not a list type or
195+ * if the elements of {@code v} are not of the type of the elements of
196+ * column {@code i}.
197+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
198+ * by CQL.
213199 */
214200 public <E> T setList(int i, List<E> v);
215201
216202 /**
217203 * Sets the {@code i}th value to the provided map.
218- * <p>
204+ * <p/>
219205 * Please note that {@code null} values are not supported inside collection by CQL.
220206 *
221207 * @param i the index of the value to set.
222208 * @param v the value to set.
223209 * @return this object.
224- *
225210 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
226- * @throws InvalidTypeException if value {@code i} is not a map type or
227- * if the elements (keys or values) of {@code v} are not of the type of the
228- * elements of column {@code i}.
229- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
230- * by CQL.
211+ * @throws InvalidTypeException if value {@code i} is not a map type or
212+ * if the elements (keys or values) of {@code v} are not of the type of the
213+ * elements of column {@code i}.
214+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
215+ * by CQL.
231216 */
232217 public <K, V> T setMap(int i, Map<K, V> v);
233218
234219 /**
235220 * Sets the {@code i}th value to the provided set.
236- * <p>
221+ * <p/>
237222 * Please note that {@code null} values are not supported inside collection by CQL.
238223 *
239224 * @param i the index of the value to set.
240225 * @param v the value to set.
241226 * @return this object.
242- *
243227 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
244- * @throws InvalidTypeException if value {@code i} is not a set type or
245- * if the elements of {@code v} are not of the type of the elements of
246- * column {@code i}.
247- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
248- * by CQL.
228+ * @throws InvalidTypeException if value {@code i} is not a set type or
229+ * if the elements of {@code v} are not of the type of the elements of
230+ * column {@code i}.
231+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
232+ * by CQL.
249233 */
250234 public <E> T setSet(int i, Set<E> v);
251235
@@ -255,10 +239,9 @@
255239 * @param i the index of the value to set.
256240 * @param v the value to set.
257241 * @return this object.
258- *
259242 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
260- * @throws InvalidTypeException if value {@code i} is not a UDT value or if its definition
261- * does not correspond to the one of {@code v}.
243+ * @throws InvalidTypeException if value {@code i} is not a UDT value or if its definition
244+ * does not correspond to the one of {@code v}.
262245 */
263246 public T setUDTValue(int i, UDTValue v);
264247
@@ -268,16 +251,15 @@
268251 * @param i the index of the value to set.
269252 * @param v the value to set.
270253 * @return this object.
271- *
272254 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
273- * @throws InvalidTypeException if value {@code i} is not a tuple value or if its types
274- * do not correspond to the ones of {@code v}.
255+ * @throws InvalidTypeException if value {@code i} is not a tuple value or if its types
256+ * do not correspond to the ones of {@code v}.
275257 */
276258 public T setTupleValue(int i, TupleValue v);
277259
278260 /**
279261 * Sets the {@code i}th value to {@code null}.
280- * <p>
262+ * <p/>
281263 * This is mainly intended for CQL types which map to native Java types.
282264 *
283265 * @param i the index of the value to set.
modified driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java +90 −108
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+
1820 import java.math.BigDecimal;
1921 import java.math.BigInteger;
2022 import java.net.InetAddress;
2123 import java.nio.ByteBuffer;
2224 import java.util.*;
2325
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
25-
2626 /**
2727 * Collection of (typed) CQL values that can set by name.
2828 */
@@ -33,12 +33,11 @@
3333 * provided boolean.
3434 *
3535 * @param name the name of the value to set; if {@code name} is present multiple
36- * times, all its values are set.
37- * @param v the value to set.
36+ * times, all its values are set.
37+ * @param v the value to set.
3838 * @return this object.
39- *
4039 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
41- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type BOOLEAN.
40+ * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type BOOLEAN.
4241 */
4342 public T setBool(String name, boolean v);
4443
@@ -47,12 +46,11 @@
4746 * provided integer.
4847 *
4948 * @param name the name of the value to set; if {@code name} is present multiple
50- * times, all its values are set.
51- * @param v the value to set.
49+ * times, all its values are set.
50+ * @param v the value to set.
5251 * @return this object.
53- *
5452 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
55- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type INT.
53+ * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type INT.
5654 */
5755 public T setInt(String name, int v);
5856
@@ -61,13 +59,12 @@
6159 * provided long.
6260 *
6361 * @param name the name of the value to set; if {@code name} is present multiple
64- * times, all its values are set.
65- * @param v the value to set.
62+ * times, all its values are set.
63+ * @param v the value to set.
6664 * @return this object.
67- *
6865 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
69- * @throws InvalidTypeException if (any occurrence of) {@code name} is
70- * not of type BIGINT or COUNTER.
66+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
67+ * not of type BIGINT or COUNTER.
7168 */
7269 public T setLong(String name, long v);
7370
@@ -76,13 +73,12 @@
7673 * provided date.
7774 *
7875 * @param name the name of the value to set; if {@code name} is present multiple
79- * times, all its values are set.
80- * @param v the value to set.
76+ * times, all its values are set.
77+ * @param v the value to set.
8178 * @return this object.
82- *
8379 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
84- * @throws InvalidTypeException if (any occurrence of) {@code name} is
85- * not of type TIMESTAMP.
80+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
81+ * not of type TIMESTAMP.
8682 */
8783 public T setDate(String name, Date v);
8884
@@ -91,13 +87,12 @@
9187 * provided float.
9288 *
9389 * @param name the name of the value to set; if {@code name} is present multiple
94- * times, all its values are set.
95- * @param v the value to set.
90+ * times, all its values are set.
91+ * @param v the value to set.
9692 * @return this object.
97- *
9893 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
99- * @throws InvalidTypeException if (any occurrence of) {@code name} is
100- * not of type FLOAT.
94+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
95+ * not of type FLOAT.
10196 */
10297 public T setFloat(String name, float v);
10398
@@ -106,13 +101,12 @@
106101 * provided double.
107102 *
108103 * @param name the name of the value to set; if {@code name} is present multiple
109- * times, all its values are set.
110- * @param v the value to set.
104+ * times, all its values are set.
105+ * @param v the value to set.
111106 * @return this object.
112- *
113107 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
114- * @throws InvalidTypeException if (any occurrence of) {@code name} is
115- * not of type DOUBLE.
108+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
109+ * not of type DOUBLE.
116110 */
117111 public T setDouble(String name, double v);
118112
@@ -121,48 +115,45 @@
121115 * provided string.
122116 *
123117 * @param name the name of the value to set; if {@code name} is present multiple
124- * times, all its values are set.
125- * @param v the value to set.
118+ * times, all its values are set.
119+ * @param v the value to set.
126120 * @return this object.
127- *
128121 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
129- * @throws InvalidTypeException if (any occurrence of) {@code name} is
130- * of neither of the following types: VARCHAR, TEXT or ASCII.
122+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
123+ * of neither of the following types: VARCHAR, TEXT or ASCII.
131124 */
132125 public T setString(String name, String v);
133126
134127 /**
135128 * Sets the value for (all occurrences of) variable {@code name} to the
136129 * provided byte buffer.
137- *
130+ * <p/>
138131 * This method validate that the type of the column set is BLOB. If you
139132 * want to insert manually serialized data into columns of another type,
140133 * use {@link #setBytesUnsafe} instead.
141134 *
142135 * @param name the name of the value to set; if {@code name} is present multiple
143- * times, all its values are set.
144- * @param v the value to set.
136+ * times, all its values are set.
137+ * @param v the value to set.
145138 * @return this object.
146- *
147139 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
148- * @throws InvalidTypeException if (any occurrence of) {@code name} is not of type BLOB.
140+ * @throws InvalidTypeException if (any occurrence of) {@code name} is not of type BLOB.
149141 */
150142 public T setBytes(String name, ByteBuffer v);
151143
152144 /**
153145 * Sets the value for (all occurrences of) variable {@code name} to the
154146 * provided byte buffer.
155- *
147+ * <p/>
156148 * Contrary to {@link #setBytes}, this method does not check the
157149 * type of the column set. If you insert data that is not compatible with
158150 * the type of the column, you will get an {@code InvalidQueryException} at
159151 * execute time.
160152 *
161153 * @param name the name of the value to set; if {@code name} is present multiple
162- * times, all its values are set.
163- * @param v the value to set.
154+ * times, all its values are set.
155+ * @param v the value to set.
164156 * @return this object.
165- *
166157 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
167158 */
168159 public T setBytesUnsafe(String name, ByteBuffer v);
@@ -172,13 +163,12 @@
172163 * provided big integer.
173164 *
174165 * @param name the name of the value to set; if {@code name} is present multiple
175- * times, all its values are set.
176- * @param v the value to set.
166+ * times, all its values are set.
167+ * @param v the value to set.
177168 * @return this object.
178- *
179169 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
180- * @throws InvalidTypeException if (any occurrence of) {@code name} is
181- * not of type VARINT.
170+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
171+ * not of type VARINT.
182172 */
183173 public T setVarint(String name, BigInteger v);
184174
@@ -187,13 +177,12 @@
187177 * provided big decimal.
188178 *
189179 * @param name the name of the value to set; if {@code name} is present multiple
190- * times, all its values are set.
191- * @param v the value to set.
180+ * times, all its values are set.
181+ * @param v the value to set.
192182 * @return this object.
193- *
194183 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
195- * @throws InvalidTypeException if (any occurrence of) {@code name} is
196- * not of type DECIMAL.
184+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
185+ * not of type DECIMAL.
197186 */
198187 public T setDecimal(String name, BigDecimal v);
199188
@@ -202,14 +191,13 @@
202191 * provided UUID.
203192 *
204193 * @param name the name of the value to set; if {@code name} is present multiple
205- * times, all its values are set.
206- * @param v the value to set.
194+ * times, all its values are set.
195+ * @param v the value to set.
207196 * @return this object.
208- *
209197 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
210- * @throws InvalidTypeException if (any occurrence of) {@code name} is
211- * not of type UUID or TIMEUUID, or if value {@code name} is of type
212- * TIMEUUID but {@code v} is not a type 1 UUID.
198+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
199+ * not of type UUID or TIMEUUID, or if value {@code name} is of type
200+ * TIMEUUID but {@code v} is not a type 1 UUID.
213201 */
214202 public T setUUID(String name, UUID v);
215203
@@ -218,73 +206,69 @@
218206 * provided inet address.
219207 *
220208 * @param name the name of the value to set; if {@code name} is present multiple
221- * times, all its values are set.
222- * @param v the value to set.
209+ * times, all its values are set.
210+ * @param v the value to set.
223211 * @return this object.
224- *
225212 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
226- * @throws InvalidTypeException if (any occurrence of) {@code name} is
227- * not of type INET.
213+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
214+ * not of type INET.
228215 */
229216 public T setInet(String name, InetAddress v);
230217
231218 /**
232219 * Sets the value for (all occurrences of) variable {@code name} to the
233220 * provided list.
234- * <p>
221+ * <p/>
235222 * Please note that {@code null} values are not supported inside collection by CQL.
236223 *
237224 * @param name the name of the value to set; if {@code name} is present multiple
238- * times, all its values are set.
239- * @param v the value to set.
225+ * times, all its values are set.
226+ * @param v the value to set.
240227 * @return this object.
241- *
242228 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
243- * @throws InvalidTypeException if (any occurrence of) {@code name} is
244- * not a list type or if the elements of {@code v} are not of the type of
245- * the elements of column {@code name}.
246- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
247- * by CQL.
229+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
230+ * not a list type or if the elements of {@code v} are not of the type of
231+ * the elements of column {@code name}.
232+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
233+ * by CQL.
248234 */
249235 public <E> T setList(String name, List<E> v);
250236
251237 /**
252238 * Sets the value for (all occurrences of) variable {@code name} to the
253239 * provided map.
254- * <p>
240+ * <p/>
255241 * Please note that {@code null} values are not supported inside collection by CQL.
256242 *
257243 * @param name the name of the value to set; if {@code name} is present multiple
258- * times, all its values are set.
259- * @param v the value to set.
244+ * times, all its values are set.
245+ * @param v the value to set.
260246 * @return this object.
261- *
262247 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
263- * @throws InvalidTypeException if (any occurrence of) {@code name} is
264- * not a map type or if the elements (keys or values) of {@code v} are not of
265- * the type of the elements of column {@code name}.
266- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
267- * by CQL.
248+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
249+ * not a map type or if the elements (keys or values) of {@code v} are not of
250+ * the type of the elements of column {@code name}.
251+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
252+ * by CQL.
268253 */
269254 public <K, V> T setMap(String name, Map<K, V> v);
270255
271256 /**
272257 * Sets the value for (all occurrences of) variable {@code name} to the
273258 * provided set.
274- * <p>
259+ * <p/>
275260 * Please note that {@code null} values are not supported inside collection by CQL.
276261 *
277262 * @param name the name of the value to set; if {@code name} is present multiple
278- * times, all its values are set.
279- * @param v the value to set.
263+ * times, all its values are set.
264+ * @param v the value to set.
280265 * @return this object.
281- *
282266 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
283- * @throws InvalidTypeException if (any occurrence of) {@code name} is
284- * not a map type or if the elements of {@code v} are not of the type of
285- * the elements of column {@code name}.
286- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
287- * by CQL.
267+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
268+ * not a map type or if the elements of {@code v} are not of the type of
269+ * the elements of column {@code name}.
270+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
271+ * by CQL.
288272 */
289273 public <E> T setSet(String name, Set<E> v);
290274
@@ -293,16 +277,15 @@
293277 * provided UDT value.
294278 *
295279 * @param name the name of the value to set; if {@code name} is present multiple
296- * times, all its values are set.
297- * @param v the value to set.
280+ * times, all its values are set.
281+ * @param v the value to set.
298282 * @return this object.
299- *
300283 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
301- * @throws InvalidTypeException if value {@code i} is not a UDT value or if its definition
302- * does not correspond to the one of {@code v}.
303- * @throws InvalidTypeException if (any occurrence of) {@code name} is
304- * not a UDT value or if the definition of column {@code name} does not correspond to
305- * the one of {@code v}.
284+ * @throws InvalidTypeException if value {@code i} is not a UDT value or if its definition
285+ * does not correspond to the one of {@code v}.
286+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
287+ * not a UDT value or if the definition of column {@code name} does not correspond to
288+ * the one of {@code v}.
306289 */
307290 public T setUDTValue(String name, UDTValue v);
308291
@@ -311,24 +294,23 @@
311294 * provided tuple value.
312295 *
313296 * @param name the name of the value to set; if {@code name} is present multiple
314- * times, all its values are set.
315- * @param v the value to set.
297+ * times, all its values are set.
298+ * @param v the value to set.
316299 * @return this object.
317- *
318300 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
319- * @throws InvalidTypeException if (any occurrence of) {@code name} is
320- * not a tuple value or if the types of column {@code name} do not correspond to
321- * the ones of {@code v}.
301+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
302+ * not a tuple value or if the types of column {@code name} do not correspond to
303+ * the ones of {@code v}.
322304 */
323305 public T setTupleValue(String name, TupleValue v);
324306
325307 /**
326308 * Sets the value for (all occurrences of) variable {@code name} to {@code null}.
327- * <p>
309+ * <p/>
328310 * This is mainly intended for CQL types which map to native Java types.
329311 *
330312 * @param name the name of the value to set; if {@code name} is present multiple
331- * times, all its values are set.
313+ * times, all its values are set.
332314 * @return this object.
333315 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
334316 */
modified driver-core/src/main/java/com/datastax/driver/core/SettableData.java +0 −1
@@ -14,7 +14,6 @@
1414 * limitations under the License.
1515 */
1616 package com.datastax.driver.core;
17-import java.util.*;
1817
1918 /**
2019 * Collection of (typed) CQL values that can set either by index (starting a 0) or by name.
modified driver-core/src/main/java/com/datastax/driver/core/SimpleJSONParser.java +10 −10
@@ -22,15 +22,15 @@
2222 * The only reason we need to read json in the driver is because for
2323 * historical reason Cassandra encodes a few properties using json in
2424 * the schema and we need to decode them.
25- *
25+ * <p/>
2626 * We however don't need a full-blown JSON library because:
27- * 1) we know we only need to decode string lists and string maps
28- * 2) we can basically assume the input is valid, we don't particularly
29- * have to bother about decoding exactly JSON as long as we at least
30- * decode what we need.
31- * 3) we don't really care much about performance, none of this is done
32- * in performance sensitive parts.
33- *
27+ * 1) we know we only need to decode string lists and string maps
28+ * 2) we can basically assume the input is valid, we don't particularly
29+ * have to bother about decoding exactly JSON as long as we at least
30+ * decode what we need.
31+ * 3) we don't really care much about performance, none of this is done
32+ * in performance sensitive parts.
33+ * <p/>
3434 * So instead of pulling a new dependency, we roll out our own very dumb
3535 * parser. We should obviously not expose this publicly.
3636 */
@@ -123,7 +123,7 @@
123123 * the closing double-quote.
124124 */
125125 private String nextString() {
126- assert input.charAt(idx-1) == '"' : "Char is '" + input.charAt(idx-1) + '\'';
126+ assert input.charAt(idx - 1) == '"' : "Char is '" + input.charAt(idx - 1) + '\'';
127127 StringBuilder sb = new StringBuilder();
128128 while (true) {
129129 char c = nextChar();
@@ -150,7 +150,7 @@
150150 sb.append('\r');
151151 break;
152152 case 'u':
153- sb.append((char)Integer.parseInt(input.substring(idx, idx+4), 16));
153+ sb.append((char) Integer.parseInt(input.substring(idx, idx + 4), 16));
154154 idx += 4;
155155 break;
156156 case '"':
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +18 −25
@@ -41,7 +41,7 @@
4141
4242 /**
4343 * Creates a new {@code SimpleStatement} with the provided query string and values.
44- * <p>
44+ * <p/>
4545 * This version of SimpleStatement is useful when you do not want to execute a
4646 * query only once (and thus do not want to resort to prepared statement), but
4747 * do not want to convert all column values to string (typically, if you have blob
@@ -60,11 +60,11 @@
6060 * </pre>
6161 * except that the former version:
6262 * <ul>
63- * <li>Requires only one round-trip to a Cassandra node.</li>
64- * <li>Does not left any prepared statement stored in memory (neither client or
65- * server side) once it has been executed.</li>
63+ * <li>Requires only one round-trip to a Cassandra node.</li>
64+ * <li>Does not left any prepared statement stored in memory (neither client or
65+ * server side) once it has been executed.</li>
6666 * </ul>
67- * <p>
67+ * <p/>
6868 * Note that the type of the {@code values} provided to this method will
6969 * not be validated by the driver as is done by {@link BoundStatement#bind} since
7070 * {@code query} is not parsed (and hence the driver cannot know what those value
@@ -75,7 +75,7 @@
7575 * thrown by this constructor however if one of the value does not correspond to
7676 * any CQL3 type (for instance, if it is a custom class).
7777 *
78- * @param query the query string.
78+ * @param query the query string.
7979 * @param values values required for the execution of {@code query}.
8080 * @throws IllegalArgumentException if the number of values is greater than 65535.
8181 */
@@ -92,7 +92,7 @@
9292 Object value = values[i];
9393 try {
9494 if (value instanceof Token)
95- value = ((Token)value).getValue();
95+ value = ((Token) value).getValue();
9696 serializedValues[i] = DataType.serializeValue(value, protocolVersion);
9797 } catch (IllegalArgumentException e) {
9898 // Catch and rethrow to provide a more helpful error message (one that include which value is bad)
@@ -131,14 +131,13 @@
131131 public boolean hasValues() {
132132 return values != null && values.length > 0;
133133 }
134-
134+
135135 /**
136136 * Returns the {@code i}th value as the Java type matching its CQL type.
137137 *
138138 * @param i the index to retrieve.
139139 * @return the value of the {@code i}th value of this statement.
140- *
141- * @throws IllegalStateException if this statement does not have values.
140+ * @throws IllegalStateException if this statement does not have values.
142141 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
143142 */
144143 public Object getObject(int i) {
@@ -151,14 +150,13 @@
151150
152151 /**
153152 * Returns the routing key for the query.
154- * <p>
153+ * <p/>
155154 * Unless the routing key has been explicitly set through
156155 * {@link #setRoutingKey}, this method will return {@code null} to
157156 * avoid having to parse the query string to retrieve the partition key.
158157 *
159158 * @return the routing key set through {@link #setRoutingKey} if such a key
160159 * was set, {@code null} otherwise.
161- *
162160 * @see Statement#getRoutingKey
163161 */
164162 @Override
@@ -168,18 +166,17 @@
168166
169167 /**
170168 * Sets the routing key for this query.
171- * <p>
169+ * <p/>
172170 * This method allows you to manually provide a routing key for this query. It
173171 * is thus optional since the routing key is only an hint for token aware
174172 * load balancing policy but is never mandatory.
175- * <p>
173+ * <p/>
176174 * If the partition key for the query is composite, use the
177175 * {@link #setRoutingKey(ByteBuffer...)} method instead to build the
178176 * routing key.
179177 *
180178 * @param routingKey the raw (binary) value to use as routing key.
181179 * @return this {@code SimpleStatement} object.
182- *
183180 * @see Statement#getRoutingKey
184181 */
185182 public SimpleStatement setRoutingKey(ByteBuffer routingKey) {
@@ -189,14 +186,13 @@
189186
190187 /**
191188 * Returns the keyspace this query operates on.
192- * <p>
189+ * <p/>
193190 * Unless the keyspace has been explicitly set through {@link #setKeyspace},
194191 * this method will return {@code null} to avoid having to parse the query
195192 * string.
196193 *
197194 * @return the keyspace set through {@link #setKeyspace} if such keyspace was
198195 * set, {@code null} otherwise.
199- *
200196 * @see Statement#getKeyspace
201197 */
202198 @Override
@@ -206,18 +202,17 @@
206202
207203 /**
208204 * Sets the keyspace this query operates on.
209- * <p>
205+ * <p/>
210206 * This method allows you to manually provide a keyspace for this query. It
211207 * is thus optional since the value returned by this method is only an hint
212208 * for token aware load balancing policy but is never mandatory.
213- * <p>
209+ * <p/>
214210 * Do note that if the query does not use a fully qualified keyspace, then
215211 * you do not need to set the keyspace through that method as the
216212 * currently logged in keyspace will be used.
217213 *
218214 * @param keyspace the name of the keyspace this query operates on.
219215 * @return this {@code SimpleStatement} object.
220- *
221216 * @see Statement#getKeyspace
222217 */
223218 public SimpleStatement setKeyspace(String keyspace) {
@@ -227,15 +222,14 @@
227222
228223 /**
229224 * Sets the routing key for this query.
230- * <p>
225+ * <p/>
231226 * See {@link #setRoutingKey(ByteBuffer)} for more information. This
232227 * method is a variant for when the query partition key is composite and
233228 * thus the routing key must be built from multiple values.
234229 *
235230 * @param routingKeyComponents the raw (binary) values to compose to obtain
236- * the routing key.
231+ * the routing key.
237232 * @return this {@code SimpleStatement} object.
238- *
239233 * @see Statement#getRoutingKey
240234 */
241235 public SimpleStatement setRoutingKey(ByteBuffer... routingKeyComponents) {
@@ -250,8 +244,7 @@
250244 totalLength += 2 + bb.remaining() + 1;
251245
252246 ByteBuffer out = ByteBuffer.allocate(totalLength);
253- for (ByteBuffer buffer : buffers)
254- {
247+ for (ByteBuffer buffer : buffers) {
255248 ByteBuffer bb = buffer.duplicate();
256249 putShortLength(out, bb.remaining());
257250 out.put(bb);
modified driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +27 −36
@@ -24,7 +24,7 @@
2424 /**
2525 * The default connection timeout in milliseconds if none is set explicitly
2626 * using {@link #setConnectTimeoutMillis}.
27- * <p>
27+ * <p/>
2828 * That default is of 5 seconds.
2929 */
3030 public static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 5000;
@@ -32,7 +32,7 @@
3232 /**
3333 * The default read timeout in milliseconds if none is set explicitly
3434 * using {@link #setReadTimeoutMillis}.
35- * <p>
35+ * <p/>
3636 * That default is of 12 seconds so as to be slightly bigger that the
3737 * default Cassandra timeout.
3838 *
@@ -52,11 +52,12 @@
5252 /**
5353 * Creates a new {@code SocketOptions} instance with default values.
5454 */
55- public SocketOptions() {}
55+ public SocketOptions() {
56+ }
5657
5758 /**
5859 * The connection timeout in milliseconds.
59- * <p>
60+ * <p/>
6061 * As the name implies, the connection timeout defines how long the driver
6162 * waits to establish a new connection to a Cassandra node before giving up.
6263 *
@@ -68,7 +69,7 @@
6869
6970 /**
7071 * Sets the connection timeout in milliseconds.
71- * <p>
72+ * <p/>
7273 * The default value is {@link #DEFAULT_CONNECT_TIMEOUT_MILLIS}.
7374 *
7475 * @param connectTimeoutMillis the timeout to set.
@@ -81,10 +82,10 @@
8182
8283 /**
8384 * The per-host read timeout in milliseconds.
84- * <p>
85+ * <p/>
8586 * This defines how long the driver will wait for a given Cassandra node to
8687 * answer a query.
87- * <p>
88+ * <p/>
8889 * Please note that this is not the maximum time a call to {@link Session#execute} may block;
8990 * this is the maximum time that call will wait for one particular
9091 * Cassandra host, but other hosts will be tried if one of them times out. In
@@ -94,12 +95,12 @@
9495 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy} in use).
9596 * If you want to control how long to wait for a query, use {@link Session#executeAsync}
9697 * and the {@code ResultSetFuture#get(long, TimeUnit)} method.
97- * <p>
98+ * <p/>
9899 * Also note that for efficiency reasons, this read timeout is approximate: it
99100 * has an accuracy of up to 100 milliseconds (i.e. it may fire up to 100 milliseconds late).
100101 * It is not meant to be used for precise timeout, but rather as a protection
101102 * against misbehaving Cassandra nodes.
102- * <p>
103+ * <p/>
103104 *
104105 * @return the read timeout in milliseconds.
105106 */
@@ -109,20 +110,20 @@
109110
110111 /**
111112 * Sets the per-host read timeout in milliseconds.
112- * <p>
113+ * <p/>
113114 * When setting this value, keep in mind the following:
114115 * <ul>
115- * <li>it should be higher than the timeout settings used on the Cassandra side
116- * ({@code *_request_timeout_in_ms} in {@code cassandra.yaml}).</li>
117- * <li>the read timeout is only approximate and only control the timeout to one Cassandra
118- * host, not the full query (see {@link #getReadTimeoutMillis} for more details). If a
119- * high level of precision on the timeout to a request is required, you should use
120- * the {@link ResultSetFuture#get(long, java.util.concurrent.TimeUnit)} method.
121- * </li>
116+ * <li>it should be higher than the timeout settings used on the Cassandra side
117+ * ({@code *_request_timeout_in_ms} in {@code cassandra.yaml}).</li>
118+ * <li>the read timeout is only approximate and only control the timeout to one Cassandra
119+ * host, not the full query (see {@link #getReadTimeoutMillis} for more details). If a
120+ * high level of precision on the timeout to a request is required, you should use
121+ * the {@link ResultSetFuture#get(long, java.util.concurrent.TimeUnit)} method.
122+ * </li>
122123 * </ul>
123- * <p>
124+ * <p/>
124125 * Setting a value of 0 disables read timeouts.
125- * <p>
126+ * <p/>
126127 * The default value is {@link #DEFAULT_READ_TIMEOUT_MILLIS}.
127128 *
128129 * @param readTimeoutMillis the timeout to set.
@@ -145,13 +146,12 @@
145146
146147 /**
147148 * Sets whether to enable TCP keepalive.
148- * <p>
149+ * <p/>
149150 * By default, this option is not set by the driver. The actual value will be the default
150151 * from the underlying Netty transport (Java NIO or native epoll).
151152 *
152153 * @param keepAlive whether to enable or disable the option.
153154 * @return this {@code SocketOptions}.
154- *
155155 * @see java.net.SocketOptions#TCP_NODELAY
156156 */
157157 public SocketOptions setKeepAlive(boolean keepAlive) {
@@ -171,13 +171,12 @@
171171
172172 /**
173173 * Sets whether to enable reuse-address.
174- * <p>
174+ * <p/>
175175 * By default, this option is not set by the driver. The actual value will be the default
176176 * from the underlying Netty transport (Java NIO or native epoll).
177177 *
178178 * @param reuseAddress whether to enable or disable the option.
179179 * @return this {@code SocketOptions}.
180- *
181180 * @see java.net.SocketOptions#SO_REUSEADDR
182181 */
183182 public SocketOptions setReuseAddress(boolean reuseAddress) {
@@ -189,7 +188,6 @@
189188 * Returns the linger-on-close timeout.
190189 *
191190 * @return the value of the option, or {@code null} if it is not set.
192- *
193191 * @see #setSoLinger(int)
194192 */
195193 public Integer getSoLinger() {
@@ -198,13 +196,12 @@
198196
199197 /**
200198 * Sets the linger-on-close timeout.
201- * <p>
199+ * <p/>
202200 * By default, this option is not set by the driver. The actual value will be the default
203201 * from the underlying Netty transport (Java NIO or native epoll).
204-
202+ *
205203 * @param soLinger the new value.
206204 * @return this {@code SocketOptions}.
207- *
208205 * @see java.net.SocketOptions#SO_LINGER
209206 */
210207 public SocketOptions setSoLinger(int soLinger) {
@@ -216,7 +213,6 @@
216213 * Returns whether Nagle's algorithm is disabled.
217214 *
218215 * @return the value of the option ({@code true} means Nagle is disabled), or {@code null} if it is not set.
219- *
220216 * @see #setTcpNoDelay(boolean)
221217 */
222218 public Boolean getTcpNoDelay() {
@@ -225,12 +221,11 @@
225221
226222 /**
227223 * Sets whether to disable Nagle's algorithm.
228- * <p>
224+ * <p/>
229225 * By default, this option is set to {@code true} (Nagle disabled).
230226 *
231227 * @param tcpNoDelay whether to enable or disable the option.
232228 * @return this {@code SocketOptions}.
233- *
234229 * @see java.net.SocketOptions#TCP_NODELAY
235230 */
236231 public SocketOptions setTcpNoDelay(boolean tcpNoDelay) {
@@ -242,7 +237,6 @@
242237 * Returns the hint to the size of the underlying buffers for incoming network I/O.
243238 *
244239 * @return the value of the option, or {@code null} if it is not set.
245- *
246240 * @see #setReceiveBufferSize(int)
247241 */
248242 public Integer getReceiveBufferSize() {
@@ -251,13 +245,12 @@
251245
252246 /**
253247 * Sets a hint to the size of the underlying buffers for incoming network I/O.
254- * <p>
248+ * <p/>
255249 * By default, this option is not set by the driver. The actual value will be the default
256250 * from the underlying Netty transport (Java NIO or native epoll).
257251 *
258252 * @param receiveBufferSize the new value.
259253 * @return this {@code SocketOptions}.
260- *
261254 * @see java.net.SocketOptions#SO_RCVBUF
262255 */
263256 public SocketOptions setReceiveBufferSize(int receiveBufferSize) {
@@ -269,7 +262,6 @@
269262 * Returns the hint to the size of the underlying buffers for outgoing network I/O.
270263 *
271264 * @return the value of the option, or {@code null} if it is not set.
272- *
273265 * @see #setSendBufferSize(int)
274266 */
275267 public Integer getSendBufferSize() {
@@ -278,13 +270,12 @@
278270
279271 /**
280272 * Sets a hint to the size of the underlying buffers for outgoing network I/O.
281- * <p>
273+ * <p/>
282274 * By default, this option is not set by the driver. The actual value will be the default
283275 * from the underlying Netty transport (Java NIO or native epoll).
284276 *
285277 * @param sendBufferSize the new value.
286278 * @return this {@code SocketOptions}.
287- *
288279 * @see java.net.SocketOptions#SO_SNDBUF
289280 */
290281 public SocketOptions setSendBufferSize(int sendBufferSize) {
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +32 −35
@@ -15,15 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-
2018 import com.datastax.driver.core.exceptions.PagingStateException;
2119 import com.datastax.driver.core.policies.RetryPolicy;
2220 import com.datastax.driver.core.querybuilder.BuiltStatement;
2321
22+import java.nio.ByteBuffer;
23+
2424 /**
2525 * An executable query.
26- * <p>
26+ * <p/>
2727 * This represents either a {@link RegularStatement}, a {@link BoundStatement} or a
2828 * {@link BatchStatement} along with the querying options (consistency level,
2929 * whether to trace the query, ...).
@@ -81,7 +81,7 @@
8181
8282 /**
8383 * Sets the serial consistency level for the query.
84- *
84+ * <p/>
8585 * The serial consistency level is only used by conditional updates (so INSERT, UPDATE
8686 * and DELETE with an IF condition). For those, the serial consistency level defines
8787 * the consistency level of the serial phase (or "paxos" phase) while the
@@ -91,20 +91,19 @@
9191 * QUORUM read is guaranteed to see that write. But if the regular consistency of that
9292 * write is ANY, then only a read with a consistency of SERIAL is guaranteed to see it
9393 * (even a read with consistency ALL is not guaranteed to be enough).
94- * <p>
94+ * <p/>
9595 * The serial consistency can only be one of {@code ConsistencyLevel.SERIAL} or
9696 * {@code ConsistencyLevel.LOCAL_SERIAL}. While {@code ConsistencyLevel.SERIAL} guarantees full
9797 * linearizability (with other SERIAL updates), {@code ConsistencyLevel.LOCAL_SERIAL} only
9898 * guarantees it in the local data center.
99- * <p>
99+ * <p/>
100100 * The serial consistency level is ignored for any query that is not a conditional
101101 * update (serial reads should use the regular consistency level for instance).
102102 *
103103 * @param serialConsistency the serial consistency level to set.
104104 * @return this {@code Statement} object.
105- *
106105 * @throws IllegalArgumentException if {@code serialConsistency} is not one of
107- * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
106+ * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
108107 */
109108 public Statement setSerialConsistencyLevel(ConsistencyLevel serialConsistency) {
110109 if (serialConsistency != ConsistencyLevel.SERIAL && serialConsistency != ConsistencyLevel.LOCAL_SERIAL)
@@ -115,7 +114,7 @@
115114
116115 /**
117116 * The serial consistency level for this query.
118- * <p>
117+ * <p/>
119118 * See {@link #setSerialConsistencyLevel} for more detail on the serial consistency level.
120119 *
121120 * @return the consistency level for this query, or {@code null} if no serial
@@ -128,7 +127,7 @@
128127
129128 /**
130129 * Enables tracing for this query.
131- *
130+ * <p/>
132131 * By default (that is unless you call this method), tracing is not enabled.
133132 *
134133 * @return this {@code Statement} object.
@@ -161,7 +160,7 @@
161160 /**
162161 * Returns the routing key (in binary raw form) to use for token aware
163162 * routing of this query.
164- * <p>
163+ * <p/>
165164 * The routing key is optional in that implementers are free to
166165 * return {@code null}. The routing key is an hint used for token-aware routing (see
167166 * {@link com.datastax.driver.core.policies.TokenAwarePolicy}), and
@@ -176,7 +175,7 @@
176175
177176 /**
178177 * Returns the keyspace this query operates on.
179- * <p>
178+ * <p/>
180179 * Note that not all query specify on which keyspace they operate on, and
181180 * so this method can always return {@code null}. Firstly, some queries do
182181 * not operate inside a keyspace: keyspace creation, {@code USE} queries,
@@ -196,7 +195,7 @@
196195
197196 /**
198197 * Sets the retry policy to use for this query.
199- * <p>
198+ * <p/>
200199 * The default retry policy, if this method is not called, is the one returned by
201200 * {@link com.datastax.driver.core.policies.Policies#getRetryPolicy} in the
202201 * cluster configuration. This method is thus only useful in case you want
@@ -223,7 +222,7 @@
223222
224223 /**
225224 * Sets the query fetch size.
226- * <p>
225+ * <p/>
227226 * The fetch size controls how much resulting rows will be retrieved
228227 * simultaneously (the goal being to avoid loading too much results
229228 * in memory for queries yielding large results). Please note that
@@ -231,9 +230,9 @@
231230 * use such a low value in practice as it will yield very poor
232231 * performance. If in doubt, leaving the default is probably a good
233232 * idea.
234- * <p>
233+ * <p/>
235234 * Only {@code SELECT} queries only ever make use of that setting.
236- * <p>
235+ * <p/>
237236 * Note: Paging is not supported with the native protocol version 1. If
238237 * you call this method with {@code fetchSize &gt; 0} and
239238 * {@code fetchSize != Integer.MAX_VALUE} and the protocol version is in
@@ -242,8 +241,8 @@
242241 * when submitting this statement for execution.
243242 *
244243 * @param fetchSize the fetch size to use. If {@code fetchSize &lte; 0},
245- * the default fetch size will be used. To disable paging of the
246- * result set, use {@code fetchSize == Integer.MAX_VALUE}.
244+ * the default fetch size will be used. To disable paging of the
245+ * result set, use {@code fetchSize == Integer.MAX_VALUE}.
247246 * @return this {@code Statement} object.
248247 */
249248 public Statement setFetchSize(int fetchSize) {
@@ -264,11 +263,11 @@
264263
265264 /**
266265 * Sets the default timestamp for this query (in microseconds since the epoch).
267- * <p>
266+ * <p/>
268267 * This feature is only available when version {@link ProtocolVersion#V3 V3} or
269268 * higher of the native protocol is in use. With earlier versions, calling this
270269 * method has no effect.
271- * <p>
270+ * <p/>
272271 * The actual timestamp that will be used for this query is, in order of
273272 * preference:
274273 * <ul>
@@ -283,9 +282,8 @@
283282 * will generate a server-side one (similar to the pre-V3 behavior).
284283 *
285284 * @param defaultTimestamp the default timestamp for this query (must be strictly
286- * positive).
285+ * positive).
287286 * @return this {@code Statement} object.
288- *
289287 * @see Cluster.Builder#withTimestampGenerator(TimestampGenerator)
290288 */
291289 public Statement setDefaultTimestamp(long defaultTimestamp) {
@@ -304,10 +302,10 @@
304302
305303 /**
306304 * Sets the paging state.
307- * <p>
305+ * <p/>
308306 * This will cause the next execution of this statement to fetch results from a given
309307 * page, rather than restarting from the beginning.
310- * <p>
308+ * <p/>
311309 * You get the paging state from a previous execution of the statement (see
312310 * {@link ExecutionInfo#getPagingState()}.
313311 * This is typically used to iterate in a "stateless" manner (e.g. across HTTP requests):
@@ -337,11 +335,11 @@
337335 * }
338336 * }
339337 * </pre>
340- * <p>
338+ * <p/>
341339 * The paging state can only be reused between perfectly identical statements
342340 * (same query string, same bound parameters). Altering the contents of the paging state
343341 * or trying to set it on a different statement will cause this method to fail.
344- * <p>
342+ * <p/>
345343 * Note that, due to internal implementation details, the paging state is not portable
346344 * across native protocol versions (see the
347345 * <a href="http://datastax.github.io/java-driver/features/native_protocol">online documentation</a>
@@ -353,7 +351,6 @@
353351 * @param pagingState the paging state to set, or {@code null} to remove any state that was
354352 * previously set on this statement.
355353 * @return this {@code Statement} object.
356- *
357354 * @throws PagingStateException if the paging state does not match this statement.
358355 */
359356 public Statement setPagingState(PagingState pagingState) {
@@ -366,8 +363,8 @@
366363 this.pagingState = pagingState.getRawState();
367364 } else {
368365 throw new PagingStateException("Paging state mismatch, "
369- + "this means that either the paging state contents were altered, "
370- + "or you're trying to apply it to a different statement");
366+ + "this means that either the paging state contents were altered, "
367+ + "or you're trying to apply it to a different statement");
371368 }
372369 }
373370 return this;
@@ -375,7 +372,7 @@
375372
376373 /**
377374 * Sets the paging state.
378- * <p>
375+ * <p/>
379376 * Contrary to {@link #setPagingState(PagingState)}, this method takes the "raw" form of the
380377 * paging state (previously extracted with {@link ExecutionInfo#getPagingStateUnsafe()}.
381378 * It won't validate that this statement matches the one that the paging state was extracted from.
@@ -403,7 +400,7 @@
403400
404401 /**
405402 * Sets whether this statement is idempotent.
406- * <p>
403+ * <p/>
407404 * See {@link #isIdempotent()} for more explanations about this property.
408405 *
409406 * @param idempotent the new value.
@@ -417,21 +414,21 @@
417414 /**
418415 * Whether this statement is idempotent, i.e. whether it can be applied multiple times
419416 * without changing the result beyond the initial application.
420- * <p>
417+ * <p/>
421418 * Idempotence plays a role in {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}.
422419 * If a statement is <em>not idempotent</em>, the driver will not schedule speculative
423420 * executions for it.
424- * <p>
421+ * <p/>
425422 * Note that this method can return {@code null}, in which case the driver will default to
426423 * {@link QueryOptions#getDefaultIdempotence()}.
427- * <p>
424+ * <p/>
428425 * By default, this method returns {@code null} for all statements, except for
429426 * {@link BuiltStatement}s, where the value will be inferred from the query: if it updates
430427 * counters, prepends/appends to a list, or uses a function call or
431428 * {@link com.datastax.driver.core.querybuilder.QueryBuilder#raw(String)} anywhere in an inserted value,
432429 * the result will be {@code false}; otherwise it will be {@code true}.
433430 * In all cases, calling {@link #setIdempotent(boolean)} forces a value that overrides every other mechanism.
434- * <p>
431+ * <p/>
435432 * Note that when a statement is prepared ({@link Session#prepare(String)}), its idempotence flag will be propagated
436433 * to all {@link PreparedStatement}s created from it.
437434 *
modified driver-core/src/main/java/com/datastax/driver/core/StatementWrapper.java +6 −6
@@ -15,19 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-
2018 import com.datastax.driver.core.policies.LoadBalancingPolicy;
2119 import com.datastax.driver.core.policies.RetryPolicy;
2220 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2321
22+import java.nio.ByteBuffer;
23+
2424 /**
2525 * Base class for custom {@link Statement} implementations that wrap another statement.
26- * <p>
26+ * <p/>
2727 * This is intended for use with a custom {@link RetryPolicy}, {@link LoadBalancingPolicy} or
2828 * {@link SpeculativeExecutionPolicy}. The client code can wrap a statement to "mark" it, or
2929 * add information that will lead to special handling in the policy.
30- * <p>
30+ * <p/>
3131 * Example:
3232 * <pre>
3333 * {@code
@@ -71,8 +71,8 @@
7171 Statement getWrappedStatement() {
7272 // Protect against multiple levels of wrapping (even though there is no practical reason for that)
7373 return (wrapped instanceof StatementWrapper)
74- ? ((StatementWrapper)wrapped).getWrappedStatement()
75- : wrapped;
74+ ? ((StatementWrapper) wrapped).getWrappedStatement()
75+ : wrapped;
7676 }
7777
7878 @Override
modified driver-core/src/main/java/com/datastax/driver/core/StreamIdGenerator.java +2 −2
@@ -20,11 +20,11 @@
2020
2121 /**
2222 * Manages a set of integer identifiers.
23- * <p>
23+ * <p/>
2424 * Clients can borrow an id with {@link #next()}, and return it to the set with {@link #release(int)}.
2525 * It is guaranteed that a given id can't be borrowed by two clients at the same time.
2626 * This class is thread-safe and non-blocking.
27- * <p>
27+ * <p/>
2828 * Implementation notes: we use an atomic long array where each bit represents an id. It is set to 1 if
2929 * the id is available, 0 otherwise. When looking for an id, we find a long that has remaining 1's and
3030 * pick the rightmost one.
modified driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java +1 −1
@@ -20,7 +20,7 @@
2020
2121 /**
2222 * Allows overriding internal settings via system properties.
23- * <p>
23+ * <p/>
2424 * Warning: this is meant for integration tests only, NOT FOR PRODUCTION USE.
2525 */
2626 class SystemProperties {
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +72 −70
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
2018 import com.google.common.base.Predicate;
2119 import com.google.common.collect.ImmutableMap;
2220 import com.google.common.collect.Iterables;
2321 import org.slf4j.Logger;
2422 import org.slf4j.LoggerFactory;
2523
24+import java.util.*;
25+
2626 /**
2727 * Describes a Table.
2828 */
@@ -30,20 +30,20 @@
3030
3131 private static final Logger logger = LoggerFactory.getLogger(TableMetadata.class);
3232
33- static final String CF_NAME = "columnfamily_name";
34- private static final String CF_ID = "cf_id";
33+ static final String CF_NAME = "columnfamily_name";
34+ private static final String CF_ID = "cf_id";
3535
36- private static final String KEY_VALIDATOR = "key_validator";
37- private static final String COMPARATOR = "comparator";
38- private static final String VALIDATOR = "default_validator";
36+ private static final String KEY_VALIDATOR = "key_validator";
37+ private static final String COMPARATOR = "comparator";
38+ private static final String VALIDATOR = "default_validator";
3939
40- private static final String KEY_ALIASES = "key_aliases";
41- private static final String COLUMN_ALIASES = "column_aliases";
42- private static final String VALUE_ALIAS = "value_alias";
40+ private static final String KEY_ALIASES = "key_aliases";
41+ private static final String COLUMN_ALIASES = "column_aliases";
42+ private static final String VALUE_ALIAS = "value_alias";
4343
44- private static final String DEFAULT_KEY_ALIAS = "key";
44+ private static final String DEFAULT_KEY_ALIAS = "key";
4545 private static final String DEFAULT_COLUMN_ALIAS = "column";
46- private static final String DEFAULT_VALUE_ALIAS = "value";
46+ private static final String DEFAULT_VALUE_ALIAS = "value";
4747
4848 private static final Comparator<ColumnMetadata> columnMetadataComparator = new Comparator<ColumnMetadata>() {
4949 public int compare(ColumnMetadata c1, ColumnMetadata c2) {
@@ -64,7 +64,7 @@
6464
6565 /**
6666 * Clustering orders.
67- * <p>
67+ * <p/>
6868 * This is used by {@link #getClusteringOrder} to indicate the clustering
6969 * order of a table.
7070 */
@@ -108,8 +108,8 @@
108108 CassandraTypeParser.ParseResult keyValidator = CassandraTypeParser.parseWithComposite(row.getString(KEY_VALIDATOR));
109109 CassandraTypeParser.ParseResult comparator = CassandraTypeParser.parseWithComposite(row.getString(COMPARATOR));
110110 List<String> columnAliases = cassandraVersion.getMajor() >= 2 || row.getString(COLUMN_ALIASES) == null
111- ? Collections.<String>emptyList()
112- : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES));
111+ ? Collections.<String>emptyList()
112+ : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES));
113113
114114 int clusteringSize = findClusteringSize(comparator, rawCols.values(), columnAliases, cassandraVersion);
115115 boolean isDense = clusteringSize != comparator.types.size() - 1;
@@ -129,8 +129,8 @@
129129 // See ControlConnection#refreshSchema for why we'd rather not probably this further. Since table options is one thing
130130 // that tends to change often in Cassandra, it's worth special casing this.
131131 logger.error(String.format("Error parsing schema options for table %s.%s: "
132- + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\").getOptions() will return null",
133- ksm.getName(), name, ksm.getName(), name), e);
132+ + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\").getOptions() will return null",
133+ ksm.getName(), name, ksm.getName(), name), e);
134134 }
135135
136136 TableMetadata tm = new TableMetadata(ksm, name, id, partitionKey, clusteringColumns, columns, options, clusteringOrder, cassandraVersion);
@@ -143,8 +143,8 @@
143143 // In C* 1.2, only the REGULAR columns are in the columns schema table, so we need to add the names from
144144 // the aliases (and make sure we handle default aliases).
145145 List<String> keyAliases = row.getString(KEY_ALIASES) == null
146- ? Collections.<String>emptyList()
147- : SimpleJSONParser.parseStringList(row.getString(KEY_ALIASES));
146+ ? Collections.<String>emptyList()
147+ : SimpleJSONParser.parseStringList(row.getString(KEY_ALIASES));
148148 for (int i = 0; i < partitionKey.size(); i++) {
149149 String alias = keyAliases.size() > i ? keyAliases.get(i) : (i == 0 ? DEFAULT_KEY_ALIAS : DEFAULT_KEY_ALIAS + (i + 1));
150150 partitionKey.set(i, ColumnMetadata.forAlias(tm, alias, keyValidator.types.get(i)));
@@ -231,7 +231,7 @@
231231
232232 /**
233233 * Returns the unique id of this table.
234- * <p>
234+ * <p/>
235235 * Note: this id is available in Cassandra 2.1 and above. It will be
236236 * {@code null} for earlier versions.
237237 *
@@ -254,8 +254,8 @@
254254 * Returns metadata on a column of this table.
255255 *
256256 * @param name the name of the column to retrieve ({@code name} will be
257- * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
258- * see {@link Metadata#quote}).
257+ * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
258+ * see {@link Metadata#quote}).
259259 * @return the metadata for the {@code name} column if it exists, or
260260 * {@code null} otherwise.
261261 */
@@ -265,7 +265,7 @@
265265
266266 /**
267267 * Returns a list containing all the columns of this table.
268- *
268+ * <p/>
269269 * The order of the columns in the list is consistent with
270270 * the order of the columns returned by a {@code SELECT * FROM thisTable}:
271271 * the first column is the partition key, next are the clustering
@@ -280,7 +280,7 @@
280280
281281 /**
282282 * Returns the list of columns composing the primary key for this table.
283- *
283+ * <p/>
284284 * A table will always at least have a partition key (that
285285 * may itself be one or more columns), so the returned list at least
286286 * has one element.
@@ -296,7 +296,7 @@
296296
297297 /**
298298 * Returns the list of columns composing the partition key for this table.
299- *
299+ * <p/>
300300 * A table always has a partition key so the returned list has
301301 * at least one element.
302302 *
@@ -318,7 +318,7 @@
318318
319319 /**
320320 * Returns the clustering order for this table.
321- * <p>
321+ * <p/>
322322 * The returned contains the clustering order of each clustering column. The
323323 * {@code i}th element of the result correspond to the order (ascending or
324324 * descending) of the {@code i}th clustering column (see
@@ -348,11 +348,11 @@
348348 /**
349349 * Returns a {@code String} containing CQL queries representing this
350350 * table and the index on it.
351- * <p>
351+ * <p/>
352352 * In other words, this method returns the queries that would allow you to
353353 * recreate the schema of this table, along with the index defined on
354354 * columns of this table.
355- * <p>
355+ * <p/>
356356 * Note that the returned String is formatted to be human readable (for
357357 * some definition of human readable at least).
358358 *
@@ -376,10 +376,10 @@
376376
377377 /**
378378 * Returns a CQL query representing this table.
379- * <p>
379+ * <p/>
380380 * This method returns a single 'CREATE TABLE' query with the options
381381 * corresponding to this table definition.
382- * <p>
382+ * <p/>
383383 * Note that the returned string is a single line; the returned query
384384 * is not formatted in any way.
385385 *
@@ -397,7 +397,7 @@
397397 if (o == null || getClass() != o.getClass())
398398 return false;
399399
400- TableMetadata that = (TableMetadata)o;
400+ TableMetadata that = (TableMetadata) o;
401401
402402 if (!name.equals(that.name))
403403 return false;
@@ -443,7 +443,8 @@
443443 sb.append('(');
444444 boolean first = true;
445445 for (ColumnMetadata cm : partitionKey) {
446- if (first) first = false; else sb.append(", ");
446+ if (first) first = false;
447+ else sb.append(", ");
447448 sb.append(Metadata.escapeId(cm.getName()));
448449 }
449450 sb.append(')');
@@ -472,7 +473,7 @@
472473 else
473474 and(sb, formatted).append("caching = ").append(formatOptionMap(options.caching));
474475 if (options.comment != null)
475- and(sb, formatted).append("comment = '").append(options.comment.replace("'","''")).append('\'');
476+ and(sb, formatted).append("comment = '").append(options.comment.replace("'", "''")).append('\'');
476477 and(sb, formatted).append("compaction = ").append(formatOptionMap(options.compaction));
477478 and(sb, formatted).append("compression = ").append(formatOptionMap(options.compression));
478479 if (cassandraVersion.getMajor() >= 2) {
@@ -508,7 +509,8 @@
508509 sb.append("{ ");
509510 boolean first = true;
510511 for (Map.Entry<String, String> entry : m.entrySet()) {
511- if (first) first = false; else sb.append(", ");
512+ if (first) first = false;
513+ else sb.append(", ");
512514 sb.append('\'').append(entry.getKey()).append('\'');
513515 sb.append(" : ");
514516 try {
@@ -544,25 +546,25 @@
544546
545547 public static class Options {
546548
547- private static final String COMMENT = "comment";
548- private static final String READ_REPAIR = "read_repair_chance";
549- private static final String LOCAL_READ_REPAIR = "local_read_repair_chance";
550- private static final String REPLICATE_ON_WRITE = "replicate_on_write";
551- private static final String GC_GRACE = "gc_grace_seconds";
552- private static final String BF_FP_CHANCE = "bloom_filter_fp_chance";
553- private static final String CACHING = "caching";
554- private static final String COMPACTION_CLASS = "compaction_strategy_class";
555- private static final String COMPACTION_OPTIONS = "compaction_strategy_options";
556- private static final String MIN_COMPACTION_THRESHOLD = "min_compaction_threshold";
557- private static final String MAX_COMPACTION_THRESHOLD = "max_compaction_threshold";
558- private static final String POPULATE_CACHE_ON_FLUSH = "populate_io_cache_on_flush";
559- private static final String COMPRESSION_PARAMS = "compression_parameters";
560- private static final String MEMTABLE_FLUSH_PERIOD_MS = "memtable_flush_period_in_ms";
561- private static final String DEFAULT_TTL = "default_time_to_live";
562- private static final String SPECULATIVE_RETRY = "speculative_retry";
563- private static final String INDEX_INTERVAL = "index_interval";
564- private static final String MIN_INDEX_INTERVAL = "min_index_interval";
565- private static final String MAX_INDEX_INTERVAL = "max_index_interval";
549+ private static final String COMMENT = "comment";
550+ private static final String READ_REPAIR = "read_repair_chance";
551+ private static final String LOCAL_READ_REPAIR = "local_read_repair_chance";
552+ private static final String REPLICATE_ON_WRITE = "replicate_on_write";
553+ private static final String GC_GRACE = "gc_grace_seconds";
554+ private static final String BF_FP_CHANCE = "bloom_filter_fp_chance";
555+ private static final String CACHING = "caching";
556+ private static final String COMPACTION_CLASS = "compaction_strategy_class";
557+ private static final String COMPACTION_OPTIONS = "compaction_strategy_options";
558+ private static final String MIN_COMPACTION_THRESHOLD = "min_compaction_threshold";
559+ private static final String MAX_COMPACTION_THRESHOLD = "max_compaction_threshold";
560+ private static final String POPULATE_CACHE_ON_FLUSH = "populate_io_cache_on_flush";
561+ private static final String COMPRESSION_PARAMS = "compression_parameters";
562+ private static final String MEMTABLE_FLUSH_PERIOD_MS = "memtable_flush_period_in_ms";
563+ private static final String DEFAULT_TTL = "default_time_to_live";
564+ private static final String SPECULATIVE_RETRY = "speculative_retry";
565+ private static final String INDEX_INTERVAL = "index_interval";
566+ private static final String MIN_INDEX_INTERVAL = "min_index_interval";
567+ private static final String MAX_INDEX_INTERVAL = "max_index_interval";
566568
567569 private static final boolean DEFAULT_REPLICATE_ON_WRITE = true;
568570 private static final double DEFAULT_BF_FP_CHANCE = 0.01;
@@ -603,8 +605,8 @@
603605 this.gcGrace = row.getInt(GC_GRACE);
604606 this.bfFpChance = isNullOrAbsent(row, BF_FP_CHANCE) ? DEFAULT_BF_FP_CHANCE : row.getDouble(BF_FP_CHANCE);
605607 this.caching = is210OrMore
606- ? SimpleJSONParser.parseStringMap(row.getString(CACHING))
607- : ImmutableMap.of("keys", row.getString(CACHING));
608+ ? SimpleJSONParser.parseStringMap(row.getString(CACHING))
609+ : ImmutableMap.of("keys", row.getString(CACHING));
608610 this.populateCacheOnFlush = isNullOrAbsent(row, POPULATE_CACHE_ON_FLUSH) ? DEFAULT_POPULATE_CACHE_ON_FLUSH : row.getBool(POPULATE_CACHE_ON_FLUSH);
609611 this.memtableFlushPeriodMs = version.getMajor() < 2 || isNullOrAbsent(row, MEMTABLE_FLUSH_PERIOD_MS) ? DEFAULT_MEMTABLE_FLUSH_PERIOD : row.getInt(MEMTABLE_FLUSH_PERIOD_MS);
610612 this.defaultTTL = version.getMajor() < 2 || isNullOrAbsent(row, DEFAULT_TTL) ? DEFAULT_DEFAULT_TTL : row.getInt(DEFAULT_TTL);
@@ -617,11 +619,11 @@
617619
618620 if (is210OrMore) {
619621 this.minIndexInterval = isNullOrAbsent(row, MIN_INDEX_INTERVAL)
620- ? DEFAULT_MIN_INDEX_INTERVAL
621- : row.getInt(MIN_INDEX_INTERVAL);
622+ ? DEFAULT_MIN_INDEX_INTERVAL
623+ : row.getInt(MIN_INDEX_INTERVAL);
622624 this.maxIndexInterval = isNullOrAbsent(row, MAX_INDEX_INTERVAL)
623- ? DEFAULT_MAX_INDEX_INTERVAL
624- : row.getInt(MAX_INDEX_INTERVAL);
625+ ? DEFAULT_MAX_INDEX_INTERVAL
626+ : row.getInt(MAX_INDEX_INTERVAL);
625627 } else {
626628 this.minIndexInterval = null;
627629 this.maxIndexInterval = null;
@@ -635,7 +637,7 @@
635637
636638 private static boolean isNullOrAbsent(Row row, String name) {
637639 return row.getColumnDefinitions().getIndexOf(name) < 0
638- || row.isNull(name);
640+ || row.isNull(name);
639641 }
640642
641643 /**
@@ -676,7 +678,7 @@
676678
677679 /**
678680 * Returns whether replicateOnWrite is set for this table.
679- *
681+ * <p/>
680682 * This is only meaningful for tables holding counters.
681683 *
682684 * @return whether replicateOnWrite is set for this table.
@@ -736,7 +738,7 @@
736738
737739 /**
738740 * Returns the default TTL for this table.
739- * <p>
741+ * <p/>
740742 * Note: this option is not available in Cassandra 1.2 and will return 0 (no default
741743 * TTL) when connected to 1.2 nodes.
742744 *
@@ -749,7 +751,7 @@
749751
750752 /**
751753 * Returns the speculative retry option for this table.
752- * <p>
754+ * <p/>
753755 * Note: this option is not available in Cassandra 1.2 and will return "NONE" (no
754756 * speculative retry) when connected to 1.2 nodes.
755757 *
@@ -761,7 +763,7 @@
761763
762764 /**
763765 * Returns the index interval option for this table.
764- * <p>
766+ * <p/>
765767 * Note: this option is not available in Cassandra 1.2 (more precisely, it is not
766768 * configurable per-table) and will return 128 (the default index interval) when
767769 * connected to 1.2 nodes. It is deprecated in Cassandra 2.1 and above, and will
@@ -775,7 +777,7 @@
775777
776778 /**
777779 * Returns the minimum index interval option for this table.
778- * <p>
780+ * <p/>
779781 * Note: this option is available in Cassandra 2.1 and above, and will return
780782 * {@code null} for earlier versions.
781783 *
@@ -787,7 +789,7 @@
787789
788790 /**
789791 * Returns the maximum index interval option for this table.
790- * <p>
792+ * <p/>
791793 * Note: this option is available in Cassandra 2.1 and above, and will return
792794 * {@code null} for earlier versions.
793795 *
@@ -822,7 +824,7 @@
822824 if (o == null || getClass() != o.getClass())
823825 return false;
824826
825- Options options = (Options)o;
827+ Options options = (Options) o;
826828
827829 if (isCompactStorage != options.isCompactStorage)
828830 return false;
@@ -867,13 +869,13 @@
867869 result = (isCompactStorage ? 1 : 0);
868870 result = 31 * result + (comment != null ? comment.hashCode() : 0);
869871 temp = Double.doubleToLongBits(readRepair);
870- result = 31 * result + (int)(temp ^ (temp >>> 32));
872+ result = 31 * result + (int) (temp ^ (temp >>> 32));
871873 temp = Double.doubleToLongBits(localReadRepair);
872- result = 31 * result + (int)(temp ^ (temp >>> 32));
874+ result = 31 * result + (int) (temp ^ (temp >>> 32));
873875 result = 31 * result + (replicateOnWrite ? 1 : 0);
874876 result = 31 * result + gcGrace;
875877 temp = Double.doubleToLongBits(bfFpChance);
876- result = 31 * result + (int)(temp ^ (temp >>> 32));
878+ result = 31 * result + (int) (temp ^ (temp >>> 32));
877879 result = 31 * result + (caching != null ? caching.hashCode() : 0);
878880 result = 31 * result + (populateCacheOnFlush ? 1 : 0);
879881 result = 31 * result + memtableFlushPeriodMs;
modified driver-core/src/main/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.java +2 −2
@@ -19,11 +19,11 @@
1919 /**
2020 * A timestamp generator based on {@code System.currentTimeMillis()}, with an incrementing thread-local counter
2121 * to generate the sub-millisecond part.
22- * <p>
22+ * <p/>
2323 * This implementation guarantees incrementing timestamps for a given client thread, provided that no more than
2424 * 1000 are requested for a given clock tick (the exact granularity of of {@link System#currentTimeMillis()}
2525 * depends on the operating system).
26- * <p>
26+ * <p/>
2727 * If that rate is exceeded, a warning is logged and the timestamps don't increment anymore until the next clock
2828 * tick.
2929 */
modified driver-core/src/main/java/com/datastax/driver/core/TimestampGenerator.java +1 −1
@@ -17,7 +17,7 @@
1717
1818 /**
1919 * Generates client-side, microsecond-precision query timestamps.
20- * <p>
20+ * <p/>
2121 * Given that Cassandra uses those timestamps to resolve conflicts, implementations should generate
2222 * incrementing timestamps for successive implementations.
2323 */
modified driver-core/src/main/java/com/datastax/driver/core/Token.java +104 −66
@@ -15,19 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.Bytes;
19+import com.google.common.annotations.VisibleForTesting;
20+import com.google.common.collect.Lists;
21+import com.google.common.primitives.UnsignedBytes;
22+
1823 import java.math.BigInteger;
1924 import java.nio.ByteBuffer;
2025 import java.security.MessageDigest;
2126 import java.security.NoSuchAlgorithmException;
22-import java.util.Arrays;
2327 import java.util.List;
2428
25-import com.google.common.annotations.VisibleForTesting;
26-import com.google.common.collect.Lists;
27-import com.google.common.primitives.UnsignedBytes;
28-
29-import com.datastax.driver.core.utils.Bytes;
30-
3129 /**
3230 * A token on the Cassandra ring.
3331 */
@@ -60,17 +58,24 @@
6058
6159 static abstract class Factory {
6260 abstract Token fromString(String tokenStr);
61+
6362 abstract DataType getTokenType();
63+
6464 abstract Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion);
65- /** The minimum token is a special value that no key ever hashes to, it's used both as lower and upper bound. */
65+
66+ /**
67+ * The minimum token is a special value that no key ever hashes to, it's used both as lower and upper bound.
68+ */
6669 abstract Token minToken();
70+
6771 abstract Token hash(ByteBuffer partitionKey);
72+
6873 abstract List<Token> split(Token startToken, Token endToken, int numberOfSplits);
6974
7075 // Base implementation for split
7176 protected List<BigInteger> split(BigInteger start, BigInteger range,
72- BigInteger ringEnd, BigInteger ringLength,
73- int numberOfSplits) {
77+ BigInteger ringEnd, BigInteger ringLength,
78+ int numberOfSplits) {
7479 BigInteger[] tmp = range.divideAndRemainder(BigInteger.valueOf(numberOfSplits));
7580 BigInteger divider = tmp[0];
7681 int remainder = tmp[1].intValue();
@@ -78,7 +83,7 @@
7883 List<BigInteger> results = Lists.newArrayListWithExpectedSize(numberOfSplits - 1);
7984 BigInteger current = start;
8085 BigInteger dividerPlusOne = (remainder == 0) ? null // won't be used
81- : divider.add(BigInteger.ONE);
86+ : divider.add(BigInteger.ONE);
8287
8388 for (int i = 1; i < numberOfSplits; i++) {
8489 current = current.add(remainder-- > 0 ? dividerPlusOne : divider);
@@ -107,9 +112,9 @@
107112 int i_8 = index << 3;
108113 int blockOffset = offset + i_8;
109114 return ((long) key.get(blockOffset + 0) & 0xff) + (((long) key.get(blockOffset + 1) & 0xff) << 8) +
110- (((long) key.get(blockOffset + 2) & 0xff) << 16) + (((long) key.get(blockOffset + 3) & 0xff) << 24) +
111- (((long) key.get(blockOffset + 4) & 0xff) << 32) + (((long) key.get(blockOffset + 5) & 0xff) << 40) +
112- (((long) key.get(blockOffset + 6) & 0xff) << 48) + (((long) key.get(blockOffset + 7) & 0xff) << 56);
115+ (((long) key.get(blockOffset + 2) & 0xff) << 16) + (((long) key.get(blockOffset + 3) & 0xff) << 24) +
116+ (((long) key.get(blockOffset + 4) & 0xff) << 32) + (((long) key.get(blockOffset + 5) & 0xff) << 40) +
117+ (((long) key.get(blockOffset + 6) & 0xff) << 48) + (((long) key.get(blockOffset + 7) & 0xff) << 56);
113118 }
114119
115120 private long rotl64(long v, int n) {
@@ -144,14 +149,24 @@
144149 //----------
145150 // body
146151
147- for(int i = 0; i < nblocks; i++) {
148- long k1 = getblock(data, offset, i*2+0);
149- long k2 = getblock(data, offset, i*2+1);
150-
151- k1 *= c1; k1 = rotl64(k1,31); k1 *= c2; h1 ^= k1;
152- h1 = rotl64(h1,27); h1 += h2; h1 = h1*5+0x52dce729;
153- k2 *= c2; k2 = rotl64(k2,33); k2 *= c1; h2 ^= k2;
154- h2 = rotl64(h2,31); h2 += h1; h2 = h2*5+0x38495ab5;
152+ for (int i = 0; i < nblocks; i++) {
153+ long k1 = getblock(data, offset, i * 2 + 0);
154+ long k2 = getblock(data, offset, i * 2 + 1);
155+
156+ k1 *= c1;
157+ k1 = rotl64(k1, 31);
158+ k1 *= c2;
159+ h1 ^= k1;
160+ h1 = rotl64(h1, 27);
161+ h1 += h2;
162+ h1 = h1 * 5 + 0x52dce729;
163+ k2 *= c2;
164+ k2 = rotl64(k2, 33);
165+ k2 *= c1;
166+ h2 ^= k2;
167+ h2 = rotl64(h2, 31);
168+ h2 += h1;
169+ h2 = h2 * 5 + 0x38495ab5;
155170 }
156171
157172 //----------
@@ -163,31 +178,54 @@
163178 long k1 = 0;
164179 long k2 = 0;
165180
166- switch(length & 15) {
167- case 15: k2 ^= ((long) data.get(offset+14)) << 48;
168- case 14: k2 ^= ((long) data.get(offset+13)) << 40;
169- case 13: k2 ^= ((long) data.get(offset+12)) << 32;
170- case 12: k2 ^= ((long) data.get(offset+11)) << 24;
171- case 11: k2 ^= ((long) data.get(offset+10)) << 16;
172- case 10: k2 ^= ((long) data.get(offset+9)) << 8;
173- case 9: k2 ^= ((long) data.get(offset+8)) << 0;
174- k2 *= c2; k2 = rotl64(k2,33); k2 *= c1; h2 ^= k2;
175-
176- case 8: k1 ^= ((long) data.get(offset+7)) << 56;
177- case 7: k1 ^= ((long) data.get(offset+6)) << 48;
178- case 6: k1 ^= ((long) data.get(offset+5)) << 40;
179- case 5: k1 ^= ((long) data.get(offset+4)) << 32;
180- case 4: k1 ^= ((long) data.get(offset+3)) << 24;
181- case 3: k1 ^= ((long) data.get(offset+2)) << 16;
182- case 2: k1 ^= ((long) data.get(offset+1)) << 8;
183- case 1: k1 ^= ((long) data.get(offset));
184- k1 *= c1; k1 = rotl64(k1,31); k1 *= c2; h1 ^= k1;
185- };
181+ switch (length & 15) {
182+ case 15:
183+ k2 ^= ((long) data.get(offset + 14)) << 48;
184+ case 14:
185+ k2 ^= ((long) data.get(offset + 13)) << 40;
186+ case 13:
187+ k2 ^= ((long) data.get(offset + 12)) << 32;
188+ case 12:
189+ k2 ^= ((long) data.get(offset + 11)) << 24;
190+ case 11:
191+ k2 ^= ((long) data.get(offset + 10)) << 16;
192+ case 10:
193+ k2 ^= ((long) data.get(offset + 9)) << 8;
194+ case 9:
195+ k2 ^= ((long) data.get(offset + 8)) << 0;
196+ k2 *= c2;
197+ k2 = rotl64(k2, 33);
198+ k2 *= c1;
199+ h2 ^= k2;
200+
201+ case 8:
202+ k1 ^= ((long) data.get(offset + 7)) << 56;
203+ case 7:
204+ k1 ^= ((long) data.get(offset + 6)) << 48;
205+ case 6:
206+ k1 ^= ((long) data.get(offset + 5)) << 40;
207+ case 5:
208+ k1 ^= ((long) data.get(offset + 4)) << 32;
209+ case 4:
210+ k1 ^= ((long) data.get(offset + 3)) << 24;
211+ case 3:
212+ k1 ^= ((long) data.get(offset + 2)) << 16;
213+ case 2:
214+ k1 ^= ((long) data.get(offset + 1)) << 8;
215+ case 1:
216+ k1 ^= ((long) data.get(offset));
217+ k1 *= c1;
218+ k1 = rotl64(k1, 31);
219+ k1 *= c2;
220+ h1 ^= k1;
221+ }
222+ ;
186223
187224 //----------
188225 // finalization
189226
190- h1 ^= length; h2 ^= length;
227+ h1 ^= length;
228+ h2 ^= length;
191229
192230 h1 += h2;
193231 h2 += h1;
@@ -233,16 +271,16 @@
233271 if (startToken.equals(endToken) && startToken.equals(MIN_TOKEN))
234272 endToken = MAX_TOKEN;
235273
236- BigInteger start = BigInteger.valueOf(((M3PToken)startToken).value);
237- BigInteger end = BigInteger.valueOf(((M3PToken)endToken).value);
274+ BigInteger start = BigInteger.valueOf(((M3PToken) startToken).value);
275+ BigInteger end = BigInteger.valueOf(((M3PToken) endToken).value);
238276
239277 BigInteger range = end.subtract(start);
240278 if (range.compareTo(BigInteger.ZERO) < 0)
241279 range = range.add(RING_LENGTH);
242280
243281 List<BigInteger> values = super.split(start, range,
244- RING_END, RING_LENGTH,
245- numberOfSplits);
282+ RING_END, RING_LENGTH,
283+ numberOfSplits);
246284 List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size());
247285 for (BigInteger value : values)
248286 tokens.add(new M3PToken(value.longValue()));
@@ -267,7 +305,7 @@
267305 @Override
268306 public int compareTo(Token other) {
269307 assert other instanceof M3PToken;
270- long otherValue = ((M3PToken)other).value;
308+ long otherValue = ((M3PToken) other).value;
271309 return value < otherValue ? -1 : (value == otherValue) ? 0 : 1;
272310 }
273311
@@ -278,12 +316,12 @@
278316 if (obj == null || this.getClass() != obj.getClass())
279317 return false;
280318
281- return value == ((M3PToken)obj).value;
319+ return value == ((M3PToken) obj).value;
282320 }
283321
284322 @Override
285323 public int hashCode() {
286- return (int)(value^(value>>>32));
324+ return (int) (value ^ (value >>> 32));
287325 }
288326
289327 @Override
@@ -346,8 +384,8 @@
346384 if (tokenOrder == 0 && startToken.equals(MIN_TOKEN))
347385 throw new IllegalArgumentException("Cannot split whole ring with ordered partitioner");
348386
349- OPPToken oppStartToken = (OPPToken)startToken;
350- OPPToken oppEndToken = (OPPToken)endToken;
387+ OPPToken oppStartToken = (OPPToken) startToken;
388+ OPPToken oppEndToken = (OPPToken) endToken;
351389
352390 int significantBytes;
353391 BigInteger start, end, range, ringEnd, ringLength;
@@ -389,8 +427,8 @@
389427 }
390428
391429 List<BigInteger> values = super.split(start, range,
392- ringEnd, ringLength,
393- numberOfSplits);
430+ ringEnd, ringLength,
431+ numberOfSplits);
394432 List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size());
395433 for (BigInteger value : values)
396434 tokens.add(new OPPToken(toBytes(value, significantBytes)));
@@ -446,8 +484,8 @@
446484 private static ByteBuffer stripTrailingZeroBytes(ByteBuffer b) {
447485 byte result[] = Bytes.getArray(b);
448486 int zeroIndex = result.length;
449- for(int i = result.length-1; i > 0; i--) {
450- if(result[i] == 0) {
487+ for (int i = result.length - 1; i > 0; i--) {
488+ if (result[i] == 0) {
451489 zeroIndex = i;
452490 } else {
453491 break;
@@ -470,8 +508,8 @@
470508 public int compareTo(Token other) {
471509 assert other instanceof OPPToken;
472510 return UnsignedBytes.lexicographicalComparator().compare(
473- Bytes.getArray(value),
474- Bytes.getArray(((OPPToken)other).value));
511+ Bytes.getArray(value),
512+ Bytes.getArray(((OPPToken) other).value));
475513 }
476514
477515 @Override
@@ -481,7 +519,7 @@
481519 if (obj == null || this.getClass() != obj.getClass())
482520 return false;
483521
484- return value.equals(((OPPToken)obj).value);
522+ return value.equals(((OPPToken) obj).value);
485523 }
486524
487525 @Override
@@ -532,7 +570,7 @@
532570
533571 @Override
534572 Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion) {
535- return new RPToken((BigInteger)getTokenType().deserialize(buffer, protocolVersion));
573+ return new RPToken((BigInteger) getTokenType().deserialize(buffer, protocolVersion));
536574 }
537575
538576 @Override
@@ -551,16 +589,16 @@
551589 if (startToken.equals(endToken) && startToken.equals(MIN_TOKEN))
552590 endToken = MAX_TOKEN;
553591
554- BigInteger start = ((RPToken)startToken).value;
555- BigInteger end = ((RPToken)endToken).value;
592+ BigInteger start = ((RPToken) startToken).value;
593+ BigInteger end = ((RPToken) endToken).value;
556594
557595 BigInteger range = end.subtract(start);
558596 if (range.compareTo(BigInteger.ZERO) < 0)
559597 range = range.add(RING_LENGTH);
560598
561599 List<BigInteger> values = super.split(start, range,
562- MAX_VALUE, RING_LENGTH,
563- numberOfSplits);
600+ MAX_VALUE, RING_LENGTH,
601+ numberOfSplits);
564602 List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size());
565603 for (BigInteger value : values)
566604 tokens.add(new RPToken(value));
@@ -585,7 +623,7 @@
585623 @Override
586624 public int compareTo(Token other) {
587625 assert other instanceof RPToken;
588- return value.compareTo(((RPToken)other).value);
626+ return value.compareTo(((RPToken) other).value);
589627 }
590628
591629 @Override
@@ -595,7 +633,7 @@
595633 if (obj == null || this.getClass() != obj.getClass())
596634 return false;
597635
598- return value.equals(((RPToken)obj).value);
636+ return value.equals(((RPToken) obj).value);
599637 }
600638
601639 @Override
modified driver-core/src/main/java/com/datastax/driver/core/TokenRange.java +46 −48
@@ -15,21 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.ArrayList;
19-import java.util.Iterator;
20-import java.util.List;
21-
2218 import com.google.common.annotations.VisibleForTesting;
2319 import com.google.common.base.Objects;
2420 import com.google.common.collect.ImmutableList;
2521 import com.google.common.collect.Lists;
2622
23+import java.util.ArrayList;
24+import java.util.List;
25+
2726 /**
2827 * A range of tokens on the Cassandra ring.
29- * <p>
28+ * <p/>
3029 * A range is start-exclusive and end-inclusive. It is empty when start and end are the same token, except if that is the minimum
3130 * token, in which case the range covers the whole ring (this is consistent with the behavior of CQL range queries).
32- * <p>
31+ * <p/>
3332 * Note that CQL does not handle wrapping. To query all partitions in a range, see {@link #unwrap()}.
3433 */
3534 public final class TokenRange implements Comparable<TokenRange> {
@@ -64,12 +63,11 @@
6463
6564 /**
6665 * Splits this range into a number of smaller ranges of equal "size" (referring to the number of tokens, not the actual amount of data).
67- * <p>
66+ * <p/>
6867 * Splitting an empty range is not permitted. But note that, in edge cases, splitting a range might produce one or more empty ranges.
6968 *
7069 * @param numberOfSplits the number of splits to create.
7170 * @return the splits.
72- *
7371 * @throws IllegalArgumentException if the range is empty or if numberOfSplits < 1.
7472 */
7573 public List<TokenRange> splitEvenly(int numberOfSplits) {
@@ -91,7 +89,7 @@
9189
9290 /**
9391 * Returns whether this range is empty.
94- * <p>
92+ * <p/>
9593 * A range is empty when start and end are the same token, except if that is the minimum token,
9694 * in which case the range covers the whole ring (this is consistent with the behavior of CQL
9795 * range queries).
@@ -114,13 +112,13 @@
114112 /**
115113 * Splits this range into a list of two non-wrapping ranges. This will return the range itself if it is
116114 * non-wrapping, or two ranges otherwise.
117- * <p>
115+ * <p/>
118116 * For example:
119117 * <ul>
120- * <li>{@code ]1,10]} unwraps to itself;</li>
121- * <li>{@code ]10,1]} unwraps to {@code ]10,min_token]} and {@code ]min_token,1]}.</li>
118+ * <li>{@code ]1,10]} unwraps to itself;</li>
119+ * <li>{@code ]10,1]} unwraps to {@code ]10,min_token]} and {@code ]min_token,1]}.</li>
122120 * </ul>
123- * <p>
121+ * <p/>
124122 * This is useful for CQL range queries, which do not handle wrapping:
125123 * <pre>
126124 * {@code
@@ -137,8 +135,8 @@
137135 public List<TokenRange> unwrap() {
138136 if (isWrappedAround()) {
139137 return ImmutableList.of(
140- new TokenRange(start, factory.minToken(), factory),
141- new TokenRange(factory.minToken(), end, factory));
138+ new TokenRange(start, factory.minToken(), factory),
139+ new TokenRange(factory.minToken(), end, factory));
142140 } else {
143141 return ImmutableList.of(this);
144142 }
@@ -146,11 +144,11 @@
146144
147145 /**
148146 * Returns whether this range intersects another one.
149- * <p>
147+ * <p/>
150148 * For example:
151149 * <ul>
152- * <li>{@code ]3,5]} intersects {@code ]1,4]}, {@code ]4,5]}...</li>
153- * <li>{@code ]3,5]} does not intersect {@code ]1,2]}, {@code ]2,3]}, {@code ]5,7]}...</li>
150+ * <li>{@code ]3,5]} intersects {@code ]1,4]}, {@code ]4,5]}...</li>
151+ * <li>{@code ]3,5]} does not intersect {@code ]1,2]}, {@code ]2,3]}, {@code ]5,7]}...</li>
154152 * </ul>
155153 *
156154 * @param that the other range.
@@ -162,17 +160,17 @@
162160 return false;
163161
164162 return this.contains(that.start, true)
165- || this.contains(that.end, false)
166- || that.contains(this.start, true)
167- || that.contains(this.end, false);
163+ || this.contains(that.end, false)
164+ || that.contains(this.start, true)
165+ || that.contains(this.end, false);
168166 }
169167
170168 /**
171169 * Computes the intersection of this range with another one.
172- * <p>
170+ * <p/>
173171 * If either of these ranges overlap the the ring, they are unwrapped and the unwrapped
174172 * tokens are compared with one another.
175- * <p>
173+ * <p/>
176174 * This call will fail if the two ranges do not intersect, you must check by calling
177175 * {@link #intersects(TokenRange)} beforehand.
178176 *
@@ -189,20 +187,20 @@
189187 // Compare the unwrapped ranges to one another.
190188 List<TokenRange> unwrappedForThis = this.unwrap();
191189 List<TokenRange> unwrappedForThat = that.unwrap();
192- for(TokenRange t1 : unwrappedForThis) {
193- for(TokenRange t2 : unwrappedForThat) {
194- if(t1.intersects(t2)) {
190+ for (TokenRange t1 : unwrappedForThis) {
191+ for (TokenRange t2 : unwrappedForThat) {
192+ if (t1.intersects(t2)) {
195193 intersected.add(new TokenRange(
196- (t1.contains(t2.start, true)) ? t2.start : t1.start,
197- (t1.contains(t2.end, false)) ? t2.end : t1.end,
198- factory));
194+ (t1.contains(t2.start, true)) ? t2.start : t1.start,
195+ (t1.contains(t2.end, false)) ? t2.end : t1.end,
196+ factory));
199197 }
200198 }
201199 }
202200
203201 // If two intersecting ranges were produced, merge them if they are adjacent.
204202 // This could happen in the case that two wrapped ranges intersected.
205- if(intersected.size() == 2) {
203+ if (intersected.size() == 2) {
206204 TokenRange t1 = intersected.get(0);
207205 TokenRange t2 = intersected.get(1);
208206 if (t1.end.equals(t2.start) || t2.end.equals(t1.start)) {
@@ -229,29 +227,28 @@
229227 private boolean contains(Token token, boolean isStart) {
230228 boolean isAfterStart = isStart ? token.compareTo(start) >= 0 : token.compareTo(start) > 0;
231229 boolean isBeforeEnd = end.equals(factory.minToken()) ||
232- (isStart ? token.compareTo(end) < 0 : token.compareTo(end) <= 0);
230+ (isStart ? token.compareTo(end) < 0 : token.compareTo(end) <= 0);
233231 return isWrappedAround()
234- ? isAfterStart || isBeforeEnd
235- : isAfterStart && isBeforeEnd;
232+ ? isAfterStart || isBeforeEnd
233+ : isAfterStart && isBeforeEnd;
236234 }
237235
238236 /**
239237 * Merges this range with another one.
240- * <p>
238+ * <p/>
241239 * The two ranges should either intersect or be adjacent; in other words, the merged range
242240 * should not include tokens that are in neither of the original ranges.
243- * <p>
241+ * <p/>
244242 * For example:
245243 * <ul>
246- * <li>merging {@code ]3,5]} with {@code ]4,7]} produces {@code ]3,7]};</li>
247- * <li>merging {@code ]3,5]} with {@code ]4,5]} produces {@code ]3,5]};</li>
248- * <li>merging {@code ]3,5]} with {@code ]5,8]} produces {@code ]3,8]};</li>
249- * <li>merging {@code ]3,5]} with {@code ]6,8]} fails.</li>
244+ * <li>merging {@code ]3,5]} with {@code ]4,7]} produces {@code ]3,7]};</li>
245+ * <li>merging {@code ]3,5]} with {@code ]4,5]} produces {@code ]3,5]};</li>
246+ * <li>merging {@code ]3,5]} with {@code ]5,8]} produces {@code ]3,8]};</li>
247+ * <li>merging {@code ]3,5]} with {@code ]6,8]} fails.</li>
250248 * </ul>
251249 *
252250 * @param that the other range.
253251 * @return the resulting range.
254- *
255252 * @throws IllegalArgumentException if the ranges neither intersect nor are adjacent.
256253 */
257254 public TokenRange mergeWith(TokenRange that) {
@@ -260,8 +257,8 @@
260257
261258 if (!(this.intersects(that) || this.end.equals(that.start) || that.end.equals(this.start)))
262259 throw new IllegalArgumentException(String.format(
263- "Can't merge %s with %s because they neither intersect nor are adjacent",
264- this, that));
260+ "Can't merge %s with %s because they neither intersect nor are adjacent",
261+ this, that));
265262
266263 if (this.isEmpty())
267264 return that;
@@ -279,8 +276,8 @@
279276
280277 // Starting at this.start, see how far we can go while staying in at least one of the ranges.
281278 Token mergedEnd = (thatStartsInThis && !this.contains(that.end, false))
282- ? that.end
283- : this.end;
279+ ? that.end
280+ : this.end;
284281
285282 // Repeat in the other direction.
286283 Token mergedStart = thisStartsInThat ? that.start : this.start;
@@ -297,9 +294,9 @@
297294 if (other == this)
298295 return true;
299296 if (other instanceof TokenRange) {
300- TokenRange that = (TokenRange)other;
297+ TokenRange that = (TokenRange) other;
301298 return Objects.equal(this.start, that.start) &&
302- Objects.equal(this.end, that.end);
299+ Objects.equal(this.end, that.end);
303300 }
304301 return false;
305302 }
@@ -314,8 +311,9 @@
314311 return String.format("]%s, %s]", start, end);
315312 }
316313
317- @Override public int compareTo(TokenRange other) {
318- if(this.equals(other)) {
314+ @Override
315+ public int compareTo(TokenRange other) {
316+ if (this.equals(other)) {
319317 return 0;
320318 } else {
321319 int compareStart = this.start.compareTo(other.start);
modified driver-core/src/main/java/com/datastax/driver/core/TransportException.java +3 −6
@@ -21,17 +21,14 @@
2121 * A connection exception that has to do with the transport itself, i.e. that
2222 * suggests the node is down.
2323 */
24-class TransportException extends ConnectionException
25-{
24+class TransportException extends ConnectionException {
2625 private static final long serialVersionUID = 0;
2726
28- public TransportException(InetSocketAddress address, String msg, Throwable cause)
29- {
27+ public TransportException(InetSocketAddress address, String msg, Throwable cause) {
3028 super(address, msg, cause);
3129 }
3230
33- public TransportException(InetSocketAddress address, String msg)
34- {
31+ public TransportException(InetSocketAddress address, String msg) {
3532 super(address, msg);
3633 }
3734 }
modified driver-core/src/main/java/com/datastax/driver/core/TupleType.java +13 −14
@@ -15,16 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
2019 import com.google.common.collect.ImmutableList;
2120 import com.google.common.reflect.TypeToken;
2221
23-import com.datastax.driver.core.exceptions.InvalidTypeException;
22+import java.util.Arrays;
23+import java.util.List;
2424
2525 /**
2626 * A tuple type.
27- * <p>
27+ * <p/>
2828 * A tuple type is a essentially a list of types.
2929 */
3030 public class TupleType extends DataType {
@@ -39,7 +39,7 @@
3939 @SuppressWarnings("unchecked")
4040 @Override
4141 TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
42- return (TypeCodec)TypeCodec.tupleOf(this);
42+ return (TypeCodec) TypeCodec.tupleOf(this);
4343 }
4444
4545 /**
@@ -74,21 +74,20 @@
7474 /**
7575 * Returns a new value for this tuple type that uses the provided values
7676 * for the components.
77- * <p>
77+ * <p/>
7878 * The numbers of values passed to this method must correspond to the
7979 * number of components in this tuple type. The {@code i}th parameter
8080 * value will then be assigned to the {@code i}th component of the resulting
8181 * tuple value.
8282 *
8383 * @param values the values to use for the component of the resulting
84- * tuple.
84+ * tuple.
8585 * @return a new tuple values based on the provided values.
86- *
8786 * @throws IllegalArgumentException if the number of {@code values}
88- * provided does not correspond to the number of components in this tuple
89- * type.
90- * @throws InvalidTypeException if any of the provided value is not of
91- * the correct type for the component.
87+ * provided does not correspond to the number of components in this tuple
88+ * type.
89+ * @throws InvalidTypeException if any of the provided value is not of
90+ * the correct type for the component.
9291 */
9392 public TupleValue newValue(Object... values) {
9493 if (values.length != types.size())
@@ -112,7 +111,7 @@
112111
113112 @Override
114113 public int hashCode() {
115- return Arrays.hashCode(new Object[]{ name, types });
114+ return Arrays.hashCode(new Object[]{name, types});
116115 }
117116
118117 @Override
@@ -120,7 +119,7 @@
120119 if (!(o instanceof TupleType))
121120 return false;
122121
123- TupleType d = (TupleType)o;
122+ TupleType d = (TupleType) o;
124123 return name == d.name && types.equals(d.types);
125124 }
126125
modified driver-core/src/main/java/com/datastax/driver/core/TupleValue.java +1 −4
@@ -15,9 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.List;
20-
2118 /**
2219 * A value for a Tuple.
2320 */
@@ -60,7 +57,7 @@
6057 if (!(o instanceof TupleValue))
6158 return false;
6259
63- TupleValue that = (TupleValue)o;
60+ TupleValue that = (TupleValue) o;
6461 if (!type.equals(that.type))
6562 return false;
6663
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +95 −82
@@ -15,6 +15,9 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.datastax.driver.core.utils.Bytes;
20+
1821 import java.math.BigDecimal;
1922 import java.math.BigInteger;
2023 import java.net.InetAddress;
@@ -28,57 +31,52 @@
2831 import java.util.*;
2932 import java.util.regex.Pattern;
3033
31-import com.datastax.driver.core.exceptions.InvalidTypeException;
32-import com.datastax.driver.core.utils.Bytes;
33-
3434 abstract class TypeCodec<T> {
3535
36- static final StringCodec utf8StringCodec = new StringCodec(Charset.forName("UTF-8"));
37- static final StringCodec asciiStringCodec = new StringCodec(Charset.forName("US-ASCII"));
38- static final LongCodec longCodec = new LongCodec();
39- static final BytesCodec bytesCodec = new BytesCodec();
40- static final BooleanCodec booleanCodec = new BooleanCodec();
41- static final DecimalCodec decimalCodec = new DecimalCodec();
42- static final DoubleCodec doubleCodec = new DoubleCodec();
43- static final FloatCodec floatCodec = new FloatCodec();
44- static final InetCodec inetCodec = new InetCodec();
45- static final IntCodec intCodec = new IntCodec();
46- static final DateCodec dateCodec = new DateCodec();
47- static final UUIDCodec uuidCodec = new UUIDCodec();
48- static final BigIntegerCodec bigIntegerCodec = new BigIntegerCodec();
49- static final TimeUUIDCodec timeUuidCodec = new TimeUUIDCodec();
36+ static final StringCodec utf8StringCodec = new StringCodec(Charset.forName("UTF-8"));
37+ static final StringCodec asciiStringCodec = new StringCodec(Charset.forName("US-ASCII"));
38+ static final LongCodec longCodec = new LongCodec();
39+ static final BytesCodec bytesCodec = new BytesCodec();
40+ static final BooleanCodec booleanCodec = new BooleanCodec();
41+ static final DecimalCodec decimalCodec = new DecimalCodec();
42+ static final DoubleCodec doubleCodec = new DoubleCodec();
43+ static final FloatCodec floatCodec = new FloatCodec();
44+ static final InetCodec inetCodec = new InetCodec();
45+ static final IntCodec intCodec = new IntCodec();
46+ static final DateCodec dateCodec = new DateCodec();
47+ static final UUIDCodec uuidCodec = new UUIDCodec();
48+ static final BigIntegerCodec bigIntegerCodec = new BigIntegerCodec();
49+ static final TimeUUIDCodec timeUuidCodec = new TimeUUIDCodec();
5050
5151 private static final Map<DataType.Name, TypeCodec<?>> primitiveCodecs = new EnumMap<DataType.Name, TypeCodec<?>>(DataType.Name.class);
5252
5353 static {
54- primitiveCodecs.put(DataType.Name.ASCII, asciiStringCodec);
55- primitiveCodecs.put(DataType.Name.BIGINT, longCodec);
56- primitiveCodecs.put(DataType.Name.BLOB, bytesCodec);
57- primitiveCodecs.put(DataType.Name.BOOLEAN, booleanCodec);
58- primitiveCodecs.put(DataType.Name.COUNTER, longCodec);
59- primitiveCodecs.put(DataType.Name.DECIMAL, decimalCodec);
60- primitiveCodecs.put(DataType.Name.DOUBLE, doubleCodec);
61- primitiveCodecs.put(DataType.Name.FLOAT, floatCodec);
62- primitiveCodecs.put(DataType.Name.INET, inetCodec);
63- primitiveCodecs.put(DataType.Name.INT, intCodec);
64- primitiveCodecs.put(DataType.Name.TEXT, utf8StringCodec);
54+ primitiveCodecs.put(DataType.Name.ASCII, asciiStringCodec);
55+ primitiveCodecs.put(DataType.Name.BIGINT, longCodec);
56+ primitiveCodecs.put(DataType.Name.BLOB, bytesCodec);
57+ primitiveCodecs.put(DataType.Name.BOOLEAN, booleanCodec);
58+ primitiveCodecs.put(DataType.Name.COUNTER, longCodec);
59+ primitiveCodecs.put(DataType.Name.DECIMAL, decimalCodec);
60+ primitiveCodecs.put(DataType.Name.DOUBLE, doubleCodec);
61+ primitiveCodecs.put(DataType.Name.FLOAT, floatCodec);
62+ primitiveCodecs.put(DataType.Name.INET, inetCodec);
63+ primitiveCodecs.put(DataType.Name.INT, intCodec);
64+ primitiveCodecs.put(DataType.Name.TEXT, utf8StringCodec);
6565 primitiveCodecs.put(DataType.Name.TIMESTAMP, dateCodec);
66- primitiveCodecs.put(DataType.Name.UUID, uuidCodec);
67- primitiveCodecs.put(DataType.Name.VARCHAR, utf8StringCodec);
68- primitiveCodecs.put(DataType.Name.VARINT, bigIntegerCodec);
69- primitiveCodecs.put(DataType.Name.TIMEUUID, timeUuidCodec);
70- primitiveCodecs.put(DataType.Name.CUSTOM, bytesCodec);
71- }
72-
73- private static class PrimitiveCollectionCodecs
74- {
66+ primitiveCodecs.put(DataType.Name.UUID, uuidCodec);
67+ primitiveCodecs.put(DataType.Name.VARCHAR, utf8StringCodec);
68+ primitiveCodecs.put(DataType.Name.VARINT, bigIntegerCodec);
69+ primitiveCodecs.put(DataType.Name.TIMEUUID, timeUuidCodec);
70+ primitiveCodecs.put(DataType.Name.CUSTOM, bytesCodec);
71+ }
72+
73+ private static class PrimitiveCollectionCodecs {
7574 public final Map<DataType.Name, TypeCodec<List<?>>> primitiveListsCodecs = new EnumMap<DataType.Name, TypeCodec<List<?>>>(DataType.Name.class);
7675 public final Map<DataType.Name, TypeCodec<Set<?>>> primitiveSetsCodecs = new EnumMap<DataType.Name, TypeCodec<Set<?>>>(DataType.Name.class);
7776 public final Map<DataType.Name, Map<DataType.Name, TypeCodec<Map<?, ?>>>> primitiveMapsCodecs = new EnumMap<DataType.Name, Map<DataType.Name, TypeCodec<Map<?, ?>>>>(DataType.Name.class);
7877
7978 @SuppressWarnings({"unchecked", "rawtypes"})
80- public PrimitiveCollectionCodecs(ProtocolVersion protocolVersion)
81- {
79+ public PrimitiveCollectionCodecs(ProtocolVersion protocolVersion) {
8280 for (Map.Entry<DataType.Name, TypeCodec<?>> entry : primitiveCodecs.entrySet()) {
8381 DataType.Name type = entry.getKey();
8482 TypeCodec<?> codec = entry.getValue();
@@ -113,32 +111,35 @@
113111 }
114112
115113
116- private TypeCodec() {}
114+ private TypeCodec() {
115+ }
117116
118117 public abstract T parse(String value);
118+
119119 public abstract String format(T value);
120120
121121 public abstract ByteBuffer serialize(T value);
122+
122123 public abstract T deserialize(ByteBuffer bytes);
123124
124125 @SuppressWarnings("unchecked")
125126 static <T> TypeCodec<T> createFor(DataType.Name name) {
126127 assert !name.isCollection();
127- return (TypeCodec<T>)primitiveCodecs.get(name);
128+ return (TypeCodec<T>) primitiveCodecs.get(name);
128129 }
129130
130131 @SuppressWarnings("unchecked")
131132 static <T> TypeCodec<List<T>> listOf(DataType arg, ProtocolVersion protocolVersion) {
132133 PrimitiveCollectionCodecs codecs = PrimitiveCollectionCodecs.forVersion(protocolVersion);
133134 TypeCodec<List<?>> codec = codecs.primitiveListsCodecs.get(arg.getName());
134- return codec != null ? (TypeCodec)codec : new ListCodec<Object>(arg.codec(protocolVersion), protocolVersion);
135+ return codec != null ? (TypeCodec) codec : new ListCodec<Object>(arg.codec(protocolVersion), protocolVersion);
135136 }
136137
137138 @SuppressWarnings("unchecked")
138139 static <T> TypeCodec<Set<T>> setOf(DataType arg, ProtocolVersion protocolVersion) {
139140 PrimitiveCollectionCodecs codecs = PrimitiveCollectionCodecs.forVersion(protocolVersion);
140141 TypeCodec<Set<?>> codec = codecs.primitiveSetsCodecs.get(arg.getName());
141- return codec != null ? (TypeCodec)codec : new SetCodec<Object>(arg.codec(protocolVersion), protocolVersion);
142+ return codec != null ? (TypeCodec) codec : new SetCodec<Object>(arg.codec(protocolVersion), protocolVersion);
142143 }
143144
144145 @SuppressWarnings("unchecked")
@@ -146,7 +147,7 @@
146147 PrimitiveCollectionCodecs codecs = PrimitiveCollectionCodecs.forVersion(protocolVersion);
147148 Map<DataType.Name, TypeCodec<Map<?, ?>>> valueCodecs = codecs.primitiveMapsCodecs.get(keys.getName());
148149 TypeCodec<Map<?, ?>> codec = valueCodecs == null ? null : valueCodecs.get(values.getName());
149- return codec != null ? (TypeCodec)codec : new MapCodec<Object, Object>(keys.codec(protocolVersion), values.codec(protocolVersion), protocolVersion);
150+ return codec != null ? (TypeCodec) codec : new MapCodec<Object, Object>(keys.codec(protocolVersion), values.codec(protocolVersion), protocolVersion);
150151 }
151152
152153 static UDTCodec udtOf(UserType definition) {
@@ -205,7 +206,7 @@
205206 return DataType.uuid();
206207
207208 if (value instanceof List) {
208- List<?> l = (List<?>)value;
209+ List<?> l = (List<?>) value;
209210 if (l.isEmpty())
210211 return DataType.list(DataType.blob());
211212 DataType eltType = getDataTypeFor(l.get(0));
@@ -213,7 +214,7 @@
213214 }
214215
215216 if (value instanceof Set) {
216- Set<?> s = (Set<?>)value;
217+ Set<?> s = (Set<?>) value;
217218 if (s.isEmpty())
218219 return DataType.set(DataType.blob());
219220 DataType eltType = getDataTypeFor(s.iterator().next());
@@ -221,15 +222,15 @@
221222 }
222223
223224 if (value instanceof Map) {
224- Map<?, ?> m = (Map<?, ?>)value;
225+ Map<?, ?> m = (Map<?, ?>) value;
225226 if (m.isEmpty())
226227 return DataType.map(DataType.blob(), DataType.blob());
227228 Map.Entry<?, ?> e = m.entrySet().iterator().next();
228229 DataType keyType = getDataTypeFor(e.getKey());
229230 DataType valueType = getDataTypeFor(e.getValue());
230231 return keyType == null || valueType == null
231- ? null
232- : DataType.map(keyType, valueType);
232+ ? null
233+ : DataType.map(keyType, valueType);
233234 }
234235
235236 if (value instanceof UDTValue) {
@@ -254,7 +255,7 @@
254255 writeCollectionSize(result, elements, version);
255256 for (ByteBuffer bb : buffers)
256257 writeCollectionValue(result, bb, version);
257- return (ByteBuffer)result.flip();
258+ return (ByteBuffer) result.flip();
258259 }
259260
260261 private static void writeCollectionSize(ByteBuffer output, int elements, ProtocolVersion version) {
@@ -263,7 +264,7 @@
263264 case V2:
264265 if (elements > 65535)
265266 throw new IllegalArgumentException("Native protocol version 2 supports up to 65535 elements in any collection - but collection contains " + elements + " elements");
266- output.putShort((short)elements);
267+ output.putShort((short) elements);
267268 break;
268269 case V3:
269270 output.putInt(elements);
@@ -307,7 +308,7 @@
307308 case V1:
308309 case V2:
309310 assert value != null;
310- output.putShort((short)value.remaining());
311+ output.putShort((short) value.remaining());
311312 output.put(value.duplicate());
312313 break;
313314 case V3:
@@ -391,7 +392,7 @@
391392 int nbMatch = 0;
392393 int start = -1;
393394 do {
394- start = text.indexOf(search, start+1);
395+ start = text.indexOf(search, start + 1);
395396 if (start != -1)
396397 ++nbMatch;
397398 } while (start != -1);
@@ -427,7 +428,8 @@
427428
428429 static class LongCodec extends TypeCodec<Long> {
429430
430- private LongCodec() {}
431+ private LongCodec() {
432+ }
431433
432434 @Override
433435 public Long parse(String value) {
@@ -469,7 +471,8 @@
469471
470472 static class BytesCodec extends TypeCodec<ByteBuffer> {
471473
472- private BytesCodec() {}
474+ private BytesCodec() {
475+ }
473476
474477 @Override
475478 public ByteBuffer parse(String value) {
@@ -496,7 +499,8 @@
496499 private static final ByteBuffer TRUE = ByteBuffer.wrap(new byte[]{1});
497500 private static final ByteBuffer FALSE = ByteBuffer.wrap(new byte[]{0});
498501
499- private BooleanCodec() {}
502+ private BooleanCodec() {
503+ }
500504
501505 @Override
502506 public Boolean parse(String value) {
@@ -537,7 +541,8 @@
537541
538542 static class DecimalCodec extends TypeCodec<BigDecimal> {
539543
540- private DecimalCodec() {}
544+ private DecimalCodec() {
545+ }
541546
542547 @Override
543548 public BigDecimal parse(String value) {
@@ -583,7 +588,8 @@
583588
584589 static class DoubleCodec extends TypeCodec<Double> {
585590
586- private DoubleCodec() {}
591+ private DoubleCodec() {
592+ }
587593
588594 @Override
589595 public Double parse(String value) {
@@ -625,7 +631,8 @@
625631
626632 static class FloatCodec extends TypeCodec<Float> {
627633
628- private FloatCodec() {}
634+ private FloatCodec() {
635+ }
629636
630637 @Override
631638 public Float parse(String value) {
@@ -667,7 +674,8 @@
667674
668675 static class InetCodec extends TypeCodec<InetAddress> {
669676
670- private InetCodec() {}
677+ private InetCodec() {
678+ }
671679
672680 @Override
673681 public InetAddress parse(String value) {
@@ -703,7 +711,8 @@
703711
704712 static class IntCodec extends TypeCodec<Integer> {
705713
706- private IntCodec() {}
714+ private IntCodec() {
715+ }
707716
708717 @Override
709718 public Integer parse(String value) {
@@ -745,26 +754,27 @@
745754
746755 static class DateCodec extends TypeCodec<Date> {
747756
748- private static final String[] iso8601Patterns = new String[] {
749- "yyyy-MM-dd HH:mm",
750- "yyyy-MM-dd HH:mm:ss",
751- "yyyy-MM-dd HH:mmZ",
752- "yyyy-MM-dd HH:mm:ssZ",
753- "yyyy-MM-dd HH:mm:ss.SSS",
754- "yyyy-MM-dd HH:mm:ss.SSSZ",
755- "yyyy-MM-dd'T'HH:mm",
756- "yyyy-MM-dd'T'HH:mmZ",
757- "yyyy-MM-dd'T'HH:mm:ss",
758- "yyyy-MM-dd'T'HH:mm:ssZ",
759- "yyyy-MM-dd'T'HH:mm:ss.SSS",
760- "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
761- "yyyy-MM-dd",
762- "yyyy-MM-ddZ"
757+ private static final String[] iso8601Patterns = new String[]{
758+ "yyyy-MM-dd HH:mm",
759+ "yyyy-MM-dd HH:mm:ss",
760+ "yyyy-MM-dd HH:mmZ",
761+ "yyyy-MM-dd HH:mm:ssZ",
762+ "yyyy-MM-dd HH:mm:ss.SSS",
763+ "yyyy-MM-dd HH:mm:ss.SSSZ",
764+ "yyyy-MM-dd'T'HH:mm",
765+ "yyyy-MM-dd'T'HH:mmZ",
766+ "yyyy-MM-dd'T'HH:mm:ss",
767+ "yyyy-MM-dd'T'HH:mm:ssZ",
768+ "yyyy-MM-dd'T'HH:mm:ss.SSS",
769+ "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
770+ "yyyy-MM-dd",
771+ "yyyy-MM-ddZ"
763772 };
764773
765774 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
766775
767- private DateCodec() {}
776+ private DateCodec() {
777+ }
768778
769779 /*
770780 * Copied and adapted from apache commons DateUtils.parseStrictly method (that is used Cassandra side
@@ -826,7 +836,8 @@
826836
827837 static class UUIDCodec extends TypeCodec<UUID> {
828838
829- protected UUIDCodec() {}
839+ protected UUIDCodec() {
840+ }
830841
831842 @Override
832843 public UUID parse(String value) {
@@ -858,7 +869,8 @@
858869
859870 static class TimeUUIDCodec extends UUIDCodec {
860871
861- private TimeUUIDCodec() {}
872+ private TimeUUIDCodec() {
873+ }
862874
863875 @Override
864876 public UUID parse(String value) {
@@ -879,7 +891,8 @@
879891
880892 static class BigIntegerCodec extends TypeCodec<BigInteger> {
881893
882- private BigIntegerCodec() {}
894+ private BigIntegerCodec() {
895+ }
883896
884897 @Override
885898 public BigInteger parse(String value) {
@@ -1213,7 +1226,7 @@
12131226 result.put(bb.duplicate());
12141227 }
12151228 }
1216- return (ByteBuffer)result.flip();
1229+ return (ByteBuffer) result.flip();
12171230 }
12181231
12191232 @Override
@@ -1297,7 +1310,7 @@
12971310 result.put(bb.duplicate());
12981311 }
12991312 }
1300- return (ByteBuffer)result.flip();
1313+ return (ByteBuffer) result.flip();
13011314 }
13021315
13031316 @Override
modified driver-core/src/main/java/com/datastax/driver/core/UDTValue.java +1 −1
@@ -57,7 +57,7 @@
5757 if (!(o instanceof UDTValue))
5858 return false;
5959
60- UDTValue that = (UDTValue)o;
60+ UDTValue that = (UDTValue) o;
6161 if (!definition.equals(that.definition))
6262 return false;
6363
modified driver-core/src/main/java/com/datastax/driver/core/UnsupportedProtocolVersionException.java +1 −2
@@ -29,8 +29,7 @@
2929 public final ProtocolVersion unsupportedVersion;
3030 public final ProtocolVersion serverVersion;
3131
32- public UnsupportedProtocolVersionException(InetSocketAddress address, ProtocolVersion unsupportedVersion, ProtocolVersion serverVersion)
33- {
32+ public UnsupportedProtocolVersionException(InetSocketAddress address, ProtocolVersion unsupportedVersion, ProtocolVersion serverVersion) {
3433 super(String.format("[%s] Host %s does not support protocol version %s but %s", address, address, unsupportedVersion, serverVersion));
3534 this.address = address;
3635 this.unsupportedVersion = unsupportedVersion;
modified driver-core/src/main/java/com/datastax/driver/core/UserType.java +23 −25
@@ -15,20 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
2019 import com.google.common.collect.ImmutableMap;
2120 import com.google.common.collect.Iterators;
2221 import com.google.common.reflect.TypeToken;
2322
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
23+import java.util.*;
2524
2625 /**
2726 * A User Defined Type (UDT).
28- * <p>
27+ * <p/>
2928 * A UDT is a essentially a named collection of fields (with a name and a type).
3029 */
31-public class UserType extends DataType implements Iterable<UserType.Field>{
30+public class UserType extends DataType implements Iterable<UserType.Field> {
3231
3332 private static final String TYPE_NAME = "type_name";
3433 private static final String COLS_NAMES = "field_names";
@@ -55,7 +54,7 @@
5554
5655 ImmutableMap.Builder<String, int[]> builder = new ImmutableMap.Builder<String, int[]>();
5756 for (int i = 0; i < byIdx.length; i++)
58- builder.put(byIdx[i].getName(), new int[]{ i });
57+ builder.put(byIdx[i].getName(), new int[]{i});
5958 this.byName = builder.build();
6059 }
6160
@@ -76,7 +75,7 @@
7675 @SuppressWarnings("unchecked")
7776 @Override
7877 TypeCodec<Object> codec(ProtocolVersion protocolVersion) {
79- return (TypeCodec)TypeCodec.udtOf(this);
78+ return (TypeCodec) TypeCodec.udtOf(this);
8079 }
8180
8281 /**
@@ -119,8 +118,8 @@
119118 * Returns whether this UDT contains a given field.
120119 *
121120 * @param name the name to check. Note that {@code name} obey the usual
122- * CQL identifier rules: it should be quoted if it denotes a case sensitive
123- * identifier (you can use {@link Metadata#quote} for the quoting).
121+ * CQL identifier rules: it should be quoted if it denotes a case sensitive
122+ * identifier (you can use {@link Metadata#quote} for the quoting).
124123 * @return {@code true} if this UDT contains a field named {@code name},
125124 * {@code false} otherwise.
126125 */
@@ -151,13 +150,12 @@
151150 * Returns the type of a given field.
152151 *
153152 * @param name the name of the field. Note that {@code name} obey the usual
154- * CQL identifier rules: it should be quoted if it denotes a case sensitive
155- * identifier (you can use {@link Metadata#quote} for the quoting).
153+ * CQL identifier rules: it should be quoted if it denotes a case sensitive
154+ * identifier (you can use {@link Metadata#quote} for the quoting).
156155 * @return the type of field {@code name} if this UDT has a field of this
157156 * name, {@code null} otherwise.
158- *
159157 * @throws IllegalArgumentException if {@code name} is not a field of this
160- * UDT definition.
158+ * UDT definition.
161159 */
162160 public DataType getFieldType(String name) {
163161 int[] idx = byName.get(Metadata.handleId(name));
@@ -188,22 +186,22 @@
188186
189187 @Override
190188 public final boolean equals(Object o) {
191- if(!(o instanceof UserType))
189+ if (!(o instanceof UserType))
192190 return false;
193191
194- UserType other = (UserType)o;
192+ UserType other = (UserType) o;
195193
196194 // Note: we don't test byName because it's redundant with byIdx in practice,
197195 // but also because the map holds 'int[]' which don't have proper equal.
198196 return name.equals(other.name)
199- && keyspace.equals(other.keyspace)
200- && typeName.equals(other.typeName)
201- && Arrays.equals(byIdx, other.byIdx);
197+ && keyspace.equals(other.keyspace)
198+ && typeName.equals(other.typeName)
199+ && Arrays.equals(byIdx, other.byIdx);
202200 }
203201
204202 /**
205203 * Returns a CQL query representing this user type in human readable form.
206- * <p>
204+ * <p/>
207205 * This method is equivalent to {@link #asCQLQuery} but the ouptut is
208206 * formatted to be human readable (for some definition of human readable).
209207 *
@@ -215,10 +213,10 @@
215213
216214 /**
217215 * Returns a CQL query representing this user type.
218- * <p>
216+ * <p/>
219217 * This method returns a single 'CREATE TYPE' query corresponding
220218 * to this UDT definition.
221- * <p>
219+ * <p/>
222220 * Note that the returned string is a single line; the returned query
223221 * is not formatted in any way.
224222 *
@@ -335,17 +333,17 @@
335333
336334 @Override
337335 public final int hashCode() {
338- return Arrays.hashCode(new Object[]{ name, type });
336+ return Arrays.hashCode(new Object[]{name, type});
339337 }
340338
341339 @Override
342340 public final boolean equals(Object o) {
343- if(!(o instanceof Field))
341+ if (!(o instanceof Field))
344342 return false;
345343
346- Field other = (Field)o;
344+ Field other = (Field) o;
347345 return name.equals(other.name)
348- && type.equals(other.type);
346+ && type.equals(other.type);
349347 }
350348
351349 @Override
modified driver-core/src/main/java/com/datastax/driver/core/VersionNumber.java +15 −16
@@ -15,17 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.base.Objects;
19+
1820 import java.util.Arrays;
1921 import java.util.Collections;
2022 import java.util.List;
21-import java.util.regex.Pattern;
2223 import java.util.regex.Matcher;
23-
24-import com.google.common.base.Objects;
24+import java.util.regex.Pattern;
2525
2626 /**
2727 * A version number in the form X.Y.Z with optional pre-release labels and build metadata.
28- * <p>
28+ * <p/>
2929 * Version numbers compare the usual way, the major number (X) is compared first, then the minor
3030 * one (Y) and then the patch level one (Z). Lastly, versions with pre-release sorts before the
3131 * versions that don't have one, and labels are sorted alphabetically if necessary. Build metadata
@@ -56,7 +56,7 @@
5656
5757 /**
5858 * Parse a version from a string.
59- * <p>
59+ * <p/>
6060 * The version string should have primarily the form X.Y.Z to which can be appended
6161 * one or more pre-release label after dashes (2.0.1-beta1, 2.1.4-rc1-SNAPSHOT)
6262 * and an optional build label (2.1.0-beta1+a20ba.sha). Out of convenience, the
@@ -64,9 +64,8 @@
6464 *
6565 * @param version the string to parse
6666 * @return the parsed version number.
67- *
6867 * @throws IllegalArgumentException if the provided string does not
69- * represent a valid version.
68+ * represent a valid version.
7069 */
7170 public static VersionNumber parse(String version) {
7271 if (version == null)
@@ -127,7 +126,7 @@
127126
128127 /**
129128 * The DSE patch version number (will only be present for version of Cassandra in DSE).
130- * <p>
129+ * <p/>
131130 * DataStax Entreprise (DSE) adds a fourth number to the version number to track potential
132131 * hot fixes and/or DSE specific patches that may have been applied to the Cassandra version.
133132 * In that case, this method return that fourth number.
@@ -161,7 +160,7 @@
161160
162161 /**
163162 * The next stable version, i.e. the version stripped of its pre-release labels and build metadata.
164- * <p>
163+ * <p/>
165164 * This is mostly used during our development stage, where we test the driver against pre-release
166165 * versions of Cassandra like 2.1.0-rc7-SNAPSHOT, but need to compare to the stable version 2.1.0
167166 * when testing for native protocol compatibility, etc.
@@ -218,18 +217,18 @@
218217
219218 @Override
220219 public boolean equals(Object o) {
221- if(!(o instanceof VersionNumber))
220+ if (!(o instanceof VersionNumber))
222221 return false;
223- VersionNumber that = (VersionNumber)o;
222+ VersionNumber that = (VersionNumber) o;
224223 if (major != that.major || minor != that.minor || patch != that.patch)
225224 return false;
226225
227226 return major == that.major
228- && minor == that.minor
229- && patch == that.patch
230- && dsePatch == that.dsePatch
231- && (preReleases == null ? that.preReleases == null : Arrays.equals(preReleases, that.preReleases))
232- && Objects.equal(build, that.build);
227+ && minor == that.minor
228+ && patch == that.patch
229+ && dsePatch == that.dsePatch
230+ && (preReleases == null ? that.preReleases == null : Arrays.equals(preReleases, that.preReleases))
231+ && Objects.equal(build, that.build);
233232 }
234233
235234 @Override
modified driver-core/src/main/java/com/datastax/driver/core/WriteType.java +14 −7
@@ -17,25 +17,32 @@
1717
1818 /**
1919 * The type of a Cassandra write query.
20- * <p>
20+ * <p/>
2121 * This information is returned by Cassandra when a write timeout is raised to
2222 * indicate what type of write timed out. This information is useful to decide
2323 * which retry policy to adopt.
2424 */
25-public enum WriteType
26-{
27- /** A write to a single partition key. Such writes are guaranteed to be atomic and isolated. */
25+public enum WriteType {
26+ /**
27+ * A write to a single partition key. Such writes are guaranteed to be atomic and isolated.
28+ */
2829 SIMPLE,
2930 /**
3031 * A write to a multiple partition key that used the distributed batch log to ensure atomicity
3132 * (atomicity meaning that if any statement in the batch succeeds, all will eventually succeed).
3233 */
3334 BATCH,
34- /** A write to a multiple partition key that doesn't use the distributed batch log. Atomicity for such writes is not guaranteed */
35+ /**
36+ * A write to a multiple partition key that doesn't use the distributed batch log. Atomicity for such writes is not guaranteed
37+ */
3538 UNLOGGED_BATCH,
36- /** A counter write (that can be for one or multiple partition key). Such write should not be replayed to avoid over-counting. */
39+ /**
40+ * A counter write (that can be for one or multiple partition key). Such write should not be replayed to avoid over-counting.
41+ */
3742 COUNTER,
38- /** The initial write to the distributed batch log that Cassandra performs internally before a BATCH write. */
43+ /**
44+ * The initial write to the distributed batch log that Cassandra performs internally before a BATCH write.
45+ */
3946 BATCH_LOG,
4047 /**
4148 * A conditional write. If a timeout has this {@code WriteType}, the timeout has happened while doing the compare-and-swap for
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/AlreadyExistsException.java +5 −5
@@ -114,13 +114,13 @@
114114 /**
115115 * Create a copy of this exception with a nicer stack trace, and including the coordinator
116116 * address that caused this exception to be raised.
117- * <p>
117+ * <p/>
118118 * This method is mainly intended for internal use by the driver and exists mainly because:
119119 * <ol>
120- * <li>the original exception was decoded from a response frame
121- * and at that time, the coordinator address was not available; and</li>
122- * <li>the newly-created exception will refer to the current thread in its stack trace,
123- * which generally yields a more user-friendly stack trace that the original one.</li>
120+ * <li>the original exception was decoded from a response frame
121+ * and at that time, the coordinator address was not available; and</li>
122+ * <li>the newly-created exception will refer to the current thread in its stack trace,
123+ * which generally yields a more user-friendly stack trace that the original one.</li>
124124 * </ol>
125125 *
126126 * @param address The full address of the host that caused this exception to be thrown.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/CoordinatorException.java +1 −2
@@ -26,12 +26,11 @@
2626
2727 /**
2828 * The coordinator host that caused this exception to be raised.
29- * <p>
29+ * <p/>
3030 * This is a shortcut for {@link InetSocketAddress#getAddress() getAddress().getAddress()}.
3131 *
3232 * @return The coordinator host that caused this exception to be raised;
3333 * may be {@code null} if the coordinator is not known.
34- *
3534 */
3635 InetAddress getHost();
3736
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverException.java +1 −1
@@ -40,7 +40,7 @@
4040
4141 /**
4242 * Copy the exception.
43- * <p>
43+ * <p/>
4444 * This return a new exception, equivalent to the original one, except that
4545 * because a new object is created in the current thread, the top-most
4646 * element in the stacktrace of the exception will refer to the current
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverInternalError.java +1 −1
@@ -17,7 +17,7 @@
1717
1818 /**
1919 * An unexpected error happened internally.
20- *
20+ * <p/>
2121 * This should never be raise and indicates a bug (either in the driver or in
2222 * Cassandra).
2323 */
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.java +1 −2
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18-import java.net.InetAddress;
1918 import java.net.InetSocketAddress;
2019
2120 /**
2221 * A specific invalid query exception that indicates that the query is invalid
2322 * because of some configuration problem.
24- * <p>
23+ * <p/>
2524 * This is generally throw by query that manipulate the schema (CREATE and
2625 * ALTER) when the required configuration options are invalid.
2726 */
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/NoHostAvailableException.java +8 −9
@@ -24,13 +24,13 @@
2424 /**
2525 * Exception thrown when a query cannot be performed because no host are
2626 * available.
27- *
27+ * <p/>
2828 * This exception is thrown if
2929 * <ul>
30- * <li>either there is no host live in the cluster at the moment of the query</li>
31- * <li>all host that have been tried have failed due to a connection problem</li>
30+ * <li>either there is no host live in the cluster at the moment of the query</li>
31+ * <li>all host that have been tried have failed due to a connection problem</li>
3232 * </ul>
33- *
33+ * <p/>
3434 * For debugging purpose, the list of hosts that have been tried along with the
3535 * failure cause can be retrieved using the {@link #errors} method.
3636 */
@@ -66,9 +66,9 @@
6666 /**
6767 * Builds a custom message for this exception.
6868 *
69- * @param maxErrors the maximum number of errors displayed (useful to limit the size of the message for big clusters). Beyond this limit,
70- * host names are still displayed, but not the associated errors. Set to {@code Integer.MAX_VALUE} to display all hosts.
71- * @param formatted whether to format the output (line break between each host).
69+ * @param maxErrors the maximum number of errors displayed (useful to limit the size of the message for big clusters). Beyond this limit,
70+ * host names are still displayed, but not the associated errors. Set to {@code Integer.MAX_VALUE} to display all hosts.
71+ * @param formatted whether to format the output (line break between each host).
7272 * @param includeStackTraces whether to include the full stacktrace of each host error. Note that this automatically implies
7373 * {@code formatted}.
7474 * @return the message.
@@ -96,8 +96,7 @@
9696
9797 int n = 0;
9898 boolean truncated = false;
99- for (Map.Entry<InetSocketAddress, Throwable> entry : errors.entrySet())
100- {
99+ for (Map.Entry<InetSocketAddress, Throwable> entry : errors.entrySet()) {
101100 if (n > 0) out.print(formatted ? "\n" : ", ");
102101 out.print(entry.getKey());
103102 if (n < maxErrorsInMessage) {
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryExecutionException.java +1 −1
@@ -17,7 +17,7 @@
1717
1818 /**
1919 * Exception related to the execution of a query.
20- *
20+ * <p/>
2121 * This correspond to the exception that Cassandra throw when a (valid) query
2222 * cannot be executed (TimeoutException, UnavailableException, ...).
2323 */
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryTimeoutException.java +3 −3
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import com.datastax.driver.core.ConsistencyLevel;
19+
1820 import java.net.InetAddress;
1921 import java.net.InetSocketAddress;
2022
21-import com.datastax.driver.core.ConsistencyLevel;
22-
2323 /**
2424 * A Cassandra timeout during a query.
25- *
25+ * <p/>
2626 * Such an exception is returned when the query has been tried by Cassandra but
2727 * cannot be achieved with the requested consistency level within the rpc
2828 * timeout set for Cassandra.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadTimeoutException.java +27 −27
@@ -15,10 +15,10 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18-import java.net.InetSocketAddress;
19-
2018 import com.datastax.driver.core.ConsistencyLevel;
2119
20+import java.net.InetSocketAddress;
21+
2222 /**
2323 * A Cassandra timeout during a read query.
2424 */
@@ -38,11 +38,11 @@
3838
3939 public ReadTimeoutException(InetSocketAddress address, ConsistencyLevel consistency, int received, int required, boolean dataPresent) {
4040 super(
41- address,
42- String.format("Cassandra timeout during read query at consistency %s (%s)", consistency, formatDetails(received, required, dataPresent)),
43- consistency,
44- received,
45- required
41+ address,
42+ String.format("Cassandra timeout during read query at consistency %s (%s)", consistency, formatDetails(received, required, dataPresent)),
43+ consistency,
44+ received,
45+ required
4646 );
4747 this.dataPresent = dataPresent;
4848 }
@@ -63,7 +63,7 @@
6363
6464 /**
6565 * Whether the actual data was amongst the received replica responses.
66- *
66+ * <p/>
6767 * During reads, Cassandra doesn't request data from every replica to
6868 * minimize internal network traffic. Instead, some replica are only asked
6969 * for a checksum of the data. A read timeout may occurred even if enough
@@ -80,26 +80,26 @@
8080 @Override
8181 public DriverException copy() {
8282 return new ReadTimeoutException(
83- getAddress(),
84- getMessage(),
85- this,
86- getConsistencyLevel(),
87- getReceivedAcknowledgements(),
88- getRequiredAcknowledgements(),
89- wasDataRetrieved()
83+ getAddress(),
84+ getMessage(),
85+ this,
86+ getConsistencyLevel(),
87+ getReceivedAcknowledgements(),
88+ getRequiredAcknowledgements(),
89+ wasDataRetrieved()
9090 );
9191 }
9292
9393 /**
9494 * Create a copy of this exception with a nicer stack trace, and including the coordinator
9595 * address that caused this exception to be raised.
96- * <p>
96+ * <p/>
9797 * This method is mainly intended for internal use by the driver and exists mainly because:
9898 * <ol>
99- * <li>the original exception was decoded from a response frame
100- * and at that time, the coordinator address was not available; and</li>
101- * <li>the newly-created exception will refer to the current thread in its stack trace,
102- * which generally yields a more user-friendly stack trace that the original one.</li>
99+ * <li>the original exception was decoded from a response frame
100+ * and at that time, the coordinator address was not available; and</li>
101+ * <li>the newly-created exception will refer to the current thread in its stack trace,
102+ * which generally yields a more user-friendly stack trace that the original one.</li>
103103 * </ol>
104104 *
105105 * @param address The full address of the host that caused this exception to be thrown.
@@ -107,13 +107,13 @@
107107 */
108108 public ReadTimeoutException copy(InetSocketAddress address) {
109109 return new ReadTimeoutException(
110- address,
111- getMessage(),
112- this,
113- getConsistencyLevel(),
114- getReceivedAcknowledgements(),
115- getRequiredAcknowledgements(),
116- wasDataRetrieved()
110+ address,
111+ getMessage(),
112+ this,
113+ getConsistencyLevel(),
114+ getReceivedAcknowledgements(),
115+ getRequiredAcknowledgements(),
116+ wasDataRetrieved()
117117 );
118118 }
119119
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnavailableException.java +7 −7
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import com.datastax.driver.core.ConsistencyLevel;
19+
1820 import java.net.InetAddress;
1921 import java.net.InetSocketAddress;
2022
21-import com.datastax.driver.core.ConsistencyLevel;
22-
2323 /**
2424 * Exception thrown when the coordinator knows there is not enough replica
2525 * alive to perform a query with the requested consistency level.
@@ -112,13 +112,13 @@
112112 /**
113113 * Create a copy of this exception with a nicer stack trace, and including the coordinator
114114 * address that caused this exception to be raised.
115- * <p>
115+ * <p/>
116116 * This method is mainly intended for internal use by the driver and exists mainly because:
117117 * <ol>
118- * <li>the original exception was decoded from a response frame
119- * and at that time, the coordinator address was not available; and</li>
120- * <li>the newly-created exception will refer to the current thread in its stack trace,
121- * which generally yields a more user-friendly stack trace that the original one.</li>
118+ * <li>the original exception was decoded from a response frame
119+ * and at that time, the coordinator address was not available; and</li>
120+ * <li>the newly-created exception will refer to the current thread in its stack trace,
121+ * which generally yields a more user-friendly stack trace that the original one.</li>
122122 * </ol>
123123 *
124124 * @param address The full address of the host that caused this exception to be thrown.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteTimeoutException.java +26 −26
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18-import java.net.InetSocketAddress;
19-
2018 import com.datastax.driver.core.ConsistencyLevel;
2119 import com.datastax.driver.core.WriteType;
2220
21+import java.net.InetSocketAddress;
22+
2323 /**
2424 * A Cassandra timeout during a write query.
2525 */
@@ -39,11 +39,11 @@
3939
4040 public WriteTimeoutException(InetSocketAddress address, ConsistencyLevel consistency, WriteType writeType, int received, int required) {
4141 super(
42- address,
43- String.format("Cassandra timeout during write query at consistency %s (%d replica were required but only %d acknowledged the write)", consistency, required, received),
44- consistency,
45- received,
46- required);
42+ address,
43+ String.format("Cassandra timeout during write query at consistency %s (%d replica were required but only %d acknowledged the write)", consistency, required, received),
44+ consistency,
45+ received,
46+ required);
4747 this.writeType = writeType;
4848 }
4949
@@ -64,26 +64,26 @@
6464 @Override
6565 public DriverException copy() {
6666 return new WriteTimeoutException(
67- getAddress(),
68- getMessage(),
69- this,
70- getConsistencyLevel(),
71- getWriteType(),
72- getReceivedAcknowledgements(),
73- getRequiredAcknowledgements()
67+ getAddress(),
68+ getMessage(),
69+ this,
70+ getConsistencyLevel(),
71+ getWriteType(),
72+ getReceivedAcknowledgements(),
73+ getRequiredAcknowledgements()
7474 );
7575 }
7676
7777 /**
7878 * Create a copy of this exception with a nicer stack trace, and including the coordinator
7979 * address that caused this exception to be raised.
80- * <p>
80+ * <p/>
8181 * This method is mainly intended for internal use by the driver and exists mainly because:
8282 * <ol>
83- * <li>the original exception was decoded from a response frame
84- * and at that time, the coordinator address was not available; and</li>
85- * <li>the newly-created exception will refer to the current thread in its stack trace,
86- * which generally yields a more user-friendly stack trace that the original one.</li>
83+ * <li>the original exception was decoded from a response frame
84+ * and at that time, the coordinator address was not available; and</li>
85+ * <li>the newly-created exception will refer to the current thread in its stack trace,
86+ * which generally yields a more user-friendly stack trace that the original one.</li>
8787 * </ol>
8888 *
8989 * @param address The full address of the host that caused this exception to be thrown.
@@ -91,13 +91,13 @@
9191 */
9292 public WriteTimeoutException copy(InetSocketAddress address) {
9393 return new WriteTimeoutException(
94- address,
95- getMessage(),
96- this,
97- getConsistencyLevel(),
98- getWriteType(),
99- getReceivedAcknowledgements(),
100- getRequiredAcknowledgements()
94+ address,
95+ getMessage(),
96+ this,
97+ getConsistencyLevel(),
98+ getWriteType(),
99+ getReceivedAcknowledgements(),
100+ getRequiredAcknowledgements()
101101 );
102102 }
103103
modified driver-core/src/main/java/com/datastax/driver/core/package-info.java +1 −1
@@ -15,7 +15,7 @@
1515 */
1616 /**
1717 * The main package for the DataStax Java driver for Cassandra.
18- * <p>
18+ * <p/>
1919 * The main entry for this package is the {@link com.datastax.driver.core.Cluster} class.
2020 */
2121 package com.datastax.driver.core;
modified driver-core/src/main/java/com/datastax/driver/core/policies/AddressTranslater.java +8 −8
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.net.InetSocketAddress;
19-
2018 import com.datastax.driver.core.Cluster;
2119
20+import java.net.InetSocketAddress;
21+
2222 /**
2323 * Translates IP addresses received from Cassandra nodes into locally queriable
2424 * addresses.
25- * <p>
25+ * <p/>
2626 * The driver auto-detect new Cassandra nodes added to the cluster through server
2727 * side pushed notifications and through checking the system tables. For each
2828 * node, the address the driver will receive will correspond to the address set as
@@ -35,7 +35,7 @@
3535 * pass by a router to reach that node). This interface allows to deal with
3636 * such cases, by allowing to translate an address as sent by a Cassandra node
3737 * to another address to be used by the driver for connection.
38- * <p>
38+ * <p/>
3939 * Please note that the contact points addresses provided while creating the
4040 * {@link Cluster} instance are not "tanslated", only IP address retrieve from or sent
4141 * by Cassandra nodes to the driver are.
@@ -46,10 +46,10 @@
4646 * Translates a Cassandra {@code rpc_address} to another address if necessary.
4747 *
4848 * @param address the address of a node as returned by Cassandra. Note that
49- * if the {@code rpc_address} of a node has been configured to {@code 0.0.0.0}
50- * server side, then the provided address will be the node {@code listen_address},
51- * *not* {@code 0.0.0.0}. Also note that the port for {@code InetSocketAddress}
52- * will always be the one set at Cluster construction time (9042 by default).
49+ * if the {@code rpc_address} of a node has been configured to {@code 0.0.0.0}
50+ * server side, then the provided address will be the node {@code listen_address},
51+ * *not* {@code 0.0.0.0}. Also note that the port for {@code InetSocketAddress}
52+ * will always be the one set at Cluster construction time (9042 by default).
5353 * @return the address the driver should actually use to connect to the node
5454 * designated by {@code address}. If the return is {@code null}, then {@code
5555 * address} will be used by the driver (it is thus equivalent to returing
modified driver-core/src/main/java/com/datastax/driver/core/policies/CloseableAddressTranslater.java +1 −1
@@ -20,7 +20,7 @@
2020 /**
2121 * Extends {@link AddressTranslater} for implementations that need to free some resources
2222 * at {@link Cluster} shutdown.
23- * <p>
23+ * <p/>
2424 * Note: the only reason {@link #close()} was not added directly to {@code AddressTranslater}
2525 * is backward-compatibility.
2626 */
modified driver-core/src/main/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicy.java +2 −2
@@ -17,14 +17,14 @@
1717
1818 /**
1919 * A load balancing policy that wants to be notified at cluster shutdown.
20- *
20+ * <p/>
2121 * The only reason that this is separate from {@link LoadBalancingPolicy} is to avoid breaking binary compatibility at the
2222 * time this was introduced (2.0.7 / 2.1.3). It might be merged with the parent interface in a future major version.
2323 */
2424 public interface CloseableLoadBalancingPolicy extends LoadBalancingPolicy {
2525 /**
2626 * Gets invoked at cluster shutdown.
27- *
27+ * <p/>
2828 * This gives the policy the opportunity to perform some cleanup, for instance stop threads that it might have started.
2929 */
3030 void close();
modified driver-core/src/main/java/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.java +6 −8
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.concurrent.atomic.AtomicInteger;
19-
20-import com.google.common.base.Preconditions;
21-
2218 import com.datastax.driver.core.Cluster;
2319 import com.datastax.driver.core.Host;
2420 import com.datastax.driver.core.Statement;
21+import com.google.common.base.Preconditions;
22+
23+import java.util.concurrent.atomic.AtomicInteger;
2524
2625 /**
2726 * A {@link SpeculativeExecutionPolicy} that schedules a given number of speculative executions, separated by a fixed delay.
@@ -33,16 +32,15 @@
3332 /**
3433 * Builds a new instance.
3534 *
36- * @param constantDelayMillis the delay between each speculative execution. Must be strictly positive.
35+ * @param constantDelayMillis the delay between each speculative execution. Must be strictly positive.
3736 * @param maxSpeculativeExecutions the number of speculative executions. Must be strictly positive.
38- *
3937 * @throws IllegalArgumentException if one of the arguments does not respect the preconditions above.
4038 */
4139 public ConstantSpeculativeExecutionPolicy(final long constantDelayMillis, final int maxSpeculativeExecutions) {
4240 Preconditions.checkArgument(constantDelayMillis > 0,
43- "delay must be strictly positive (was %d)", constantDelayMillis);
41+ "delay must be strictly positive (was %d)", constantDelayMillis);
4442 Preconditions.checkArgument(maxSpeculativeExecutions > 0,
45- "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions);
43+ "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions);
4644 this.constantDelayMillis = constantDelayMillis;
4745 this.maxSpeculativeExecutions = maxSpeculativeExecutions;
4846 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +26 −27
@@ -15,12 +15,7 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.*;
19-import java.util.concurrent.ConcurrentHashMap;
20-import java.util.concurrent.ConcurrentMap;
21-import java.util.concurrent.CopyOnWriteArrayList;
22-import java.util.concurrent.atomic.AtomicInteger;
23-
18+import com.datastax.driver.core.*;
2419 import com.google.common.annotations.VisibleForTesting;
2520 import com.google.common.base.Joiner;
2621 import com.google.common.base.Preconditions;
@@ -29,18 +24,22 @@
2924 import org.slf4j.Logger;
3025 import org.slf4j.LoggerFactory;
3126
32-import com.datastax.driver.core.*;
27+import java.util.*;
28+import java.util.concurrent.ConcurrentHashMap;
29+import java.util.concurrent.ConcurrentMap;
30+import java.util.concurrent.CopyOnWriteArrayList;
31+import java.util.concurrent.atomic.AtomicInteger;
3332
3433 /**
3534 * A data-center aware Round-robin load balancing policy.
36- * <p>
35+ * <p/>
3736 * This policy provides round-robin queries over the node of the local
3837 * data center. It also includes in the query plans returned a configurable
3938 * number of hosts in the remote data centers, but those are always tried
4039 * after the local nodes. In other words, this policy guarantees that no
4140 * host in a remote data center will be queried unless no host in the local
4241 * data center can be reached.
43- * <p>
42+ * <p/>
4443 * If used with a single data center, this policy is equivalent to the
4544 * {@link RoundRobinPolicy}, but its DC awareness incurs a slight overhead
4645 * so the latter should be preferred to this policy in that case.
@@ -158,16 +157,16 @@
158157
159158 @SuppressWarnings("unchecked")
160159 private static CopyOnWriteArrayList<Host> cloneList(CopyOnWriteArrayList<Host> list) {
161- return (CopyOnWriteArrayList<Host>)list.clone();
160+ return (CopyOnWriteArrayList<Host>) list.clone();
162161 }
163162
164163 /**
165164 * Return the HostDistance for the provided host.
166- * <p>
165+ * <p/>
167166 * This policy consider nodes in the local datacenter as {@code LOCAL}.
168167 * For each remote datacenter, it considers a configurable number of
169168 * hosts as {@code REMOTE} and the rest is {@code IGNORED}.
170- * <p>
169+ * <p/>
171170 * To configure how many host in each remote datacenter is considered
172171 * {@code REMOTE}, see {@link #DCAwareRoundRobinPolicy(String, int)}.
173172 *
@@ -187,13 +186,13 @@
187186 // We need to clone, otherwise our subList call is not thread safe
188187 dcHosts = cloneList(dcHosts);
189188 return dcHosts.subList(0, Math.min(dcHosts.size(), usedHostsPerRemoteDc)).contains(host)
190- ? HostDistance.REMOTE
191- : HostDistance.IGNORED;
189+ ? HostDistance.REMOTE
190+ : HostDistance.IGNORED;
192191 }
193192
194193 /**
195194 * Returns the hosts to use for a new query.
196- * <p>
195+ * <p/>
197196 * The returned plan will always try each known host in the local
198197 * datacenter first, and then, if none of the local host is reachable,
199198 * will try up to a configurable number of other host per remote datacenter.
@@ -201,8 +200,8 @@
201200 * Round-robin algorithm.
202201 *
203202 * @param loggedKeyspace the keyspace currently logged in on for this
204- * query.
205- * @param statement the query for which to build the plan.
203+ * query.
204+ * @param statement the query for which to build the plan.
206205 * @return a new query plan, i.e. an iterator indicating which host to
207206 * try first for querying, which one to use as failover, etc...
208207 */
@@ -245,8 +244,8 @@
245244 }
246245
247246 ConsistencyLevel cl = statement.getConsistencyLevel() == null
248- ? configuration.getQueryOptions().getConsistencyLevel()
249- : statement.getConsistencyLevel();
247+ ? configuration.getQueryOptions().getConsistencyLevel()
248+ : statement.getConsistencyLevel();
250249
251250 if (dontHopForLocalCL && cl.isDCLocal())
252251 return endOfData();
@@ -331,10 +330,10 @@
331330
332331 /**
333332 * Sets the name of the datacenter that will be considered "local" by the policy.
334- * <p>
333+ * <p/>
335334 * This must be the name as known by Cassandra (in other words, the name in that appears in
336335 * {@code system.peers}, or in the output of admin tools like nodetool).
337- * <p>
336+ * <p/>
338337 * If this method isn't called, the policy will default to the datacenter of the first node
339338 * connected to. This will always be ok if all the contact points use at {@code Cluster}
340339 * creation are in the local data-center. Otherwise, you should provide the name yourself
@@ -345,24 +344,24 @@
345344 */
346345 public Builder withLocalDc(String localDc) {
347346 Preconditions.checkArgument(!Strings.isNullOrEmpty(localDc),
348- "localDc name can't be null or empty. If you want to let the policy autodetect the datacenter, don't call Builder.withLocalDC");
347+ "localDc name can't be null or empty. If you want to let the policy autodetect the datacenter, don't call Builder.withLocalDC");
349348 this.localDc = localDc;
350349 return this;
351350 }
352351
353352 /**
354353 * Sets the number of hosts per remote datacenter that the policy should consider.
355- * <p>
354+ * <p/>
356355 * The policy's {@code distance()} method will return a {@code HostDistance.REMOTE} distance for only {@code usedHostsPerRemoteDc}
357356 * hosts per remote datacenter. Other hosts of the remote datacenters will be ignored (and thus no connections to them will be
358357 * maintained).
359- * <p>
358+ * <p/>
360359 * If {@code usedHostsPerRemoteDc > 0}, then if for a query no host in the local datacenter can be reached and if the consistency
361360 * level of the query is not {@code LOCAL_ONE} or {@code LOCAL_QUORUM}, then up to {@code usedHostsPerRemoteDc} hosts per remote
362361 * datacenter will be tried by the policy as a fallback. By default, no remote host will be used for {@code LOCAL_ONE} and
363362 * {@code LOCAL_QUORUM}, since this would change the meaning of the consistency level, somewhat breaking the consistency contract
364363 * (this can be overridden with {@link #allowRemoteDCsForLocalConsistencyLevel()}).
365- * <p>
364+ * <p/>
366365 * If this method isn't called, the policy will default to 0.
367366 *
368367 * @param usedHostsPerRemoteDc the number.
@@ -370,7 +369,7 @@
370369 */
371370 public Builder withUsedHostsPerRemoteDc(int usedHostsPerRemoteDc) {
372371 Preconditions.checkArgument(usedHostsPerRemoteDc >= 0,
373- "usedHostsPerRemoteDc must be equal or greater than 0");
372+ "usedHostsPerRemoteDc must be equal or greater than 0");
374373 this.usedHostsPerRemoteDc = usedHostsPerRemoteDc;
375374 return this;
376375 }
@@ -378,7 +377,7 @@
378377 /**
379378 * Allows the policy to return remote hosts when building query plans for queries having consistency level {@code LOCAL_ONE}
380379 * or {@code LOCAL_QUORUM}.
381- * <p>
380+ * <p/>
382381 * When used in conjunction with {@link #withUsedHostsPerRemoteDc(int) usedHostsPerRemoteDc} > 0, this overrides the policy of
383382 * never using remote datacenter nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is however inadvisable to do
384383 * so in almost all cases, as this would potentially break consistency guarantees and if you are fine with that, it's probably
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +32 −31
@@ -21,16 +21,16 @@
2121
2222 /**
2323 * The default retry policy.
24- * <p>
24+ * <p/>
2525 * This policy retries queries in only two cases:
2626 * <ul>
27- * <li>On a read timeout, if enough replicas replied but data was not retrieved.</li>
28- * <li>On a write timeout, if we timeout while writing the distributed log used by batch statements.</li>
27+ * <li>On a read timeout, if enough replicas replied but data was not retrieved.</li>
28+ * <li>On a write timeout, if we timeout while writing the distributed log used by batch statements.</li>
2929 * </ul>
30- * <p>
30+ * <p/>
3131 * This retry policy is conservative in that it will never retry with a
3232 * different consistency level than the one of the initial operation.
33- * <p>
33+ * <p/>
3434 * In some cases, it may be convenient to use a more aggressive retry policy
3535 * like {@link DowngradingConsistencyRetryPolicy}.
3636 */
@@ -38,11 +38,12 @@
3838
3939 public static final DefaultRetryPolicy INSTANCE = new DefaultRetryPolicy();
4040
41- private DefaultRetryPolicy() {}
41+ private DefaultRetryPolicy() {
42+ }
4243
4344 /**
4445 * Defines whether to retry and at which consistency level on a read timeout.
45- * <p>
46+ * <p/>
4647 * This method triggers a maximum of one retry, and only if enough
4748 * replicas had responded to the read request but data was not retrieved
4849 * amongst those. Indeed, that case usually means that enough replica
@@ -52,15 +53,15 @@
5253 * timeout the dead replica will likely have been detected as dead and
5354 * the retry has a high chance of success.
5455 *
55- * @param statement the original query that timed out.
56- * @param cl the original consistency level of the read that timed out.
56+ * @param statement the original query that timed out.
57+ * @param cl the original consistency level of the read that timed out.
5758 * @param requiredResponses the number of responses that were required to
58- * achieve the requested consistency level.
59+ * achieve the requested consistency level.
5960 * @param receivedResponses the number of responses that had been received
60- * by the time the timeout exception was raised.
61- * @param dataRetrieved whether actual data (by opposition to data checksum)
62- * was present in the received responses.
63- * @param nbRetry the number of retries already performed for this operation.
61+ * by the time the timeout exception was raised.
62+ * @param dataRetrieved whether actual data (by opposition to data checksum)
63+ * was present in the received responses.
64+ * @param nbRetry the number of retries already performed for this operation.
6465 * @return {@code RetryDecision.retry(cl)} if no retry attempt has yet been tried and
6566 * {@code receivedResponses >= requiredResponses && !dataRetrieved}, {@code RetryDecision.rethrow()} otherwise.
6667 */
@@ -74,7 +75,7 @@
7475
7576 /**
7677 * Defines whether to retry and at which consistency level on a write timeout.
77- * <p>
78+ * <p/>
7879 * This method triggers a maximum of one retry, and only in the case of
7980 * a {@code WriteType.BATCH_LOG} write. The reasoning for the retry in
8081 * that case is that write to the distributed batch log is tried by the
@@ -85,14 +86,14 @@
8586 * nodes will likely have been detected as dead and the retry has thus a
8687 * high chance of success.
8788 *
88- * @param statement the original query that timed out.
89- * @param cl the original consistency level of the write that timed out.
90- * @param writeType the type of the write that timed out.
89+ * @param statement the original query that timed out.
90+ * @param cl the original consistency level of the write that timed out.
91+ * @param writeType the type of the write that timed out.
9192 * @param requiredAcks the number of acknowledgments that were required to
92- * achieve the requested consistency level.
93+ * achieve the requested consistency level.
9394 * @param receivedAcks the number of acknowledgments that had been received
94- * by the time the timeout exception was raised.
95- * @param nbRetry the number of retry already performed for this operation.
95+ * by the time the timeout exception was raised.
96+ * @param nbRetry the number of retry already performed for this operation.
9697 * @return {@code RetryDecision.retry(cl)} if no retry attempt has yet been tried and
9798 * {@code writeType == WriteType.BATCH_LOG}, {@code RetryDecision.rethrow()} otherwise.
9899 */
@@ -108,7 +109,7 @@
108109 /**
109110 * Defines whether to retry and at which consistency level on an
110111 * unavailable exception.
111- * <p>
112+ * <p/>
112113 * This method triggers a retry iff no retry has been executed before
113114 * (nbRetry == 0), with
114115 * {@link RetryPolicy.RetryDecision#tryNextHost(ConsistencyLevel) RetryDecision.tryNextHost(cl)},
@@ -119,20 +120,20 @@
119120 * be "network" isolated from all the other nodes but can still answer to
120121 * the client, it makes sense to retry the query on another node.
121122 *
122- * @param statement the original query for which the consistency level cannot
123- * be achieved.
124- * @param cl the original consistency level for the operation.
123+ * @param statement the original query for which the consistency level cannot
124+ * be achieved.
125+ * @param cl the original consistency level for the operation.
125126 * @param requiredReplica the number of replica that should have been
126- * (known) alive for the operation to be attempted.
127- * @param aliveReplica the number of replica that were know to be alive by
128- * the coordinator of the operation.
129- * @param nbRetry the number of retry already performed for this operation.
127+ * (known) alive for the operation to be attempted.
128+ * @param aliveReplica the number of replica that were know to be alive by
129+ * the coordinator of the operation.
130+ * @param nbRetry the number of retry already performed for this operation.
130131 * @return {@code RetryDecision.rethrow()}.
131132 */
132133 @Override
133134 public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
134135 return (nbRetry == 0)
135- ? RetryDecision.tryNextHost(cl)
136- : RetryDecision.rethrow();
136+ ? RetryDecision.tryNextHost(cl)
137+ : RetryDecision.rethrow();
137138 }
138139 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +44 −43
@@ -22,7 +22,7 @@
2222 /**
2323 * A retry policy that sometimes retry with a lower consistency level than
2424 * the one initially requested.
25- * <p>
25+ * <p/>
2626 * <b>BEWARE</b>: This policy may retry queries using a lower consistency
2727 * level than the one initially requested. By doing so, it may break
2828 * consistency guarantees. In other words, if you use this retry policy,
@@ -32,34 +32,34 @@
3232 * are ok with that. It is also highly recommended to always wrap this
3333 * policy into {@link LoggingRetryPolicy} to log the occurrences of
3434 * such consistency break.
35- * <p>
35+ * <p/>
3636 * This policy implements the same retries than the {@link DefaultRetryPolicy}
3737 * policy. But on top of that, it also retries in the following cases:
3838 * <ul>
39- * <li>On a read timeout: if the number of replica that responded is
40- * greater than one but lower than is required by the requested
41- * consistency level, the operation is retried at a lower consistency
42- * level.</li>
43- * <li>On a write timeout: if the operation is an {@code
44- * WriteType.UNLOGGED_BATCH} and at least one replica acknowledged the
45- * write, the operation is retried at a lower consistency level.
46- * Furthermore, for other operation, if at least one replica acknowledged
47- * the write, the timeout is ignored.</li>
48- * <li>On an unavailable exception: if at least one replica is alive, the
49- * operation is retried at a lower consistency level.</li>
39+ * <li>On a read timeout: if the number of replica that responded is
40+ * greater than one but lower than is required by the requested
41+ * consistency level, the operation is retried at a lower consistency
42+ * level.</li>
43+ * <li>On a write timeout: if the operation is an {@code
44+ * WriteType.UNLOGGED_BATCH} and at least one replica acknowledged the
45+ * write, the operation is retried at a lower consistency level.
46+ * Furthermore, for other operation, if at least one replica acknowledged
47+ * the write, the timeout is ignored.</li>
48+ * <li>On an unavailable exception: if at least one replica is alive, the
49+ * operation is retried at a lower consistency level.</li>
5050 * </ul>
51- * <p>
51+ * <p/>
5252 * The reasoning being this retry policy is the following one. If, based
5353 * on the information the Cassandra coordinator node returns, retrying the
5454 * operation with the initially requested consistency has a change to
5555 * succeed, do it. Otherwise, if based on these information we know <b>the
5656 * initially requested consistency level cannot be achieve currently</b>, then:
5757 * <ul>
58- * <li>For writes, ignore the exception (thus silently failing the
59- * consistency requirement) if we know the write has been persisted on at
60- * least one replica.</li>
61- * <li>For reads, try reading at a lower consistency level (thus silently
62- * failing the consistency requirement).</li>
58+ * <li>For writes, ignore the exception (thus silently failing the
59+ * consistency requirement) if we know the write has been persisted on at
60+ * least one replica.</li>
61+ * <li>For reads, try reading at a lower consistency level (thus silently
62+ * failing the consistency requirement).</li>
6363 * </ul>
6464 * In other words, this policy implements the idea that if the requested
6565 * consistency level cannot be achieved, the next best thing for writes is
@@ -70,7 +70,8 @@
7070
7171 public static final DowngradingConsistencyRetryPolicy INSTANCE = new DowngradingConsistencyRetryPolicy();
7272
73- private DowngradingConsistencyRetryPolicy() {}
73+ private DowngradingConsistencyRetryPolicy() {
74+ }
7475
7576 private RetryDecision maxLikelyToWorkCL(int knownOk) {
7677 if (knownOk >= 3)
@@ -85,7 +86,7 @@
8586
8687 /**
8788 * Defines whether to retry and at which consistency level on a read timeout.
88- * <p>
89+ * <p/>
8990 * This method triggers a maximum of one retry. If less replica
9091 * responded than required by the consistency level (but at least one
9192 * replica did respond), the operation is retried at a lower
@@ -93,15 +94,15 @@
9394 * retrieve, the operation is retried with the initial consistency
9495 * level. Otherwise, an exception is thrown.
9596 *
96- * @param statement the original query that timed out.
97- * @param cl the original consistency level of the read that timed out.
97+ * @param statement the original query that timed out.
98+ * @param cl the original consistency level of the read that timed out.
9899 * @param requiredResponses the number of responses that were required to
99- * achieve the requested consistency level.
100+ * achieve the requested consistency level.
100101 * @param receivedResponses the number of responses that had been received
101- * by the time the timeout exception was raised.
102- * @param dataRetrieved whether actual data (by opposition to data checksum)
103- * was present in the received responses.
104- * @param nbRetry the number of retry already performed for this operation.
102+ * by the time the timeout exception was raised.
103+ * @param dataRetrieved whether actual data (by opposition to data checksum)
104+ * was present in the received responses.
105+ * @param nbRetry the number of retry already performed for this operation.
105106 * @return a RetryDecision as defined above.
106107 */
107108 @Override
@@ -126,7 +127,7 @@
126127
127128 /**
128129 * Defines whether to retry and at which consistency level on a write timeout.
129- * <p>
130+ * <p/>
130131 * This method triggers a maximum of one retry. If {@code writeType ==
131132 * WriteType.BATCH_LOG}, the write is retried with the initial
132133 * consistency level. If {@code writeType == WriteType.UNLOGGED_BATCH}
@@ -137,14 +138,14 @@
137138 * and {@code WriteType.BATCH}), if we know the write has been persisted on at
138139 * least one replica, we ignore the exception. Otherwise, an exception is thrown.
139140 *
140- * @param statement the original query that timed out.
141- * @param cl the original consistency level of the write that timed out.
142- * @param writeType the type of the write that timed out.
141+ * @param statement the original query that timed out.
142+ * @param cl the original consistency level of the write that timed out.
143+ * @param writeType the type of the write that timed out.
143144 * @param requiredAcks the number of acknowledgments that were required to
144- * achieve the requested consistency level.
145+ * achieve the requested consistency level.
145146 * @param receivedAcks the number of acknowledgments that had been received
146- * by the time the timeout exception was raised.
147- * @param nbRetry the number of retry already performed for this operation.
147+ * by the time the timeout exception was raised.
148+ * @param nbRetry the number of retry already performed for this operation.
148149 * @return a RetryDecision as defined above.
149150 */
150151 @Override
@@ -171,19 +172,19 @@
171172 /**
172173 * Defines whether to retry and at which consistency level on an
173174 * unavailable exception.
174- * <p>
175+ * <p/>
175176 * This method triggers a maximum of one retry. If at least one replica
176177 * is know to be alive, the operation is retried at a lower consistency
177178 * level.
178179 *
179- * @param statement the original query for which the consistency level cannot
180- * be achieved.
181- * @param cl the original consistency level for the operation.
180+ * @param statement the original query for which the consistency level cannot
181+ * be achieved.
182+ * @param cl the original consistency level for the operation.
182183 * @param requiredReplica the number of replica that should have been
183- * (known) alive for the operation to be attempted.
184- * @param aliveReplica the number of replica that were know to be alive by
185- * the coordinator of the operation.
186- * @param nbRetry the number of retry already performed for this operation.
184+ * (known) alive for the operation to be attempted.
185+ * @param aliveReplica the number of replica that were know to be alive by
186+ * the coordinator of the operation.
187+ * @param nbRetry the number of retry already performed for this operation.
187188 * @return a RetryDecision as defined above.
188189 */
189190 @Override
modified driver-core/src/main/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslater.java +14 −15
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.net.InetAddress;
19-import java.net.InetSocketAddress;
20-import java.util.Enumeration;
21-import java.util.Hashtable;
22-
18+import com.datastax.driver.core.exceptions.DriverException;
2319 import com.google.common.annotations.VisibleForTesting;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+
2423 import javax.naming.Context;
2524 import javax.naming.NamingEnumeration;
2625 import javax.naming.NamingException;
@@ -28,22 +27,22 @@
2827 import javax.naming.directory.Attributes;
2928 import javax.naming.directory.DirContext;
3029 import javax.naming.directory.InitialDirContext;
31-import org.slf4j.Logger;
32-import org.slf4j.LoggerFactory;
33-
34-import com.datastax.driver.core.exceptions.DriverException;
30+import java.net.InetAddress;
31+import java.net.InetSocketAddress;
32+import java.util.Enumeration;
33+import java.util.Hashtable;
3534
3635 /**
3736 * {@link AddressTranslater} implementation for a multi-region EC2 deployment <b>where clients are also deployed in EC2</b>.
38- * <p>
37+ * <p/>
3938 * Its distinctive feature is that it translates addresses according to the location of the Cassandra host:
4039 * <ul>
4140 * <li>addresses in different EC2 regions (than the client) are unchanged;</li>
4241 * <li>addresses in the same EC2 region are <b>translated to private IPs</b>.</li>
4342 * </ul>
4443 * This optimizes network costs, because Amazon charges more for communication over public IPs.
45- *
46- * <p>
44+ * <p/>
45+ * <p/>
4746 * Implementation note: this class performs a reverse DNS lookup of the origin address, to find the domain name of the target
4847 * instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the private/public switch automatically
4948 * based on location.
@@ -93,9 +92,9 @@
9392 }
9493
9594 private String lookupPtrRecord(String reversedDomain) throws Exception {
96- Attributes attrs = ctx.getAttributes(reversedDomain, new String[]{ "PTR" });
95+ Attributes attrs = ctx.getAttributes(reversedDomain, new String[]{"PTR"});
9796 for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements(); ) {
98- Attribute attr = (Attribute)ae.next();
97+ Attribute attr = (Attribute) ae.next();
9998 for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements(); )
10099 return vals.nextElement().toString();
101100 }
@@ -136,7 +135,7 @@
136135 int lowNibble = b & 0x0F;
137136 int highNibble = b >> 4 & 0x0F;
138137 builder.append(Integer.toHexString(lowNibble)).append('.')
139- .append(Integer.toHexString(highNibble)).append('.');
138+ .append(Integer.toHexString(highNibble)).append('.');
140139 }
141140 builder.append("ip6.arpa");
142141 return builder.toString();
modified driver-core/src/main/java/com/datastax/driver/core/policies/ExponentialReconnectionPolicy.java +3 −3
@@ -30,8 +30,8 @@
3030 * Creates a reconnection policy waiting exponentially longer for each new attempt.
3131 *
3232 * @param baseDelayMs the base delay in milliseconds to use for
33- * the schedules created by this policy.
34- * @param maxDelayMs the maximum delay to wait between two attempts.
33+ * the schedules created by this policy.
34+ * @param maxDelayMs the maximum delay to wait between two attempts.
3535 */
3636 public ExponentialReconnectionPolicy(long baseDelayMs, long maxDelayMs) {
3737 if (baseDelayMs < 0 || maxDelayMs < 0)
@@ -71,7 +71,7 @@
7171
7272 /**
7373 * A new schedule that used an exponentially growing delay between reconnection attempts.
74- * <p>
74+ * <p/>
7575 * For this schedule, reconnection attempt {@code i} will be tried
7676 * {@code Math.min(2^(i-1) * getBaseDelayMs(), getMaxDelayMs())} milliseconds after the previous one.
7777 *
modified driver-core/src/main/java/com/datastax/driver/core/policies/FallthroughRetryPolicy.java +23 −22
@@ -21,7 +21,7 @@
2121
2222 /**
2323 * A retry policy that never retry (nor ignore).
24- * <p>
24+ * <p/>
2525 * All of the methods of this retry policy unconditionally return {@link RetryPolicy.RetryDecision#rethrow}.
2626 * If this policy is used, retry will have to be implemented in business code.
2727 */
@@ -29,20 +29,21 @@
2929
3030 public static final FallthroughRetryPolicy INSTANCE = new FallthroughRetryPolicy();
3131
32- private FallthroughRetryPolicy() {}
32+ private FallthroughRetryPolicy() {
33+ }
3334
3435 /**
3536 * Defines whether to retry and at which consistency level on a read timeout.
3637 *
37- * @param statement the original query that timed out.
38- * @param cl the original consistency level of the read that timed out.
38+ * @param statement the original query that timed out.
39+ * @param cl the original consistency level of the read that timed out.
3940 * @param requiredResponses the number of responses that were required to
40- * achieve the requested consistency level.
41+ * achieve the requested consistency level.
4142 * @param receivedResponses the number of responses that had been received
42- * by the time the timeout exception was raised.
43- * @param dataRetrieved whether actual data (by opposition to data checksum)
44- * was present in the received responses.
45- * @param nbRetry the number of retry already performed for this operation.
43+ * by the time the timeout exception was raised.
44+ * @param dataRetrieved whether actual data (by opposition to data checksum)
45+ * was present in the received responses.
46+ * @param nbRetry the number of retry already performed for this operation.
4647 * @return {@code RetryDecision.rethrow()}.
4748 */
4849 @Override
@@ -53,14 +54,14 @@
5354 /**
5455 * Defines whether to retry and at which consistency level on a write timeout.
5556 *
56- * @param statement the original query that timed out.
57- * @param cl the original consistency level of the write that timed out.
58- * @param writeType the type of the write that timed out.
57+ * @param statement the original query that timed out.
58+ * @param cl the original consistency level of the write that timed out.
59+ * @param writeType the type of the write that timed out.
5960 * @param requiredAcks the number of acknowledgments that were required to
60- * achieve the requested consistency level.
61+ * achieve the requested consistency level.
6162 * @param receivedAcks the number of acknowledgments that had been received
62- * by the time the timeout exception was raised.
63- * @param nbRetry the number of retry already performed for this operation.
63+ * by the time the timeout exception was raised.
64+ * @param nbRetry the number of retry already performed for this operation.
6465 * @return {@code RetryDecision.rethrow()}.
6566 */
6667 @Override
@@ -72,14 +73,14 @@
7273 * Defines whether to retry and at which consistency level on an
7374 * unavailable exception.
7475 *
75- * @param statement the original query for which the consistency level cannot
76- * be achieved.
77- * @param cl the original consistency level for the operation.
76+ * @param statement the original query for which the consistency level cannot
77+ * be achieved.
78+ * @param cl the original consistency level for the operation.
7879 * @param requiredReplica the number of replica that should have been
79- * (known) alive for the operation to be attempted.
80- * @param aliveReplica the number of replica that were know to be alive by
81- * the coordinator of the operation.
82- * @param nbRetry the number of retry already performed for this operation.
80+ * (known) alive for the operation to be attempted.
81+ * @param aliveReplica the number of replica that were know to be alive by
82+ * the coordinator of the operation.
83+ * @param nbRetry the number of retry already performed for this operation.
8384 * @return {@code RetryDecision.rethrow()}.
8485 */
8586 @Override
modified driver-core/src/main/java/com/datastax/driver/core/policies/HostFilterPolicy.java +18 −22
@@ -15,25 +15,23 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.net.InetSocketAddress;
19-import java.util.ArrayList;
20-import java.util.Collection;
21-import java.util.Iterator;
22-import java.util.List;
23-
24-import com.google.common.base.Predicate;
25-import com.google.common.base.Predicates;
26-import com.google.common.collect.ImmutableSet;
27-
2818 import com.datastax.driver.core.Cluster;
2919 import com.datastax.driver.core.Host;
3020 import com.datastax.driver.core.HostDistance;
3121 import com.datastax.driver.core.Statement;
22+import com.google.common.base.Predicate;
23+import com.google.common.base.Predicates;
24+import com.google.common.collect.ImmutableSet;
25+
26+import java.util.ArrayList;
27+import java.util.Collection;
28+import java.util.Iterator;
29+import java.util.List;
3230
3331 /**
3432 * A load balancing policy wrapper that ensures that only hosts matching the predicate
3533 * will ever be returned.
36- * <p>
34+ * <p/>
3735 * This policy wraps another load balancing policy and will delegate the choice
3836 * of hosts to the wrapped policy with the exception that only hosts matching
3937 * the predicate provided when constructing this policy will ever be
@@ -49,8 +47,8 @@
4947 * matching the predicate.
5048 *
5149 * @param childPolicy the wrapped policy.
52- * @param predicate the host predicate. Only hosts matching this predicate may get connected
53- * to (whether they will get connected to or not depends on the child policy).
50+ * @param predicate the host predicate. Only hosts matching this predicate may get connected
51+ * to (whether they will get connected to or not depends on the child policy).
5452 */
5553 public HostFilterPolicy(LoadBalancingPolicy childPolicy, Predicate<Host> predicate) {
5654 this.childPolicy = childPolicy;
@@ -66,7 +64,7 @@
6664 * {@inheritDoc}
6765 *
6866 * @throws IllegalArgumentException if none of the host in {@code hosts}
69- * (which will correspond to the contact points) matches the predicate.
67+ * (which will correspond to the contact points) matches the predicate.
7068 */
7169 @Override
7270 public void init(Cluster cluster, Collection<Host> hosts) {
@@ -90,13 +88,13 @@
9088 @Override
9189 public HostDistance distance(Host host) {
9290 return predicate.apply(host)
93- ? childPolicy.distance(host)
94- : HostDistance.IGNORED;
91+ ? childPolicy.distance(host)
92+ : HostDistance.IGNORED;
9593 }
9694
9795 /**
9896 * {@inheritDoc}
99- * <p>
97+ * <p/>
10098 * It is guaranteed that only hosts matching the predicate will be returned.
10199 */
102100 @Override
@@ -141,7 +139,7 @@
141139 @Override
142140 public void close() {
143141 if (childPolicy instanceof CloseableLoadBalancingPolicy)
144- ((CloseableLoadBalancingPolicy)childPolicy).close();
142+ ((CloseableLoadBalancingPolicy) childPolicy).close();
145143 }
146144
147145 /**
@@ -149,8 +147,7 @@
149147 * whose DC belongs to the provided list.
150148 *
151149 * @param childPolicy the wrapped policy.
152- * @param dcs the DCs.
153- *
150+ * @param dcs the DCs.
154151 * @return the policy.
155152 */
156153 public static HostFilterPolicy fromDCWhiteList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) {
@@ -162,8 +159,7 @@
162159 * whose DC belongs to the provided list.
163160 *
164161 * @param childPolicy the wrapped policy.
165- * @param dcs the DCs.
166- *
162+ * @param dcs the DCs.
167163 * @return the policy.
168164 */
169165 public static HostFilterPolicy fromDCBlackList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) {
modified driver-core/src/main/java/com/datastax/driver/core/policies/IdentityTranslater.java +1 −1
@@ -25,7 +25,7 @@
2525
2626 /**
2727 * Translates a Cassandra {@code rpc_address} to another address if necessary.
28- * <p>
28+ * <p/>
2929 * This method is the identity function, it always return the address passed
3030 * in argument, doing no translation.
3131 *
modified driver-core/src/main/java/com/datastax/driver/core/policies/LatencyAwarePolicy.java +53 −57
@@ -15,10 +15,8 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.*;
19-import java.util.concurrent.*;
20-import java.util.concurrent.atomic.AtomicReference;
21-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.*;
2220 import com.google.common.annotations.VisibleForTesting;
2321 import com.google.common.collect.AbstractIterator;
2422 import com.google.common.collect.ImmutableMap;
@@ -27,19 +25,20 @@
2725 import org.slf4j.Logger;
2826 import org.slf4j.LoggerFactory;
2927
30-import com.datastax.driver.core.*;
31-import com.datastax.driver.core.exceptions.*;
28+import java.util.*;
29+import java.util.concurrent.*;
30+import java.util.concurrent.atomic.AtomicReference;
3231
3332 /**
3433 * A wrapper load balancing policy that adds latency awareness to a child policy.
35- * <p>
34+ * <p/>
3635 * When used, this policy will collect the latencies of the queries to each
3736 * Cassandra node and maintain a per-node latency score (an average). Based
3837 * on these scores, the policy will penalize (technically, it will ignore them
3938 * unless no other nodes are up) the nodes that are slower than the best
4039 * performing node by more than some configurable amount (the exclusion
4140 * threshold).
42- * <p>
41+ * <p/>
4342 * The latency score for a given node is a based on a form of
4443 * <a href="http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average">exponential moving average</a>.
4544 * In other words, the latency score of a node is the average of its previously
@@ -48,13 +47,13 @@
4847 * time elapsed since the previous measure (to account for the fact that
4948 * latencies are not necessarily reported with equal regularity, neither
5049 * over time nor between different nodes).
51- * <p>
50+ * <p/>
5251 * Once a node is excluded from query plans (because its averaged latency grew
5352 * over the exclusion threshold), its latency score will not be updated anymore
5453 * (since it is not queried). To give a chance to this node to recover, the
5554 * policy has a configurable retry period. The policy will not penalize a host
5655 * for which no measurement has been collected for more than this retry period.
57- * <p>
56+ * <p/>
5857 * Please see the {@link Builder} class and methods for more details on the
5958 * possible parameters of this policy.
6059 *
@@ -100,7 +99,7 @@
10099 * that the resulting policy should wrap.
101100 *
102101 * @param childPolicy the load balancing policy to wrap with latency
103- * awareness.
102+ * awareness.
104103 * @return the created builder.
105104 */
106105 public static Builder builder(LoadBalancingPolicy childPolicy) {
@@ -140,11 +139,11 @@
140139 continue;
141140 }
142141
143- if (stats.getLatencyScore() > ((long)(exclusionThreshold * currentMin))) {
142+ if (stats.getLatencyScore() > ((long) (exclusionThreshold * currentMin))) {
144143 excludedThisTick.add(host);
145144 if (!excludedAtLastTick.contains(host))
146145 logger.debug(String.format("Host %s has an average latency score of %.3fms, more than %f times more than the minimum %.3fms: will be avoided temporarily.",
147- host, inMS(stats.getLatencyScore()), exclusionThreshold, inMS(currentMin)));
146+ host, inMS(stats.getLatencyScore()), exclusionThreshold, inMS(currentMin)));
148147 continue;
149148 }
150149
@@ -162,7 +161,7 @@
162161 }
163162
164163 private static double inMS(long nanos) {
165- return ((double)nanos) / (1000 * 1000);
164+ return ((double) nanos) / (1000 * 1000);
166165 }
167166
168167 private static double inMS(double nanos) {
@@ -192,19 +191,19 @@
192191
193192 /**
194193 * Returns the hosts to use for a new query.
195- * <p>
194+ * <p/>
196195 * The returned plan will be the same as the plan generated by the
197196 * child policy, but with the (initial) exclusion of hosts whose recent
198197 * (averaged) latency is more than {@code exclusionThreshold * minLatency}
199198 * (where {@code minLatency} is the (averaged) latency of the fastest
200199 * host).
201- * <p>
200+ * <p/>
202201 * The hosts that are initially excluded due to their latency will be returned
203202 * by this iterator, but only only after all non-excluded hosts of the
204203 * child policy have been returned.
205204 *
206205 * @param loggedKeyspace the currently logged keyspace.
207- * @param statement the statement for which to build the plan.
206+ * @param statement the statement for which to build the plan.
208207 * @return the new query plan.
209208 */
210209 @Override
@@ -229,7 +228,7 @@
229228
230229 // If the host latency is within acceptable bound of the faster known host, return
231230 // that host. Otherwise, skip it.
232- if (latency.average <= ((long)(exclusionThreshold * (double)min)))
231+ if (latency.average <= ((long) (exclusionThreshold * (double) min)))
233232 return host;
234233
235234 if (skipped == null)
@@ -241,7 +240,9 @@
241240 return skipped.poll();
242241
243242 return endOfData();
244- };
243+ }
244+
245+ ;
245246 };
246247 }
247248
@@ -379,11 +380,11 @@
379380 * and tend to make the host's score look better than it actually is.
380381 */
381382 private static final Set<Class<? extends DriverException>> EXCLUDED_EXCEPTIONS = ImmutableSet.of(
382- UnavailableException.class, // this is done via the snitch and is usually very fast
383- OverloadedException.class,
384- BootstrappingException.class,
385- UnpreparedException.class,
386- QueryValidationException.class // query validation also happens at early stages in the coordinator
383+ UnavailableException.class, // this is done via the snitch and is usually very fast
384+ OverloadedException.class,
385+ BootstrappingException.class,
386+ UnpreparedException.class,
387+ QueryValidationException.class // query validation also happens at early stages in the coordinator
387388 );
388389
389390 private class Tracker implements LatencyTracker {
@@ -392,7 +393,7 @@
392393 private volatile long cachedMin = -1L;
393394
394395 public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
395- if(shouldConsiderNewLatency(statement, exception)) {
396+ if (shouldConsiderNewLatency(statement, exception)) {
396397 HostLatencyTracker hostTracker = latencies.get(host);
397398 if (hostTracker == null) {
398399 hostTracker = new HostLatencyTracker(scale, (30L * minMeasure) / 100L);
@@ -406,9 +407,9 @@
406407
407408 private boolean shouldConsiderNewLatency(Statement statement, Exception exception) {
408409 // query was successful: always consider
409- if(exception == null) return true;
410+ if (exception == null) return true;
410411 // filter out "fast" errors
411- if(EXCLUDED_EXCEPTIONS.contains(exception.getClass())) return false;
412+ if (EXCLUDED_EXCEPTIONS.contains(exception.getClass())) return false;
412413 return true;
413414 }
414415
@@ -465,7 +466,7 @@
465466 private final AtomicReference<TimestampedAverage> current = new AtomicReference<TimestampedAverage>();
466467
467468 HostLatencyTracker(long scale, long thresholdToAccount) {
468- this.scale = (double)scale; // We keep in double since that's how we'll use it.
469+ this.scale = (double) scale; // We keep in double since that's how we'll use it.
469470 this.thresholdToAccount = thresholdToAccount;
470471 }
471472
@@ -499,11 +500,11 @@
499500 if (delay <= 0)
500501 return null;
501502
502- double scaledDelay = ((double)delay)/scale;
503+ double scaledDelay = ((double) delay) / scale;
503504 // Note: We don't use log1p because we it's quite a bit slower and we don't care about the precision (and since we
504505 // refuse ridiculously big scales, scaledDelay can't be so low that scaledDelay+1 == 1.0 (due to rounding)).
505- double prevWeight = Math.log(scaledDelay+1) / scaledDelay;
506- long newAverage = (long)((1.0 - prevWeight) * newLatencyNanos + prevWeight * previous.average);
506+ double prevWeight = Math.log(scaledDelay + 1) / scaledDelay;
507+ long newAverage = (long) ((1.0 - prevWeight) * newLatencyNanos + prevWeight * previous.average);
507508
508509 return new TimestampedAverage(currentTimestamp, newAverage, nbMeasure);
509510 }
@@ -515,13 +516,13 @@
515516
516517 /**
517518 * Helper builder object to create a latency aware policy.
518- * <p>
519+ * <p/>
519520 * This helper allows to configure the different parameters used by
520521 * {@code LatencyAwarePolicy}. The only mandatory parameter is the child
521522 * policy that will be wrapped with latency awareness. The other parameters
522523 * can be set through the methods of this builder, but all have defaults (that
523524 * are documented in the javadoc of each method) if you don't.
524- * <p>
525+ * <p/>
525526 * If you observe that the resulting policy excludes hosts too aggressively or
526527 * not enough so, the main parameters to check are the exclusion threshold
527528 * ({@link #withExclusionThreshold}) and scale ({@link #withScale}).
@@ -549,7 +550,7 @@
549550 * that the resulting policy wraps.
550551 *
551552 * @param childPolicy the load balancing policy to wrap with latency
552- * awareness.
553+ * awareness.
553554 */
554555 public Builder(LoadBalancingPolicy childPolicy) {
555556 this.childPolicy = childPolicy;
@@ -557,19 +558,18 @@
557558
558559 /**
559560 * Sets the exclusion threshold to use for the resulting latency aware policy.
560- * <p>
561+ * <p/>
561562 * The exclusion threshold controls how much worse the average latency
562563 * of a node must be compared to the fastest performing node for it to be
563564 * penalized by the policy.
564- * <p>
565+ * <p/>
565566 * The default exclusion threshold (if this method is not called) is <b>2</b>.
566567 * In other words, the resulting policy excludes nodes that are more than
567568 * twice slower than the fastest node.
568569 *
569570 * @param exclusionThreshold the exclusion threshold to use. Must be
570- * greater or equal to 1.
571+ * greater or equal to 1.
571572 * @return this builder.
572- *
573573 * @throws IllegalArgumentException if {@code exclusionThreshold &lt; 1}.
574574 */
575575 public Builder withExclusionThreshold(double exclusionThreshold) {
@@ -581,32 +581,31 @@
581581
582582 /**
583583 * Sets the scale to use for the resulting latency aware policy.
584- * <p>
584+ * <p/>
585585 * The {@code scale} provides control on how the weight given to older latencies
586586 * decreases over time. For a given host, if a new latency \(l\) is received at
587587 * time \(t\), and the previously calculated average is \(prev\) calculated at
588588 * time \(t'\), then the newly calculated average \(avg\) for that host is calculated
589589 * thusly:
590590 * \[
591- * d = \frac{t - t'}{scale} \\
592- * \alpha = 1 - \left(\frac{\ln(d+1)}{d}\right) \\
593- * avg = \alpha * l + (1-\alpha) * prev
591+ * d = \frac{t - t'}{scale} \\
592+ * \alpha = 1 - \left(\frac{\ln(d+1)}{d}\right) \\
593+ * avg = \alpha * l + (1-\alpha) * prev
594594 * \]
595595 * Typically, with a {@code scale} of 100 milliseconds (the default), if a new
596596 * latency is measured and the previous measure is 10 millisecond old (so \(d=0.1\)),
597597 * then \(\alpha\) will be around \(0.05\). In other words, the new latency will
598598 * weight 5% of the updated average. A bigger scale will get less weight to new
599599 * measurements (compared to previous ones), a smaller one will give them more weight.
600- * <p>
600+ * <p/>
601601 * The default scale (if this method is not used) is of <b>100 milliseconds</b>. If unsure, try
602602 * this default scale first and experiment only if it doesn't provide acceptable results
603603 * (hosts are excluded too quickly or not fast enough and tuning the exclusion threshold
604604 * doesn't help).
605605 *
606606 * @param scale the scale to use.
607- * @param unit the unit of {@code scale}.
607+ * @param unit the unit of {@code scale}.
608608 * @return this builder.
609- *
610609 * @throws IllegalArgumentException if {@code scale &lte; 0}.
611610 */
612611 public Builder withScale(long scale, TimeUnit unit) {
@@ -618,7 +617,7 @@
618617
619618 /**
620619 * Sets the retry period for the resulting latency aware policy.
621- * <p>
620+ * <p/>
622621 * The retry period defines how long a node may be penalized by the
623622 * policy before it is given a 2nd change. More precisely, a node is excluded
624623 * from query plans if both his calculated average latency is {@code exclusionThreshold}
@@ -628,9 +627,8 @@
628627 * latency updated, this is basically how long the policy will exclude a node.
629628 *
630629 * @param retryPeriod the retry period to use.
631- * @param unit the unit for {@code retryPeriod}.
630+ * @param unit the unit for {@code retryPeriod}.
632631 * @return this builder.
633- *
634632 * @throws IllegalArgumentException if {@code retryPeriod &lt; 0}.
635633 */
636634 public Builder withRetryPeriod(long retryPeriod, TimeUnit unit) {
@@ -642,14 +640,14 @@
642640
643641 /**
644642 * Sets the update rate for the resulting latency aware policy.
645- *
643+ * <p/>
646644 * The update rate defines how often the minimum average latency is
647645 * recomputed. While the average latency score of each node is computed
648646 * iteratively (updated each time a new latency is collected), the
649647 * minimum score needs to be recomputed from scratch every time, which
650648 * is slightly more costly. For this reason, the minimum is only
651649 * re-calculated at the given fixed rate and cached between re-calculation.
652- * <p>
650+ * <p/>
653651 * The default update rate if <b>100 milliseconds</b>, which should be
654652 * appropriate for most applications. In particular, note that while we
655653 * want to avoid to recompute the minimum for every query, that
@@ -658,9 +656,8 @@
658656 * unnecessarily slow for instance).
659657 *
660658 * @param updateRate the update rate to use.
661- * @param unit the unit for {@code updateRate}.
659+ * @param unit the unit for {@code updateRate}.
662660 * @return this builder.
663- *
664661 * @throws IllegalArgumentException if {@code updateRate &lte; 0}.
665662 */
666663 public Builder withUpdateRate(long updateRate, TimeUnit unit) {
@@ -673,7 +670,7 @@
673670 /**
674671 * Sets the minimum number of measurements per-host to consider for
675672 * the resulting latency aware policy.
676- * <p>
673+ * <p/>
677674 * Penalizing nodes is based on an average of their recently measured
678675 * average latency. This average is only meaningful if a minimum of
679676 * measurements have been collected (moreover, a newly started
@@ -686,10 +683,10 @@
686683 * ignored, while the {@code 70%} next ones are accounted in the latency
687684 * computed but the node won't get convicted until we've had at least
688685 * {@code minMeasure} measurements).
689- * <p>
686+ * <p/>
690687 * Note that the number of collected measurements for a given host is
691688 * reset if the node is restarted.
692- * <p>
689+ * <p/>
693690 * The default for this option (if this method is not called) is <b>50</b>.
694691 * Note that it is probably not a good idea to put this option too low
695692 * if only to avoid the influence of JVM warm-up on newly restarted
@@ -697,7 +694,6 @@
697694 *
698695 * @param minMeasure the minimum measurements to consider.
699696 * @return this builder.
700- *
701697 * @throws IllegalArgumentException if {@code minMeasure &lt; 0}.
702698 */
703699 public Builder withMininumMeasurements(int minMeasure) {
@@ -721,7 +717,7 @@
721717 @Override
722718 public void close() {
723719 if (childPolicy instanceof CloseableLoadBalancingPolicy)
724- ((CloseableLoadBalancingPolicy)childPolicy).close();
720+ ((CloseableLoadBalancingPolicy) childPolicy).close();
725721 updaterService.shutdown();
726722 }
727723 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/LoadBalancingPolicy.java +18 −18
@@ -15,25 +15,25 @@
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 * The policy that decides which Cassandra hosts to contact for each new query.
28- * <p>
28+ * <p/>
2929 * Two methods need to be implemented:
3030 * <ul>
31- * <li>{@link LoadBalancingPolicy#distance}: returns the "distance" of an
32- * host for that balancing policy. </li>
33- * <li>{@link LoadBalancingPolicy#newQueryPlan}: it is used for each query to
34- * find which host to query first, and which hosts to use as failover.</li>
31+ * <li>{@link LoadBalancingPolicy#distance}: returns the "distance" of an
32+ * host for that balancing policy. </li>
33+ * <li>{@link LoadBalancingPolicy#newQueryPlan}: it is used for each query to
34+ * find which host to query first, and which hosts to use as failover.</li>
3535 * </ul>
36- * <p>
36+ * <p/>
3737 * The {@code LoadBalancingPolicy} is a {@link com.datastax.driver.core.Host.StateListener}
3838 * and is thus informed of hosts up/down events. For efficiency purposes, the
3939 * policy is expected to exclude down hosts from query plans.
@@ -42,25 +42,25 @@
4242
4343 /**
4444 * Initialize this load balancing policy.
45- * <p>
45+ * <p/>
4646 * Note that the driver guarantees that it will call this method exactly
4747 * once per policy object and will do so before any call to another of the
4848 * methods of the policy.
4949 *
5050 * @param cluster the {@code Cluster} instance for which the policy is created.
51- * @param hosts the initial hosts to use.
51+ * @param hosts the initial hosts to use.
5252 */
5353 public void init(Cluster cluster, Collection<Host> hosts);
5454
5555 /**
5656 * Returns the distance assigned by this policy to the provided host.
57- * <p>
57+ * <p/>
5858 * The distance of an host influence how much connections are kept to the
5959 * node (see {@link HostDistance}). A policy should assign a {@code
6060 * LOCAL} distance to nodes that are susceptible to be returned first by
6161 * {@code newQueryPlan} and it is useless for {@code newQueryPlan} to
6262 * return hosts to which it assigns an {@code IGNORED} distance.
63- * <p>
63+ * <p/>
6464 * The host distance is primarily used to prevent keeping too many
6565 * connections to host in remote datacenters when the policy itself always
6666 * picks host in the local datacenter first.
@@ -72,7 +72,7 @@
7272
7373 /**
7474 * Returns the hosts to use for a new query.
75- * <p>
75+ * <p/>
7676 * Each new query will call this method. The first host in the result will
7777 * then be used to perform the query. In the event of a connection problem
7878 * (the queried host is down or appear to be so), the next host will be
@@ -80,10 +80,10 @@
8080 * will fail.
8181 *
8282 * @param loggedKeyspace the currently logged keyspace (the one set through either
83- * {@link Cluster#connect(String)} or by manually doing a {@code USE} query) for
84- * the session on which this plan need to be built. This can be {@code null} if
85- * the corresponding session has no keyspace logged in.
86- * @param statement the query for which to build a plan.
83+ * {@link Cluster#connect(String)} or by manually doing a {@code USE} query) for
84+ * the session on which this plan need to be built. This can be {@code null} if
85+ * the corresponding session has no keyspace logged in.
86+ * @param statement the query for which to build a plan.
8787 * @return an iterator of Host. The query is tried against the hosts
8888 * returned by this iterator in order, until the query has been sent
8989 * successfully to one of the host.
modified driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java +4 −5
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import org.slf4j.Logger;
19-import org.slf4j.LoggerFactory;
20-
2118 import com.datastax.driver.core.ConsistencyLevel;
2219 import com.datastax.driver.core.Statement;
2320 import com.datastax.driver.core.WriteType;
21+import org.slf4j.Logger;
22+import org.slf4j.LoggerFactory;
2423
2524 /**
2625 * A retry policy that wraps another policy, logging the decision made by its sub-policy.
27- * <p>
26+ * <p/>
2827 * Note that this policy only log the IGNORE and RETRY decisions (since
2928 * RETHROW decisions are just meant to propagate the cassandra exception). The
3029 * logging is done at the INFO level.
@@ -38,7 +37,7 @@
3837 * Creates a new {@code RetryPolicy} that logs the decision of {@code policy}.
3938 *
4039 * @param policy the policy to wrap. The policy created by this constructor
41- * will return the same decision than {@code policy} but will log them.
40+ * will return the same decision than {@code policy} but will log them.
4241 */
4342 public LoggingRetryPolicy(RetryPolicy policy) {
4443 this.policy = policy;
modified driver-core/src/main/java/com/datastax/driver/core/policies/NoSpeculativeExecutionPolicy.java +3 −1
@@ -24,7 +24,9 @@
2424 */
2525 public class NoSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy {
2626
27- /** The single instance (this class is stateless). */
27+ /**
28+ * The single instance (this class is stateless).
29+ */
2830 public static final NoSpeculativeExecutionPolicy INSTANCE = new NoSpeculativeExecutionPolicy();
2931
3032 private static final SpeculativeExecutionPlan PLAN = new SpeculativeExecutionPlan() {
modified driver-core/src/main/java/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.java +13 −14
@@ -15,20 +15,19 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.concurrent.atomic.AtomicInteger;
19-
20-import com.google.common.annotations.Beta;
21-
22-import static com.google.common.base.Preconditions.checkArgument;
23-
2418 import com.datastax.driver.core.Cluster;
2519 import com.datastax.driver.core.Host;
26-import com.datastax.driver.core.Statement;
2720 import com.datastax.driver.core.PerHostPercentileTracker;
21+import com.datastax.driver.core.Statement;
22+import com.google.common.annotations.Beta;
23+
24+import java.util.concurrent.atomic.AtomicInteger;
25+
26+import static com.google.common.base.Preconditions.checkArgument;
2827
2928 /**
3029 * A policy that triggers speculative executions when the request to the current host is above a given percentile.
31- *
30+ * <p/>
3231 * This class uses a {@link PerHostPercentileTracker} that must be registered with the cluster instance:
3332 * <pre>
3433 * PerHostPercentileTracker tracker = PerHostPercentileTracker
@@ -43,7 +42,7 @@
4342 * </pre>
4443 * You <b>must</b> register the tracker with the cluster yourself (as shown on the last line above), this class will not
4544 * do it itself.
46- * <p>
45+ * <p/>
4746 * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
4847 * to change.</b>
4948 */
@@ -56,17 +55,17 @@
5655 /**
5756 * Builds a new instance.
5857 *
59- * @param percentileTracker the component that will record latencies. Note that this policy doesn't register it with the {@code Cluster},
60- * you <b>must</b> do it yourself (see the code example in this class's Javadoc).
61- * @param percentile the percentile that a request's latency must fall into to be considered slow (ex: {@code 99.0}).
58+ * @param percentileTracker the component that will record latencies. Note that this policy doesn't register it with the {@code Cluster},
59+ * you <b>must</b> do it yourself (see the code example in this class's Javadoc).
60+ * @param percentile the percentile that a request's latency must fall into to be considered slow (ex: {@code 99.0}).
6261 * @param maxSpeculativeExecutions the maximum number of speculative executions that will be triggered for a given request (this does not
6362 * include the initial, normal request). Must be strictly positive.
6463 */
6564 public PercentileSpeculativeExecutionPolicy(PerHostPercentileTracker percentileTracker, double percentile, int maxSpeculativeExecutions) {
6665 checkArgument(maxSpeculativeExecutions > 0,
67- "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions);
66+ "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions);
6867 checkArgument(percentile >= 0.0 && percentile < 100,
69- "percentile must be between 0.0 and 100 (was %f)");
68+ "percentile must be between 0.0 and 100 (was %f)");
7069
7170 this.percentileTracker = percentileTracker;
7271 this.percentile = percentile;
modified driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +18 −19
@@ -15,10 +15,9 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import com.google.common.base.Objects;
19-
2018 import com.datastax.driver.core.ServerSideTimestampGenerator;
2119 import com.datastax.driver.core.TimestampGenerator;
20+import com.google.common.base.Objects;
2221
2322 /**
2423 * Policies configured for a {@link com.datastax.driver.core.Cluster} instance.
@@ -72,10 +71,10 @@
7271
7372 /**
7473 * The default load balancing policy.
75- * <p>
74+ * <p/>
7675 * The default load balancing policy is {@link DCAwareRoundRobinPolicy} with token
7776 * awareness (so {@code new TokenAwarePolicy(new DCAwareRoundRobinPolicy())}).
78- * <p>
77+ * <p/>
7978 * Note that this policy shuffles the replicas when token awareness is used, see
8079 * {@link TokenAwarePolicy#TokenAwarePolicy(LoadBalancingPolicy, boolean)} for an
8180 * explanation of the tradeoffs.
@@ -90,7 +89,7 @@
9089
9190 /**
9291 * The default reconnection policy.
93- * <p>
92+ * <p/>
9493 * The default reconnection policy is an {@link ExponentialReconnectionPolicy}
9594 * where the base delay is 1 second and the max delay is 10 minutes;
9695 *
@@ -102,7 +101,7 @@
102101
103102 /**
104103 * The default retry policy.
105- * <p>
104+ * <p/>
106105 * The default retry policy is {@link DefaultRetryPolicy}.
107106 *
108107 * @return the default retry policy.
@@ -113,7 +112,7 @@
113112
114113 /**
115114 * The default address translater.
116- * <p>
115+ * <p/>
117116 * The default address translater is {@link IdentityTranslater}.
118117 *
119118 * @return the default address translater.
@@ -124,7 +123,7 @@
124123
125124 /**
126125 * The default timestamp generator.
127- * <p>
126+ * <p/>
128127 * This is an instance of {@link ServerSideTimestampGenerator}.
129128 *
130129 * @return the default timestamp generator.
@@ -135,7 +134,7 @@
135134
136135 /**
137136 * The default speculative retry policy.
138- * <p>
137+ * <p/>
139138 * The default speculative retry policy is a {@link NoSpeculativeExecutionPolicy}.
140139 *
141140 * @return the default speculative retry policy.
@@ -146,7 +145,7 @@
146145
147146 /**
148147 * The load balancing policy in use.
149- * <p>
148+ * <p/>
150149 * The load balancing policy defines how Cassandra hosts are picked for queries.
151150 *
152151 * @return the load balancing policy in use.
@@ -157,7 +156,7 @@
157156
158157 /**
159158 * The reconnection policy in use.
160- * <p>
159+ * <p/>
161160 * The reconnection policy defines how often the driver tries to reconnect to a dead node.
162161 *
163162 * @return the reconnection policy in use.
@@ -168,7 +167,7 @@
168167
169168 /**
170169 * The retry policy in use.
171- * <p>
170+ * <p/>
172171 * The retry policy defines in which conditions a query should be
173172 * automatically retries by the driver.
174173 *
@@ -284,19 +283,19 @@
284283
285284 /**
286285 * Builds the final object from this builder.
287- * <p>
286+ * <p/>
288287 * Any field that hasn't been set explicitly will get its default value.
289288 *
290289 * @return the object.
291290 */
292291 public Policies build() {
293292 return new Policies(
294- loadBalancingPolicy == null ? Policies.defaultLoadBalancingPolicy() : loadBalancingPolicy,
295- Objects.firstNonNull(reconnectionPolicy, Policies.defaultReconnectionPolicy()),
296- Objects.firstNonNull(retryPolicy, Policies.defaultRetryPolicy()),
297- Objects.firstNonNull(addressTranslater, Policies.defaultAddressTranslater()),
298- Objects.firstNonNull(timestampGenerator, Policies.defaultTimestampGenerator()),
299- Objects.firstNonNull(speculativeExecutionPolicy, Policies.defaultSpeculativeExecutionPolicy()));
293+ loadBalancingPolicy == null ? Policies.defaultLoadBalancingPolicy() : loadBalancingPolicy,
294+ Objects.firstNonNull(reconnectionPolicy, Policies.defaultReconnectionPolicy()),
295+ Objects.firstNonNull(retryPolicy, Policies.defaultRetryPolicy()),
296+ Objects.firstNonNull(addressTranslater, Policies.defaultAddressTranslater()),
297+ Objects.firstNonNull(timestampGenerator, Policies.defaultTimestampGenerator()),
298+ Objects.firstNonNull(speculativeExecutionPolicy, Policies.defaultSpeculativeExecutionPolicy()));
300299 }
301300 }
302301
modified driver-core/src/main/java/com/datastax/driver/core/policies/ReconnectionPolicy.java +4 −4
@@ -17,18 +17,18 @@
1717
1818 /**
1919 * Policy that decides how often the reconnection to a dead node is attempted.
20- *
20+ * <p/>
2121 * Each time a node is detected dead (because a connection error occurs), a new
2222 * {@code ReconnectionSchedule} instance is created (through the {@link #newSchedule()}).
2323 * Then each call to the {@link ReconnectionSchedule#nextDelayMs} method of
2424 * this instance will decide when the next reconnection attempt to this node
2525 * will be tried.
26- *
26+ * <p/>
2727 * Note that if the driver receives a push notification from the Cassandra cluster
2828 * that a node is UP, any existing {@code ReconnectionSchedule} on that node
2929 * will be cancelled and a new one will be created (in effect, the driver reset
3030 * the scheduler).
31- *
31+ * <p/>
3232 * The default {@link ExponentialReconnectionPolicy} policy is usually
3333 * adequate.
3434 */
@@ -48,7 +48,7 @@
4848
4949 /**
5050 * When to attempt the next reconnection.
51- *
51+ * <p/>
5252 * This method will be called once when the host is detected down to
5353 * schedule the first reconnection attempt, and then once after each failed
5454 * reconnection attempt to schedule the next one. Hence each call to this
modified driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +41 −34
@@ -22,7 +22,7 @@
2222 /**
2323 * A policy that defines a default behavior to adopt when a request returns
2424 * a TimeoutException or an UnavailableException.
25- *
25+ * <p/>
2626 * Such policy allows to centralize the handling of query retries, allowing to
2727 * minimize the need for exception catching/handling in business code.
2828 */
@@ -31,28 +31,32 @@
3131 /**
3232 * A retry decision to adopt on a Cassandra exception (read/write timeout
3333 * or unavailable exception).
34- * <p>
34+ * <p/>
3535 * There is three possible decision:
3636 * <ul>
37- * <li>RETHROW: no retry should be attempted and an exception should be thrown</li>
38- * <li>RETRY: the operation will be retried. The consistency level of the
39- * retry should be specified.</li>
40- * <li>IGNORE: no retry should be attempted and the exception should be
41- * ignored. In that case, the operation that triggered the Cassandra
42- * exception will return an empty result set.</li>
37+ * <li>RETHROW: no retry should be attempted and an exception should be thrown</li>
38+ * <li>RETRY: the operation will be retried. The consistency level of the
39+ * retry should be specified.</li>
40+ * <li>IGNORE: no retry should be attempted and the exception should be
41+ * ignored. In that case, the operation that triggered the Cassandra
42+ * exception will return an empty result set.</li>
4343 * </ul>
4444 */
4545 class RetryDecision {
4646 /**
4747 * The type of retry decisions.
4848 */
49- public enum Type { RETRY, RETHROW, IGNORE };
49+ public enum Type {
50+ RETRY, RETHROW, IGNORE
51+ }
52+
53+ ;
5054
5155 private final Type type;
5256 private final ConsistencyLevel retryCL;
5357 private final boolean retryCurrent;
5458
55- private RetryDecision(Type type, ConsistencyLevel retryCL, boolean retryCurrent){
59+ private RetryDecision(Type type, ConsistencyLevel retryCL, boolean retryCurrent) {
5660 this.type = type;
5761 this.retryCL = retryCL;
5862 this.retryCurrent = retryCurrent;
@@ -127,9 +131,12 @@
127131 @Override
128132 public String toString() {
129133 switch (type) {
130- case RETRY: return "Retry at " + retryCL + " on " + (retryCurrent ? "same " : "next ") + "host.";
131- case RETHROW: return "Rethrow";
132- case IGNORE: return "Ignore";
134+ case RETRY:
135+ return "Retry at " + retryCL + " on " + (retryCurrent ? "same " : "next ") + "host.";
136+ case RETHROW:
137+ return "Rethrow";
138+ case IGNORE:
139+ return "Ignore";
133140 }
134141 throw new AssertionError();
135142 }
@@ -137,21 +144,21 @@
137144
138145 /**
139146 * Defines whether to retry and at which consistency level on a read timeout.
140- * <p>
147+ * <p/>
141148 * Note that this method may be called even if
142149 * {@code requiredResponses >= receivedResponses} if {@code dataPresent} is
143150 * {@code false} (see
144151 * {@link com.datastax.driver.core.exceptions.ReadTimeoutException#wasDataRetrieved}).
145152 *
146- * @param statement the original query that timed out.
147- * @param cl the original consistency level of the read that timed out.
153+ * @param statement the original query that timed out.
154+ * @param cl the original consistency level of the read that timed out.
148155 * @param requiredResponses the number of responses that were required to
149- * achieve the requested consistency level.
156+ * achieve the requested consistency level.
150157 * @param receivedResponses the number of responses that had been received
151- * by the time the timeout exception was raised.
152- * @param dataRetrieved whether actual data (by opposition to data checksum)
153- * was present in the received responses.
154- * @param nbRetry the number of retry already performed for this operation.
158+ * by the time the timeout exception was raised.
159+ * @param dataRetrieved whether actual data (by opposition to data checksum)
160+ * was present in the received responses.
161+ * @param nbRetry the number of retry already performed for this operation.
155162 * @return the retry decision. If {@code RetryDecision.RETHROW} is returned,
156163 * a {@link com.datastax.driver.core.exceptions.ReadTimeoutException} will
157164 * be thrown for the operation.
@@ -161,14 +168,14 @@
161168 /**
162169 * Defines whether to retry and at which consistency level on a write timeout.
163170 *
164- * @param statement the original query that timed out.
165- * @param cl the original consistency level of the write that timed out.
166- * @param writeType the type of the write that timed out.
171+ * @param statement the original query that timed out.
172+ * @param cl the original consistency level of the write that timed out.
173+ * @param writeType the type of the write that timed out.
167174 * @param requiredAcks the number of acknowledgments that were required to
168- * achieve the requested consistency level.
175+ * achieve the requested consistency level.
169176 * @param receivedAcks the number of acknowledgments that had been received
170- * by the time the timeout exception was raised.
171- * @param nbRetry the number of retry already performed for this operation.
177+ * by the time the timeout exception was raised.
178+ * @param nbRetry the number of retry already performed for this operation.
172179 * @return the retry decision. If {@code RetryDecision.RETHROW} is returned,
173180 * a {@link com.datastax.driver.core.exceptions.WriteTimeoutException} will
174181 * be thrown for the operation.
@@ -179,14 +186,14 @@
179186 * Defines whether to retry and at which consistency level on an
180187 * unavailable exception.
181188 *
182- * @param statement the original query for which the consistency level cannot
183- * be achieved.
184- * @param cl the original consistency level for the operation.
189+ * @param statement the original query for which the consistency level cannot
190+ * be achieved.
191+ * @param cl the original consistency level for the operation.
185192 * @param requiredReplica the number of replica that should have been
186- * (known) alive for the operation to be attempted.
187- * @param aliveReplica the number of replica that were know to be alive by
188- * the coordinator of the operation.
189- * @param nbRetry the number of retry already performed for this operation.
193+ * (known) alive for the operation to be attempted.
194+ * @param aliveReplica the number of replica that were know to be alive by
195+ * the coordinator of the operation.
196+ * @param nbRetry the number of retry already performed for this operation.
190197 * @return the retry decision. If {@code RetryDecision.RETHROW} is returned,
191198 * an {@link com.datastax.driver.core.exceptions.UnavailableException} will
192199 * be thrown for the operation.
modified driver-core/src/main/java/com/datastax/driver/core/policies/RoundRobinPolicy.java +18 −26
@@ -15,34 +15,25 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.datastax.driver.core.*;
19+import com.google.common.collect.AbstractIterator;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+
1823 import java.util.Collection;
1924 import java.util.Iterator;
2025 import java.util.List;
2126 import java.util.Random;
2227 import java.util.concurrent.CopyOnWriteArrayList;
23-import java.util.concurrent.ExecutionException;
24-import java.util.concurrent.TimeUnit;
25-import java.util.concurrent.TimeoutException;
2628 import java.util.concurrent.atomic.AtomicInteger;
2729
28-import com.google.common.collect.AbstractIterator;
29-import org.slf4j.Logger;
30-import org.slf4j.LoggerFactory;
31-
32-import com.datastax.driver.core.Cluster;
33-import com.datastax.driver.core.Configuration;
34-import com.datastax.driver.core.ConsistencyLevel;
35-import com.datastax.driver.core.Host;
36-import com.datastax.driver.core.HostDistance;
37-import com.datastax.driver.core.Statement;
38-
3930 /**
4031 * A Round-robin load balancing policy.
41- * <p>
32+ * <p/>
4233 * This policy queries nodes in a round-robin fashion. For a given query,
4334 * if an host fail, the next one (following the round-robin order) is
4435 * tried, until all hosts have been tried.
45- * <p>
36+ * <p/>
4637 * This policy is not datacenter aware and will include every known
4738 * Cassandra host in its round robin algorithm. If you use multiple
4839 * datacenter this will be inefficient and you will want to use the
@@ -62,7 +53,8 @@
6253 * Creates a load balancing policy that picks host to query in a round robin
6354 * fashion (on all the hosts of the Cassandra cluster).
6455 */
65- public RoundRobinPolicy() {}
56+ public RoundRobinPolicy() {
57+ }
6658
6759 @Override
6860 public void init(Cluster cluster, Collection<Host> hosts) {
@@ -73,7 +65,7 @@
7365
7466 /**
7567 * Return the HostDistance for the provided host.
76- * <p>
68+ * <p/>
7769 * This policy consider all nodes as local. This is generally the right
7870 * thing to do in a single datacenter deployment. If you use multiple
7971 * datacenter, see {@link DCAwareRoundRobinPolicy} instead.
@@ -88,14 +80,14 @@
8880
8981 /**
9082 * Returns the hosts to use for a new query.
91- * <p>
83+ * <p/>
9284 * The returned plan will try each known host of the cluster. Upon each
9385 * call to this method, the {@code i}th host of the plans returned will cycle
9486 * over all the hosts of the cluster in a round-robin fashion.
9587 *
9688 * @param loggedKeyspace the keyspace currently logged in on for this
97- * query.
98- * @param statement the query for which to build the plan.
89+ * query.
90+ * @param statement the query for which to build the plan.
9991 * @return a new query plan, i.e. an iterator indicating which host to
10092 * try first for querying, which one to use as failover, etc...
10193 */
@@ -104,13 +96,13 @@
10496
10597 if (!hasLoggedLocalCLUse) {
10698 ConsistencyLevel cl = statement.getConsistencyLevel() == null
107- ? configuration.getQueryOptions().getConsistencyLevel()
108- : statement.getConsistencyLevel();
99+ ? configuration.getQueryOptions().getConsistencyLevel()
100+ : statement.getConsistencyLevel();
109101 if (cl.isDCLocal()) {
110102 hasLoggedLocalCLUse = true;
111103 logger.warn("Detected request at Consistency Level {} but the non-DC aware RoundRobinPolicy is in use. "
112- + "It is strongly advised to use DCAwareRoundRobinPolicy if you have multiple DCs/use DC-aware consistency levels "
113- + "(note: this message will only be logged once)", statement.getConsistencyLevel());
104+ + "It is strongly advised to use DCAwareRoundRobinPolicy if you have multiple DCs/use DC-aware consistency levels "
105+ + "(note: this message will only be logged once)", statement.getConsistencyLevel());
114106 }
115107 }
116108
@@ -119,7 +111,7 @@
119111 // would be racy). We use clone() as it don't involve a copy of the
120112 // underlying array (and thus we rely on liveHosts being a CopyOnWriteArrayList).
121113 @SuppressWarnings("unchecked")
122- final List<Host> hosts = (List<Host>)liveHosts.clone();
114+ final List<Host> hosts = (List<Host>) liveHosts.clone();
123115 final int startIdx = index.getAndIncrement();
124116
125117 // Overflow protection; not theoretically thread safe but should be good enough
modified driver-core/src/main/java/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.java +7 −7
@@ -22,7 +22,7 @@
2222 /**
2323 * The policy that decides if the driver will send speculative queries to the next hosts when the current host takes too
2424 * long to respond.
25- * <p>
25+ * <p/>
2626 * Note that only idempotent statements will be speculatively retried, see
2727 * {@link com.datastax.driver.core.Statement#isIdempotent()} for more information.
2828 */
@@ -38,24 +38,24 @@
3838 * Returns the plan to use for a new query.
3939 *
4040 * @param loggedKeyspace the currently logged keyspace (the one set through either
41- * {@link Cluster#connect(String)} or by manually doing a {@code USE} query) for
42- * the session on which this plan need to be built. This can be {@code null} if
43- * the corresponding session has no keyspace logged in.
44- * @param statement the query for which to build a plan.
41+ * {@link Cluster#connect(String)} or by manually doing a {@code USE} query) for
42+ * the session on which this plan need to be built. This can be {@code null} if
43+ * the corresponding session has no keyspace logged in.
44+ * @param statement the query for which to build a plan.
4545 * @return the plan.
4646 */
4747 SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement);
4848
4949 /**
5050 * Gets invoked at cluster shutdown.
51- *
51+ * <p/>
5252 * This gives the policy the opportunity to perform some cleanup, for instance stop threads that it might have started.
5353 */
5454 void close();
5555
5656 /**
5757 * A plan that governs speculative executions for a given query.
58- * <p>
58+ * <p/>
5959 * Each time a host is queried, {@link #nextExecution(Host)} is invoked to determine if and when a speculative query to
6060 * the next host will be sent.
6161 */
modified driver-core/src/main/java/com/datastax/driver/core/policies/TokenAwarePolicy.java +18 −22
@@ -15,31 +15,29 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.nio.ByteBuffer;
19-import java.util.*;
20-
21-import com.google.common.collect.Lists;
22-
18+import com.datastax.driver.core.*;
2319 import com.google.common.collect.AbstractIterator;
20+import com.google.common.collect.Lists;
2421
25-import com.datastax.driver.core.*;
22+import java.nio.ByteBuffer;
23+import java.util.*;
2624
2725 /**
2826 * A wrapper load balancing policy that add token awareness to a child policy.
29- * <p>
27+ * <p/>
3028 * This policy encapsulates another policy. The resulting policy works in
3129 * the following way:
3230 * <ul>
33- * <li>the {@code distance} method is inherited from the child policy.</li>
34- * <li>the iterator return by the {@code newQueryPlan} method will first
35- * return the {@code LOCAL} replicas for the query (based on {@link Statement#getRoutingKey})
36- * <i>if possible</i> (i.e. if the query {@code getRoutingKey} method
37- * doesn't return {@code null} and if {@link Metadata#getReplicas}
38- * returns a non empty set of replicas for that partition key). If no
39- * local replica can be either found or successfully contacted, the rest
40- * of the query plan will fallback to one of the child policy.</li>
31+ * <li>the {@code distance} method is inherited from the child policy.</li>
32+ * <li>the iterator return by the {@code newQueryPlan} method will first
33+ * return the {@code LOCAL} replicas for the query (based on {@link Statement#getRoutingKey})
34+ * <i>if possible</i> (i.e. if the query {@code getRoutingKey} method
35+ * doesn't return {@code null} and if {@link Metadata#getReplicas}
36+ * returns a non empty set of replicas for that partition key). If no
37+ * local replica can be either found or successfully contacted, the rest
38+ * of the query plan will fallback to one of the child policy.</li>
4139 * </ul>
42- * <p>
40+ * <p/>
4341 * Do note that only replica for which the child policy {@code distance}
4442 * method returns {@code HostDistance.LOCAL} will be considered having
4543 * priority. For example, if you wrap {@link DCAwareRoundRobinPolicy} with this
@@ -55,7 +53,7 @@
5553 /**
5654 * Creates a new {@code TokenAware} policy.
5755 *
58- * @param childPolicy the load balancing policy to wrap with token awareness.
56+ * @param childPolicy the load balancing policy to wrap with token awareness.
5957 * @param shuffleReplicas whether to shuffle the replicas returned by {@code getRoutingKey}.
6058 * Note that setting this parameter to {@code true} might decrease the
6159 * effectiveness of caching (especially at consistency level ONE), since
@@ -63,7 +61,6 @@
6361 * "primary" replica without shuffling).
6462 * On the other hand, shuffling will better distribute writes, and can
6563 * alleviate hotspots caused by "fat" partitions.
66- *
6764 */
6865 public TokenAwarePolicy(LoadBalancingPolicy childPolicy, boolean shuffleReplicas) {
6966 this.childPolicy = childPolicy;
@@ -74,8 +71,7 @@
7471 * Creates a new {@code TokenAware} policy with shuffling of replicas.
7572 *
7673 * @param childPolicy the load balancing policy to wrap with token
77- * awareness.
78- *
74+ * awareness.
7975 * @see #TokenAwarePolicy(LoadBalancingPolicy, boolean)
8076 */
8177 public TokenAwarePolicy(LoadBalancingPolicy childPolicy) {
@@ -106,7 +102,7 @@
106102
107103 /**
108104 * Returns the hosts to use for a new query.
109- * <p>
105+ * <p/>
110106 * The returned plan will first return replicas (whose {@code HostDistance}
111107 * for the child policy is {@code LOCAL}) for the query if it can determine
112108 * them (i.e. mainly if {@code statement.getRoutingKey()} is not {@code null}).
@@ -193,6 +189,6 @@
193189 @Override
194190 public void close() {
195191 if (childPolicy instanceof CloseableLoadBalancingPolicy)
196- ((CloseableLoadBalancingPolicy)childPolicy).close();
192+ ((CloseableLoadBalancingPolicy) childPolicy).close();
197193 }
198194 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java +7 −8
@@ -15,24 +15,23 @@
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.Host;
2119 import com.google.common.base.Predicate;
2220 import com.google.common.collect.ImmutableSet;
2321
24-import com.datastax.driver.core.Host;
22+import java.net.InetSocketAddress;
23+import java.util.Collection;
2524
2625 /**
2726 * A load balancing policy wrapper that ensure that only hosts from a provided
2827 * white list will ever be returned.
29- * <p>
28+ * <p/>
3029 * This policy wraps another load balancing policy and will delegate the choice
3130 * of hosts to the wrapped policy with the exception that only hosts contained
3231 * in the white list provided when constructing this policy will ever be
3332 * returned. Any host not in the while list will be considered {@code IGNORED}
3433 * and thus will not be connected to.
35- * <p>
34+ * <p/>
3635 * This policy can be useful to ensure that the driver only connects to a
3736 * predefined set of hosts. Keep in mind however that this policy defeats
3837 * somewhat the host auto-detection of the driver. As such, this policy is only
@@ -50,8 +49,8 @@
5049 * from the provided while list.
5150 *
5251 * @param childPolicy the wrapped policy.
53- * @param whiteList the white listed hosts. Only hosts from this list may get connected
54- * to (whether they will get connected to or not depends on the child policy).
52+ * @param whiteList the white listed hosts. Only hosts from this list may get connected
53+ * to (whether they will get connected to or not depends on the child policy).
5554 */
5655 public WhiteListPolicy(LoadBalancingPolicy childPolicy, Collection<InetSocketAddress> whiteList) {
5756 super(childPolicy, buildPredicate(whiteList));
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java +2 −2
@@ -73,8 +73,8 @@
7373
7474 CounterAssignment(String name, Object value, boolean isIncr) {
7575 super(name);
76- if (!isIncr && value instanceof Long && ((Long)value) < 0) {
77- this.value = -((Long)value);
76+ if (!isIncr && value instanceof Long && ((Long) value) < 0) {
77+ this.value = -((Long) value);
7878 this.isIncr = true;
7979 } else {
8080 this.value = value;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +16 −21
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
19-import java.util.ArrayList;
20-import java.util.List;
21-
2218 import com.datastax.driver.core.ProtocolVersion;
2319 import com.datastax.driver.core.RegularStatement;
2420 import com.datastax.driver.core.SimpleStatement;
2521
22+import java.nio.ByteBuffer;
23+import java.util.ArrayList;
24+import java.util.List;
25+
2626 /**
2727 * A built BATCH statement.
2828 */
@@ -37,10 +37,10 @@
3737 private int nonBuiltStatementValues;
3838
3939 Batch(RegularStatement[] statements, boolean logged) {
40- super((String)null);
40+ super((String) null);
4141 this.statements = statements.length == 0
42- ? new ArrayList<RegularStatement>()
43- : new ArrayList<RegularStatement>(statements.length);
42+ ? new ArrayList<RegularStatement>()
43+ : new ArrayList<RegularStatement>(statements.length);
4444 this.logged = logged;
4545 this.usings = new Options(this);
4646
@@ -53,8 +53,8 @@
5353 StringBuilder builder = new StringBuilder();
5454
5555 builder.append(isCounterOp()
56- ? "BEGIN COUNTER BATCH"
57- : (logged ? "BEGIN BATCH" : "BEGIN UNLOGGED BATCH"));
56+ ? "BEGIN COUNTER BATCH"
57+ : (logged ? "BEGIN BATCH" : "BEGIN UNLOGGED BATCH"));
5858
5959 if (!usings.usings.isEmpty()) {
6060 builder.append(" USING ");
@@ -65,7 +65,7 @@
6565 for (int i = 0; i < statements.size(); i++) {
6666 RegularStatement stmt = statements.get(i);
6767 if (stmt instanceof BuiltStatement) {
68- BuiltStatement bst = (BuiltStatement)stmt;
68+ BuiltStatement bst = (BuiltStatement) stmt;
6969 builder.append(maybeAddSemicolon(bst.buildQueryString(variables)));
7070
7171 } else {
@@ -88,9 +88,8 @@
8888 *
8989 * @param statement the new statement to add.
9090 * @return this batch.
91- *
9291 * @throws IllegalArgumentException if counter and non-counter operations
93- * are mixed.
92+ * are mixed.
9493 */
9594 public Batch add(RegularStatement statement) {
9695 boolean isCounterOp = statement instanceof BuiltStatement && ((BuiltStatement) statement).isCounterOp();
@@ -102,16 +101,13 @@
102101
103102 this.statements.add(statement);
104103
105- if (statement instanceof BuiltStatement)
106- {
107- this.hasBindMarkers |= ((BuiltStatement)statement).hasBindMarkers;
108- }
109- else
110- {
104+ if (statement instanceof BuiltStatement) {
105+ this.hasBindMarkers |= ((BuiltStatement) statement).hasBindMarkers;
106+ } else {
111107 // For non-BuiltStatement, we cannot know if it includes a bind makers and we assume it does. In practice,
112108 // this means we will always serialize values as strings when there is non-BuiltStatement
113109 this.hasBindMarkers = true;
114- this.nonBuiltStatementValues += ((SimpleStatement)statement).valuesCount();
110+ this.nonBuiltStatementValues += ((SimpleStatement) statement).valuesCount();
115111 }
116112
117113 checkForBindMarkers(null);
@@ -134,8 +130,7 @@
134130
135131 ByteBuffer[] values = new ByteBuffer[nonBuiltStatementValues];
136132 int i = 0;
137- for (RegularStatement statement : statements)
138- {
133+ for (RegularStatement statement : statements) {
139134 if (statement instanceof BuiltStatement)
140135 continue;
141136
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BindMarker.java +2 −2
@@ -17,10 +17,10 @@
1717
1818 /**
1919 * A CQL3 bind marker.
20- * <p>
20+ * <p/>
2121 * This can be either an anonymous bind marker or a named one (but note that
2222 * named ones are only supported starting in Cassandra 2.0.1).
23- * <p>
23+ * <p/>
2424 * Please note that to create a new bind maker object you should use
2525 * {@link QueryBuilder#bindMarker()} (anonymous marker) or
2626 * {@link QueryBuilder#bindMarker(String)} (named marker).
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +12 −14
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.policies.RetryPolicy;
20+
1821 import java.nio.ByteBuffer;
1922 import java.util.ArrayList;
2023 import java.util.List;
2124 import java.util.regex.Pattern;
2225
23-import com.datastax.driver.core.*;
24-import com.datastax.driver.core.policies.RetryPolicy;
25-
2626 /**
2727 * Common ancestor to the query builder built statements.
2828 */
@@ -75,8 +75,7 @@
7575 *
7676 * @param i the index to retrieve.
7777 * @return the value of the {@code i}th value of this statement.
78- *
79- * @throws IllegalStateException if this statement does not have values.
78+ * @throws IllegalStateException if this statement does not have values.
8079 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
8180 */
8281 public Object getObject(int i) {
@@ -103,7 +102,7 @@
103102
104103 if (values.size() > 65535)
105104 throw new IllegalArgumentException("Too many values for built statement, the maximum allowed is 65535");
106-
105+
107106 if (values.isEmpty())
108107 values = null;
109108 }
@@ -184,8 +183,8 @@
184183 return null;
185184
186185 return routingKey.length == 1
187- ? routingKey[0]
188- : compose(routingKey);
186+ ? routingKey[0]
187+ : compose(routingKey);
189188 }
190189
191190 @Override
@@ -231,7 +230,7 @@
231230
232231 /**
233232 * Allows to force this builder to not generate values (through its {@code getValues()} method).
234- * <p>
233+ * <p/>
235234 * By default (and unless the protocol version 1 is in use, see below) and
236235 * for performance reasons, the query builder will not serialize all values
237236 * provided to strings. This means that the {@link #getQueryString} may
@@ -244,13 +243,13 @@
244243 * return {@code null} and that the string returned by {@code
245244 * getQueryString()} will contain no other bind markers than the one
246245 * inputted by the user.
247- * <p>
246+ * <p/>
248247 * If the native protocol version 1 is in use, the driver will default
249248 * to not generating values since those are not supported by that version of
250249 * the protocol. In practice, the driver will automatically call this method
251250 * with {@code true} as argument prior to execution. Hence, calling this
252251 * method when the protocol version 1 is in use is basically a no-op.
253- * <p>
252+ * <p/>
254253 * Note that this method is mainly useful for debugging purpose. In general,
255254 * the default behavior should be the correct and most efficient one.
256255 *
@@ -270,8 +269,7 @@
270269 totalLength += 2 + bb.remaining() + 1;
271270
272271 ByteBuffer out = ByteBuffer.allocate(totalLength);
273- for (ByteBuffer buffer : buffers)
274- {
272+ for (ByteBuffer buffer : buffers) {
275273 ByteBuffer bb = buffer.duplicate();
276274 putShortLength(out, bb.remaining());
277275 out.put(bb);
@@ -294,7 +292,7 @@
294292 T statement;
295293
296294 ForwardingStatement(T statement) {
297- super((String)null);
295+ super((String) null);
298296 this.statement = statement;
299297 }
300298
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +1 −0
@@ -20,6 +20,7 @@
2020 public abstract class Clause extends Utils.Appendeable {
2121
2222 abstract String name();
23+
2324 abstract Object firstValue();
2425
2526 private static abstract class AbstractClause extends Clause {
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +14 −16
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.TableMetadata;
19+
1820 import java.util.ArrayList;
1921 import java.util.List;
2022
21-import com.datastax.driver.core.TableMetadata;
22-
2323 /**
2424 * A built DELETE statement.
2525 */
@@ -86,7 +86,7 @@
8686
8787 /**
8888 * Adds a WHERE clause to this statement.
89- *
89+ * <p/>
9090 * This is a shorter/more readable version for {@code where().and(clause)}.
9191 *
9292 * @param clause the clause to add.
@@ -107,7 +107,7 @@
107107
108108 /**
109109 * Adds a conditions clause (IF) to this statement.
110- * <p>
110+ * <p/>
111111 * This is a shorter/more readable version for {@code onlyIf().and(condition)}.
112112 *
113113 * @param condition the condition to add.
@@ -149,7 +149,7 @@
149149
150150 /**
151151 * Sets the 'IF EXISTS' option for this DELETE statement.
152- *
152+ * <p/>
153153 * <p>
154154 * A delete with that option will report whether the statement actually
155155 * resulted in data being deleted. The existence check and deletion are
@@ -185,8 +185,7 @@
185185 * @param clause the clause to add.
186186 * @return this WHERE clause.
187187 */
188- public Where and(Clause clause)
189- {
188+ public Where and(Clause clause) {
190189 clauses.add(clause);
191190 statement.maybeAddRoutingKey(clause.name(), clause.firstValue());
192191 checkForBindMarkers(clause);
@@ -206,7 +205,7 @@
206205 /**
207206 * Sets the 'IF EXISTS' option for the DELETE statement this WHERE clause
208207 * is part of.
209- *
208+ * <p/>
210209 * <p>
211210 * A delete with that option will report whether the statement actually
212211 * resulted in data being deleted. The existence check and deletion are
@@ -299,7 +298,7 @@
299298 * Adds the table to delete from.
300299 *
301300 * @param keyspace the name of the keyspace to delete from.
302- * @param table the name of the table to delete from.
301+ * @param table the name of the table to delete from.
303302 * @return a newly built DELETE statement that deletes from {@code keyspace.table}.
304303 */
305304 public Delete from(String keyspace, String table) {
@@ -326,7 +325,6 @@
326325 * Deletes all columns (i.e. "DELETE FROM ...")
327326 *
328327 * @return an in-build DELETE statement.
329- *
330328 * @throws IllegalStateException if some columns had already been selected for this builder.
331329 */
332330 public Builder all() {
@@ -351,7 +349,7 @@
351349 * Deletes the provided list element.
352350 *
353351 * @param columnName the name of the list column.
354- * @param idx the index of the element to delete.
352+ * @param idx the index of the element to delete.
355353 * @return this in-build DELETE Selection
356354 */
357355 public Selection listElt(String columnName, int idx) {
@@ -364,7 +362,7 @@
364362 * specified as a bind marker.
365363 *
366364 * @param columnName the name of the list column.
367- * @param idx the index of the element to delete.
365+ * @param idx the index of the element to delete.
368366 * @return this in-build DELETE Selection
369367 */
370368 public Selection listElt(String columnName, BindMarker idx) {
@@ -376,7 +374,7 @@
376374 * Deletes the provided set element.
377375 *
378376 * @param columnName the name of the set column.
379- * @param element the element to delete.
377+ * @param element the element to delete.
380378 * @return this in-build DELETE Selection
381379 */
382380 public Selection setElt(String columnName, Object element) {
@@ -389,7 +387,7 @@
389387 * specified as a bind marker.
390388 *
391389 * @param columnName the name of the set column.
392- * @param element the element to delete.
390+ * @param element the element to delete.
393391 * @return this in-build DELETE Selection
394392 */
395393 public Selection setElt(String columnName, BindMarker element) {
@@ -401,7 +399,7 @@
401399 * Deletes a map element given a key.
402400 *
403401 * @param columnName the name of the map column.
404- * @param key the key for the element to delete.
402+ * @param key the key for the element to delete.
405403 * @return this in-build DELETE Selection
406404 */
407405 public Selection mapElt(String columnName, Object key) {
@@ -489,7 +487,7 @@
489487
490488 /**
491489 * Adds the provided condition for the deletion.
492- * <p>
490+ * <p/>
493491 * Note that while the query builder accept any type of {@code Clause}
494492 * as conditions, Cassandra currently only allows equality ones.
495493 *
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +16 −16
@@ -15,12 +15,12 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.TableMetadata;
19+
1820 import java.util.ArrayList;
1921 import java.util.Arrays;
2022 import java.util.List;
2123
22-import com.datastax.driver.core.TableMetadata;
23-
2424 /**
2525 * A built INSERT statement.
2626 */
@@ -71,7 +71,7 @@
7171 /**
7272 * Adds a column/value pair to the values inserted by this INSERT statement.
7373 *
74- * @param name the name of the column to insert/update.
74+ * @param name the name of the column to insert/update.
7575 * @param value the value to insert/update for {@code name}.
7676 * @return this INSERT statement.
7777 */
@@ -88,10 +88,10 @@
8888 /**
8989 * Adds multiple column/value pairs to the values inserted by this INSERT statement.
9090 *
91- * @param names a list of column names to insert/update.
91+ * @param names a list of column names to insert/update.
9292 * @param values a list of values to insert/update. The {@code i}th
93- * value in {@code values} will be inserted for the {@code i}th column
94- * in {@code names}.
93+ * value in {@code values} will be inserted for the {@code i}th column
94+ * in {@code names}.
9595 * @return this INSERT statement.
9696 * @throws IllegalArgumentException if {@code names.length != values.length}.
9797 */
@@ -102,10 +102,10 @@
102102 /**
103103 * Adds multiple column/value pairs to the values inserted by this INSERT statement.
104104 *
105- * @param names a list of column names to insert/update.
105+ * @param names a list of column names to insert/update.
106106 * @param values a list of values to insert/update. The {@code i}th
107- * value in {@code values} will be inserted for the {@code i}th column
108- * in {@code names}.
107+ * value in {@code values} will be inserted for the {@code i}th column
108+ * in {@code names}.
109109 * @return this INSERT statement.
110110 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
111111 */
@@ -144,15 +144,16 @@
144144 public Options using() {
145145 return usings;
146146 }
147+
147148 /**
148149 * Sets the 'IF NOT EXISTS' option for this INSERT statement.
149- * <p>
150+ * <p/>
150151 * An insert with that option will not succeed unless the row does not
151152 * exist at the time the insertion is executed. The existence check and
152153 * insertions are done transactionally in the sense that if multiple
153154 * clients attempt to create a given row with this option, then at most one
154155 * may succeed.
155- * <p>
156+ * <p/>
156157 * Please keep in mind that using this option has a non negligible
157158 * performance impact and should be avoided when possible.
158159 *
@@ -189,7 +190,7 @@
189190 /**
190191 * Adds a column/value pair to the values inserted by this INSERT statement.
191192 *
192- * @param name the name of the column to insert/update.
193+ * @param name the name of the column to insert/update.
193194 * @param value the value to insert/update for {@code name}.
194195 * @return the INSERT statement those options are part of.
195196 */
@@ -200,12 +201,11 @@
200201 /**
201202 * Adds multiple column/value pairs to the values inserted by this INSERT statement.
202203 *
203- * @param names a list of column names to insert/update.
204+ * @param names a list of column names to insert/update.
204205 * @param values a list of values to insert/update. The {@code i}th
205- * value in {@code values} will be inserted for the {@code i}th column
206- * in {@code names}.
206+ * value in {@code values} will be inserted for the {@code i}th column
207+ * in {@code names}.
207208 * @return the INSERT statement those options are part of.
208- *
209209 * @throws IllegalArgumentException if {@code names.length != values.length}.
210210 */
211211 public Insert values(String[] names, Object[] values) {
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +103 −108
@@ -15,34 +15,35 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.*;
19-
2018 import com.datastax.driver.core.RegularStatement;
2119 import com.datastax.driver.core.TableMetadata;
2220 import com.datastax.driver.core.exceptions.InvalidQueryException;
2321
22+import java.util.*;
23+
2424 /**
2525 * Static methods to build a CQL3 query.
26- * <p>
26+ * <p/>
2727 * The queries built by this builder will provide a value for the
2828 * {@link com.datastax.driver.core.Statement#getRoutingKey} method only when a
2929 * {@link com.datastax.driver.core.TableMetadata} is provided to the builder.
3030 * It is thus advised to do so if a {@link com.datastax.driver.core.policies.TokenAwarePolicy}
3131 * is in use.
32- * <p>
32+ * <p/>
3333 * The provided builders perform very little validation of the built query.
3434 * There is thus no guarantee that a built query is valid, and it is
3535 * definitively possible to create invalid queries.
36- * <p>
36+ * <p/>
3737 * Note that it could be convenient to use an 'import static' to use the methods of this class.
3838 */
3939 public final class QueryBuilder {
4040
41- private QueryBuilder() {}
41+ private QueryBuilder() {
42+ }
4243
4344 /**
4445 * Start building a new SELECT query that selects the provided names.
45- *
46+ * <p/>
4647 * Note that {@code select(c1, c2)} is just a shortcut for {@code select().column(c1).column(c2) }.
4748 *
4849 * @param columns the columns names that should be selected by the query.
@@ -50,7 +51,7 @@
5051 * least a FROM clause to complete the query).
5152 */
5253 public static Select.Builder select(String... columns) {
53- return new Select.Builder(Arrays.asList((Object[])columns));
54+ return new Select.Builder(Arrays.asList((Object[]) columns));
5455 }
5556
5657 /**
@@ -78,7 +79,7 @@
7879 * Start building a new INSERT query.
7980 *
8081 * @param keyspace the name of the keyspace to use.
81- * @param table the name of the table to insert into.
82+ * @param table the name of the table to insert into.
8283 * @return an in-construction INSERT query.
8384 */
8485 public static Insert insertInto(String keyspace, String table) {
@@ -110,7 +111,7 @@
110111 * Start building a new UPDATE query.
111112 *
112113 * @param keyspace the name of the keyspace to use.
113- * @param table the name of the table to update.
114+ * @param table the name of the table to update.
114115 * @return an in-construction UPDATE query (at least a SET and a WHERE
115116 * clause needs to be provided to complete the query).
116117 */
@@ -153,7 +154,7 @@
153154
154155 /**
155156 * Built a new BATCH query on the provided statements.
156- * <p>
157+ * <p/>
157158 * This method will build a logged batch (this is the default in CQL3). To
158159 * create unlogged batches, use {@link #unloggedBatch}. Also note that
159160 * for convenience, if the provided statements are counter statements, this
@@ -170,14 +171,14 @@
170171
171172 /**
172173 * Built a new UNLOGGED BATCH query on the provided statements.
173- * <p>
174+ * <p/>
174175 * Compared to logged batches (the default), unlogged batch don't
175176 * use the distributed batch log server side and as such are not
176177 * guaranteed to be atomic. In other words, if an unlogged batch
177178 * timeout, some of the batched statements may have been persisted
178179 * while some have not. Unlogged batch will however be slightly
179180 * faster than logged batch.
180- * <p>
181+ * <p/>
181182 * If the statements added to the batch are counter statements, the
182183 * resulting batch will be a COUNTER one.
183184 *
@@ -203,7 +204,7 @@
203204 * Creates a new TRUNCATE query.
204205 *
205206 * @param keyspace the name of the keyspace to use.
206- * @param table the name of the table to truncate.
207+ * @param table the name of the table to truncate.
207208 * @return the truncation query.
208209 */
209210 public static Truncate truncate(String keyspace, String table) {
@@ -246,7 +247,7 @@
246247
247248 /**
248249 * The token of column names.
249- * <p>
250+ * <p/>
250251 * This variant is most useful when the partition key is composite.
251252 *
252253 * @param columnNames the column names to take the token of.
@@ -255,7 +256,7 @@
255256 public static String token(String... columnNames) {
256257 StringBuilder sb = new StringBuilder();
257258 sb.append("token(");
258- Utils.joinAndAppendNames(sb, ",", Arrays.asList((Object[])columnNames));
259+ Utils.joinAndAppendNames(sb, ",", Arrays.asList((Object[]) columnNames));
259260 sb.append(')');
260261 return sb.toString();
261262 }
@@ -264,7 +265,7 @@
264265 * Creates an "equal" where clause stating the provided column must be
265266 * equal to the provided value.
266267 *
267- * @param name the column name
268+ * @param name the column name
268269 * @param value the value
269270 * @return the corresponding where clause.
270271 */
@@ -276,31 +277,31 @@
276277 * Create an "in" where clause stating the provided column must be equal
277278 * to one of the provided values.
278279 *
279- * @param name the column name
280+ * @param name the column name
280281 * @param values the values
281282 * @return the corresponding where clause.
282283 */
283284 public static Clause in(String name, Object... values) {
284285 return new Clause.InClause(name, Arrays.asList(values));
285286 }
286-
287+
287288 /**
288289 * Create an "in" where clause stating the provided column must be equal
289290 * to one of the provided values.
290291 *
291- * @param name the column name
292+ * @param name the column name
292293 * @param values the values
293294 * @return the corresponding where clause.
294295 */
295- public static Clause in(String name, List<?> values) {
296- return new Clause.InClause(name, values);
297- }
296+ public static Clause in(String name, List<?> values) {
297+ return new Clause.InClause(name, values);
298+ }
298299
299300 /**
300301 * Creates a "contains" where clause stating the provided column must contain
301302 * the value provided.
302303 *
303- * @param name the column name
304+ * @param name the column name
304305 * @param value the value
305306 * @return the corresponding where clause.
306307 */
@@ -313,7 +314,7 @@
313314 * the key provided.
314315 *
315316 * @param name the column name
316- * @param key the key
317+ * @param key the key
317318 * @return the corresponding where clause.
318319 */
319320 public static Clause containsKey(String name, Object key) {
@@ -324,7 +325,7 @@
324325 * Creates a "lesser than" where clause stating the provided column must be less than
325326 * the provided value.
326327 *
327- * @param name the column name
328+ * @param name the column name
328329 * @param value the value
329330 * @return the corresponding where clause.
330331 */
@@ -334,16 +335,15 @@
334335
335336 /**
336337 * Creates a "lesser than" where clause for a group of clustering columns.
337- * <p>
338+ * <p/>
338339 * For instance, {@code lt(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
339340 * will generate the CQL WHERE clause {@code (a, b) &lt; (2, 'test') }.
340- * <p>
341+ * <p/>
341342 * Please note that this variant is only supported starting with Cassandra 2.0.6.
342343 *
343- * @param names the column names
344+ * @param names the column names
344345 * @param values the values
345346 * @return the corresponding where clause.
346- *
347347 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
348348 */
349349 public static Clause lt(List<String> names, List<?> values) {
@@ -357,7 +357,7 @@
357357 * Creates a "lesser than or equal" where clause stating the provided column must
358358 * be lesser than or equal to the provided value.
359359 *
360- * @param name the column name
360+ * @param name the column name
361361 * @param value the value
362362 * @return the corresponding where clause.
363363 */
@@ -367,16 +367,15 @@
367367
368368 /**
369369 * Creates a "lesser than or equal" where clause for a group of clustering columns.
370- * <p>
370+ * <p/>
371371 * For instance, {@code lte(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
372372 * will generate the CQL WHERE clause {@code (a, b) &lte; (2, 'test') }.
373- * <p>
373+ * <p/>
374374 * Please note that this variant is only supported starting with Cassandra 2.0.6.
375375 *
376- * @param names the column names
376+ * @param names the column names
377377 * @param values the values
378378 * @return the corresponding where clause.
379- *
380379 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
381380 */
382381 public static Clause lte(List<String> names, List<?> values) {
@@ -390,7 +389,7 @@
390389 * Creates a "greater than" where clause stating the provided column must
391390 * be greater to the provided value.
392391 *
393- * @param name the column name
392+ * @param name the column name
394393 * @param value the value
395394 * @return the corresponding where clause.
396395 */
@@ -400,16 +399,15 @@
400399
401400 /**
402401 * Creates a "greater than" where clause for a group of clustering columns.
403- * <p>
402+ * <p/>
404403 * For instance, {@code gt(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
405404 * will generate the CQL WHERE clause {@code (a, b) &gt; (2, 'test') }.
406- * <p>
405+ * <p/>
407406 * Please note that this variant is only supported starting with Cassandra 2.0.6.
408407 *
409- * @param names the column names
408+ * @param names the column names
410409 * @param values the values
411410 * @return the corresponding where clause.
412- *
413411 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
414412 */
415413 public static Clause gt(List<String> names, List<?> values) {
@@ -423,7 +421,7 @@
423421 * Creates a "greater than or equal" where clause stating the provided
424422 * column must be greater than or equal to the provided value.
425423 *
426- * @param name the column name
424+ * @param name the column name
427425 * @param value the value
428426 * @return the corresponding where clause.
429427 */
@@ -433,16 +431,15 @@
433431
434432 /**
435433 * Creates a "greater than or equal" where clause for a group of clustering columns.
436- * <p>
434+ * <p/>
437435 * For instance, {@code gte(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
438436 * will generate the CQL WHERE clause {@code (a, b) &gte; (2, 'test') }.
439- * <p>
437+ * <p/>
440438 * Please note that this variant is only supported starting with Cassandra 2.0.6.
441439 *
442- * @param names the column names
440+ * @param names the column names
443441 * @param values the values
444442 * @return the corresponding where clause.
445- *
446443 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
447444 */
448445 public static Clause gte(List<String> names, List<?> values) {
@@ -477,7 +474,6 @@
477474 *
478475 * @param timestamp the timestamp (in microseconds) to use.
479476 * @return the corresponding option
480- *
481477 * @throws IllegalArgumentException if {@code timestamp &lt; 0}.
482478 */
483479 public static Using timestamp(long timestamp) {
@@ -502,7 +498,6 @@
502498 *
503499 * @param ttl the ttl (in seconds) to use.
504500 * @return the corresponding option
505- *
506501 * @throws IllegalArgumentException if {@code ttl &lt; 0}.
507502 */
508503 public static Using ttl(int ttl) {
@@ -524,10 +519,10 @@
524519
525520 /**
526521 * Simple "set" assignment of a value to a column.
527- * <p>
522+ * <p/>
528523 * This will generate: {@code name = value}.
529524 *
530- * @param name the column name
525+ * @param name the column name
531526 * @param value the value to assign
532527 * @return the correspond assignment (to use in an update query)
533528 */
@@ -537,7 +532,7 @@
537532
538533 /**
539534 * Incrementation of a counter column.
540- * <p>
535+ * <p/>
541536 * This will generate: {@code name = name + 1}.
542537 *
543538 * @param name the column name to increment
@@ -549,10 +544,10 @@
549544
550545 /**
551546 * Incrementation of a counter column by a provided value.
552- * <p>
547+ * <p/>
553548 * This will generate: {@code name = name + value}.
554549 *
555- * @param name the column name to increment
550+ * @param name the column name to increment
556551 * @param value the value by which to increment
557552 * @return the correspond assignment (to use in an update query)
558553 */
@@ -562,10 +557,10 @@
562557
563558 /**
564559 * Incrementation of a counter column by a provided value.
565- * <p>
560+ * <p/>
566561 * This will generate: {@code name = name + value}.
567562 *
568- * @param name the column name to increment
563+ * @param name the column name to increment
569564 * @param value a bind marker representing the value by which to increment
570565 * @return the correspond assignment (to use in an update query)
571566 */
@@ -575,7 +570,7 @@
575570
576571 /**
577572 * Decrementation of a counter column.
578- * <p>
573+ * <p/>
579574 * This will generate: {@code name = name - 1}.
580575 *
581576 * @param name the column name to decrement
@@ -587,10 +582,10 @@
587582
588583 /**
589584 * Decrementation of a counter column by a provided value.
590- * <p>
585+ * <p/>
591586 * This will generate: {@code name = name - value}.
592587 *
593- * @param name the column name to decrement
588+ * @param name the column name to decrement
594589 * @param value the value by which to decrement
595590 * @return the correspond assignment (to use in an update query)
596591 */
@@ -600,10 +595,10 @@
600595
601596 /**
602597 * Decrementation of a counter column by a provided value.
603- * <p>
598+ * <p/>
604599 * This will generate: {@code name = name - value}.
605600 *
606- * @param name the column name to decrement
601+ * @param name the column name to decrement
607602 * @param value a bind marker representing the value by which to decrement
608603 * @return the correspond assignment (to use in an update query)
609604 */
@@ -613,10 +608,10 @@
613608
614609 /**
615610 * Prepend a value to a list column.
616- * <p>
611+ * <p/>
617612 * This will generate: {@code name = [ value ] + name}.
618613 *
619- * @param name the column name (must be of type list).
614+ * @param name the column name (must be of type list).
620615 * @param value the value to prepend. Using a BindMarker here is not supported.
621616 * To use a BindMarker use {@code QueryBuilder#prependAll} with a
622617 * singleton list.
@@ -631,7 +626,7 @@
631626
632627 /**
633628 * Prepend a list of values to a list column.
634- * <p>
629+ * <p/>
635630 * This will generate: {@code name = list + name}.
636631 *
637632 * @param name the column name (must be of type list).
@@ -644,7 +639,7 @@
644639
645640 /**
646641 * Prepend a list of values to a list column.
647- * <p>
642+ * <p/>
648643 * This will generate: {@code name = list + name}.
649644 *
650645 * @param name the column name (must be of type list).
@@ -657,10 +652,10 @@
657652
658653 /**
659654 * Append a value to a list column.
660- * <p>
655+ * <p/>
661656 * This will generate: {@code name = name + [value]}.
662657 *
663- * @param name the column name (must be of type list).
658+ * @param name the column name (must be of type list).
664659 * @param value the value to append. Using a BindMarker here is not supported.
665660 * To use a BindMarker use {@code QueryBuilder#appendAll} with a
666661 * singleton list.
@@ -675,7 +670,7 @@
675670
676671 /**
677672 * Append a list of values to a list column.
678- * <p>
673+ * <p/>
679674 * This will generate: {@code name = name + list}.
680675 *
681676 * @param name the column name (must be of type list).
@@ -688,7 +683,7 @@
688683
689684 /**
690685 * Append a list of values to a list column.
691- * <p>
686+ * <p/>
692687 * This will generate: {@code name = name + list}.
693688 *
694689 * @param name the column name (must be of type list).
@@ -701,10 +696,10 @@
701696
702697 /**
703698 * Discard a value from a list column.
704- * <p>
699+ * <p/>
705700 * This will generate: {@code name = name - [value]}.
706701 *
707- * @param name the column name (must be of type list).
702+ * @param name the column name (must be of type list).
708703 * @param value the value to discard. Using a BindMarker here is not supported.
709704 * To use a BindMarker use {@code QueryBuilder#discardAll} with a singleton list.
710705 * @return the correspond assignment (to use in an update query)
@@ -718,7 +713,7 @@
718713
719714 /**
720715 * Discard a list of values to a list column.
721- * <p>
716+ * <p/>
722717 * This will generate: {@code name = name - list}.
723718 *
724719 * @param name the column name (must be of type list).
@@ -731,7 +726,7 @@
731726
732727 /**
733728 * Discard a list of values to a list column.
734- * <p>
729+ * <p/>
735730 * This will generate: {@code name = name - list}.
736731 *
737732 * @param name the column name (must be of type list).
@@ -744,11 +739,11 @@
744739
745740 /**
746741 * Sets a list column value by index.
747- * <p>
742+ * <p/>
748743 * This will generate: {@code name[idx] = value}.
749744 *
750- * @param name the column name (must be of type list).
751- * @param idx the index to set
745+ * @param name the column name (must be of type list).
746+ * @param idx the index to set
752747 * @param value the value to set
753748 * @return the correspond assignment (to use in an update query)
754749 */
@@ -758,17 +753,17 @@
758753
759754 /**
760755 * Adds a value to a set column.
761- * <p>
756+ * <p/>
762757 * This will generate: {@code name = name + {value}}.
763758 *
764- * @param name the column name (must be of type set).
759+ * @param name the column name (must be of type set).
765760 * @param value the value to add. Using a BindMarker here is not supported.
766761 * To use a BindMarker use {@code QueryBuilder#addAll} with a
767762 * singleton set.
768763 * @return the correspond assignment (to use in an update query)
769764 */
770765 public static Assignment add(String name, Object value) {
771- if (value instanceof BindMarker){
766+ if (value instanceof BindMarker) {
772767 throw new InvalidQueryException("Binding a value in add() is not supported, use addAll() and bind a singleton list");
773768 }
774769 return addAll(name, Collections.singleton(value));
@@ -776,11 +771,11 @@
776771
777772 /**
778773 * Adds a set of values to a set column.
779- * <p>
774+ * <p/>
780775 * This will generate: {@code name = name + set}.
781776 *
782777 * @param name the column name (must be of type set).
783- * @param set the set of values to append
778+ * @param set the set of values to append
784779 * @return the correspond assignment (to use in an update query)
785780 */
786781 public static Assignment addAll(String name, Set<?> set) {
@@ -789,11 +784,11 @@
789784
790785 /**
791786 * Adds a set of values to a set column.
792- * <p>
787+ * <p/>
793788 * This will generate: {@code name = name + set}.
794789 *
795790 * @param name the column name (must be of type set).
796- * @param set a bind marker representing the set of values to append
791+ * @param set a bind marker representing the set of values to append
797792 * @return the correspond assignment (to use in an update query)
798793 */
799794 public static Assignment addAll(String name, BindMarker set) {
@@ -802,10 +797,10 @@
802797
803798 /**
804799 * Remove a value from a set column.
805- * <p>
800+ * <p/>
806801 * This will generate: {@code name = name - {value}}.
807802 *
808- * @param name the column name (must be of type set).
803+ * @param name the column name (must be of type set).
809804 * @param value the value to remove. Using a BindMarker here is not supported.
810805 * To use a BindMarker use {@code QueryBuilder#removeAll} with a singleton set.
811806 * @return the correspond assignment (to use in an update query)
@@ -819,11 +814,11 @@
819814
820815 /**
821816 * Remove a set of values from a set column.
822- * <p>
817+ * <p/>
823818 * This will generate: {@code name = name - set}.
824819 *
825820 * @param name the column name (must be of type set).
826- * @param set the set of values to remove
821+ * @param set the set of values to remove
827822 * @return the correspond assignment (to use in an update query)
828823 */
829824 public static Assignment removeAll(String name, Set<?> set) {
@@ -832,11 +827,11 @@
832827
833828 /**
834829 * Remove a set of values from a set column.
835- * <p>
830+ * <p/>
836831 * This will generate: {@code name = name - set}.
837832 *
838833 * @param name the column name (must be of type set).
839- * @param set a bind marker representing the set of values to remove
834+ * @param set a bind marker representing the set of values to remove
840835 * @return the correspond assignment (to use in an update query)
841836 */
842837 public static Assignment removeAll(String name, BindMarker set) {
@@ -845,11 +840,11 @@
845840
846841 /**
847842 * Puts a new key/value pair to a map column.
848- * <p>
843+ * <p/>
849844 * This will generate: {@code name[key] = value}.
850845 *
851- * @param name the column name (must be of type map).
852- * @param key the key to put
846+ * @param name the column name (must be of type map).
847+ * @param key the key to put
853848 * @param value the value to put
854849 * @return the correspond assignment (to use in an update query)
855850 */
@@ -859,11 +854,11 @@
859854
860855 /**
861856 * Puts a map of new key/value pairs to a map column.
862- * <p>
857+ * <p/>
863858 * This will generate: {@code name = name + map}.
864859 *
865860 * @param name the column name (must be of type map).
866- * @param map the map of key/value pairs to put
861+ * @param map the map of key/value pairs to put
867862 * @return the correspond assignment (to use in an update query)
868863 */
869864 public static Assignment putAll(String name, Map<?, ?> map) {
@@ -872,11 +867,11 @@
872867
873868 /**
874869 * Puts a map of new key/value pairs to a map column.
875- * <p>
870+ * <p/>
876871 * This will generate: {@code name = name + map}.
877872 *
878873 * @param name the column name (must be of type map).
879- * @param map a bind marker representing the map of key/value pairs to put
874+ * @param map a bind marker representing the map of key/value pairs to put
880875 * @return the correspond assignment (to use in an update query)
881876 */
882877 public static Assignment putAll(String name, BindMarker map) {
@@ -885,7 +880,7 @@
885880
886881 /**
887882 * An object representing an anonymous bind marker (a question mark).
888- * <p>
883+ * <p/>
889884 * This can be used wherever a value is expected. For instance, one can do:
890885 * <pre>
891886 * {@code
@@ -903,7 +898,7 @@
903898
904899 /**
905900 * An object representing a named bind marker.
906- * <p>
901+ * <p/>
907902 * This can be used wherever a value is expected. For instance, one can do:
908903 * <pre>
909904 * {@code
@@ -912,7 +907,7 @@
912907 * PreparedState p = session.prepare(i.toString());
913908 * }
914909 * </pre>
915- * <p>
910+ * <p/>
916911 * Please note that named bind makers are only supported starting with Cassandra 2.0.1.
917912 *
918913 * @param name the name for the bind marker.
@@ -924,19 +919,19 @@
924919
925920 /**
926921 * Protects a value from any interpretation by the query builder.
927- * <p>
922+ * <p/>
928923 * The following table exemplify the behavior of this function:
929924 * <table border=1>
930- * <caption>Examples of use</caption>
931- * <tr><th>Code</th><th>Resulting query string</th></tr>
932- * <tr><td>{@code select().from("t").where(eq("c", "C'est la vie!")); }</td><td>{@code "SELECT * FROM t WHERE c='C''est la vie!';"}</td></tr>
933- * <tr><td>{@code select().from("t").where(eq("c", raw("C'est la vie!"))); }</td><td>{@code "SELECT * FROM t WHERE c=C'est la vie!;"}</td></tr>
934- * <tr><td>{@code select().from("t").where(eq("c", raw("'C'est la vie!'"))); }</td><td>{@code "SELECT * FROM t WHERE c='C'est la vie!';"}</td></tr>
935- * <tr><td>{@code select().from("t").where(eq("c", "now()")); }</td><td>{@code "SELECT * FROM t WHERE c='now()';"}</td></tr>
936- * <tr><td>{@code select().from("t").where(eq("c", raw("now()"))); }</td><td>{@code "SELECT * FROM t WHERE c=now();"}</td></tr>
925+ * <caption>Examples of use</caption>
926+ * <tr><th>Code</th><th>Resulting query string</th></tr>
927+ * <tr><td>{@code select().from("t").where(eq("c", "C'est la vie!")); }</td><td>{@code "SELECT * FROM t WHERE c='C''est la vie!';"}</td></tr>
928+ * <tr><td>{@code select().from("t").where(eq("c", raw("C'est la vie!"))); }</td><td>{@code "SELECT * FROM t WHERE c=C'est la vie!;"}</td></tr>
929+ * <tr><td>{@code select().from("t").where(eq("c", raw("'C'est la vie!'"))); }</td><td>{@code "SELECT * FROM t WHERE c='C'est la vie!';"}</td></tr>
930+ * <tr><td>{@code select().from("t").where(eq("c", "now()")); }</td><td>{@code "SELECT * FROM t WHERE c='now()';"}</td></tr>
931+ * <tr><td>{@code select().from("t").where(eq("c", raw("now()"))); }</td><td>{@code "SELECT * FROM t WHERE c=now();"}</td></tr>
937932 * </table>
938933 * <i>Note: the 2nd and 3rd examples in this table are not a valid CQL3 queries.</i>
939- * <p>
934+ * <p/>
940935 * The use of that method is generally discouraged since it lead to security risks. However,
941936 * if you know what you are doing, it allows to escape the interpretations done by the
942937 * QueryBuilder.
@@ -951,7 +946,7 @@
951946 /**
952947 * Creates a function call.
953948 *
954- * @param name the name of the function to call.
949+ * @param name the name of the function to call.
955950 * @param parameters the parameters for the function.
956951 * @return the function call.
957952 */
@@ -979,7 +974,7 @@
979974
980975 /**
981976 * Declares that the name in argument should be treated as a column name.
982- * <p>
977+ * <p/>
983978 * This mainly meant for use with {@link Select.Selection#fcall} when a
984979 * function should apply to a column name, not a string value.
985980 *
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +30 −38
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.TableMetadata;
19+
1820 import java.util.ArrayList;
1921 import java.util.Arrays;
2022 import java.util.Collections;
2123 import java.util.List;
2224
23-import com.datastax.driver.core.TableMetadata;
24-
2525 /**
2626 * A built SELECT statement.
2727 */
@@ -93,7 +93,7 @@
9393
9494 /**
9595 * Adds a WHERE clause to this statement.
96- *
96+ * <p/>
9797 * This is a shorter/more readable version for {@code where().and(clause)}.
9898 *
9999 * @param clause the clause to add.
@@ -117,9 +117,8 @@
117117 *
118118 * @param orderings the orderings to define for this query.
119119 * @return this statement.
120- *
121120 * @throws IllegalStateException if an ORDER BY clause has already been
122- * provided.
121+ * provided.
123122 */
124123 public Select orderBy(Ordering... orderings) {
125124 if (this.orderings != null)
@@ -136,10 +135,9 @@
136135 *
137136 * @param limit the limit to set.
138137 * @return this statement.
139- *
140138 * @throws IllegalArgumentException if {@code limit &gte; 0}.
141- * @throws IllegalStateException if a LIMIT clause has already been
142- * provided.
139+ * @throws IllegalStateException if a LIMIT clause has already been
140+ * provided.
143141 */
144142 public Select limit(int limit) {
145143 if (limit <= 0)
@@ -158,9 +156,8 @@
158156 *
159157 * @param marker the marker to use for the limit.
160158 * @return this statement.
161- *
162159 * @throws IllegalStateException if a LIMIT clause has already been
163- * provided.
160+ * provided.
164161 */
165162 public Select limit(BindMarker marker) {
166163 if (this.limit != null)
@@ -211,9 +208,8 @@
211208 *
212209 * @param orderings the orderings to add.
213210 * @return the select statement this Where clause if part of.
214- *
215211 * @throws IllegalStateException if an ORDER BY clause has already been
216- * provided.
212+ * provided.
217213 */
218214 public Select orderBy(Ordering... orderings) {
219215 return statement.orderBy(orderings);
@@ -225,10 +221,9 @@
225221 *
226222 * @param limit the limit to set.
227223 * @return the select statement this Where clause if part of.
228- *
229224 * @throws IllegalArgumentException if {@code limit &gte; 0}.
230- * @throws IllegalStateException if a LIMIT clause has already been
231- * provided.
225+ * @throws IllegalStateException if a LIMIT clause has already been
226+ * provided.
232227 */
233228 public Select limit(int limit) {
234229 return statement.limit(limit);
@@ -240,9 +235,8 @@
240235 *
241236 * @param limit the bind marker to use as limit.
242237 * @return the select statement this Where clause if part of.
243- *
244238 * @throws IllegalStateException if a LIMIT clause has already been
245- * provided.
239+ * provided.
246240 */
247241 public Select limit(BindMarker limit) {
248242 return statement.limit(limit);
@@ -257,7 +251,8 @@
257251 List<Object> columnNames;
258252 boolean isDistinct;
259253
260- Builder() {}
254+ Builder() {
255+ }
261256
262257 Builder(List<Object> columnNames) {
263258 this.columnNames = columnNames;
@@ -287,7 +282,7 @@
287282 * Adds the table to select from.
288283 *
289284 * @param keyspace the name of the keyspace to select from.
290- * @param table the name of the table to select from.
285+ * @param table the name of the table to select from.
291286 * @return a newly built SELECT statement that selects from {@code keyspace.table}.
292287 */
293288 public Select from(String keyspace, String table) {
@@ -324,7 +319,6 @@
324319 * Selects all columns (i.e. "SELECT * ...")
325320 *
326321 * @return an in-build SELECT statement.
327- *
328322 * @throws IllegalStateException if some columns had already been selected for this builder.
329323 */
330324 public abstract Builder all();
@@ -333,7 +327,6 @@
333327 * Selects the count of all returned rows (i.e. "SELECT count(*) ...").
334328 *
335329 * @return an in-build SELECT statement.
336- *
337330 * @throws IllegalStateException if some columns had already been selected for this builder.
338331 */
339332 public abstract Builder countAll();
@@ -348,7 +341,7 @@
348341
349342 /**
350343 * Selects the write time of provided column.
351- * <p>
344+ * <p/>
352345 * This is a shortcut for {@code fcall("writetime", QueryBuilder.column(name))}.
353346 *
354347 * @param name the name of the column to select the write time of.
@@ -358,7 +351,7 @@
358351
359352 /**
360353 * Selects the ttl of provided column.
361- * <p>
354+ * <p/>
362355 * This is a shortcut for {@code fcall("ttl", QueryBuilder.column(name))}.
363356 *
364357 * @param name the name of the column to select the ttl of.
@@ -368,16 +361,16 @@
368361
369362 /**
370363 * Creates a function call.
371- * <p>
364+ * <p/>
372365 * Please note that the parameters are interpreted as values, and so
373366 * {@code fcall("textToBlob", "foo")} will generate the string
374367 * {@code "textToBlob('foo')"}. If you want to generate
375368 * {@code "textToBlob(foo)"}, i.e. if the argument must be interpreted
376369 * as a column name (in a select clause), you will need to use the
377- * {@link QueryBuilder#column} method, and so
370+ * {@link QueryBuilder#column} method, and so
378371 * {@code fcall("textToBlob", QueryBuilder.column(foo)}.
379372 *
380- * @param name the name of the function.
373+ * @param name the name of the function.
381374 * @param parameters the parameters for the function call.
382375 * @return this in-build SELECT statement
383376 */
@@ -386,7 +379,7 @@
386379
387380 /**
388381 * An Selection clause for an in-construction SELECT statement.
389- * <p>
382+ * <p/>
390383 * This only differs from {@link Selection} in that you can add an
391384 * alias for the previously selected item through {@link SelectionOrAlias#as}.
392385 */
@@ -394,7 +387,8 @@
394387
395388 private Object previousSelection;
396389
397- SelectionOrAlias() {}
390+ SelectionOrAlias() {
391+ }
398392
399393 /**
400394 * Adds an alias for the just selected item.
@@ -430,7 +424,6 @@
430424 * Selects all columns (i.e. "SELECT * ...")
431425 *
432426 * @return an in-build SELECT statement.
433- *
434427 * @throws IllegalStateException if some columns had already been selected for this builder.
435428 */
436429 public Builder all() {
@@ -439,14 +432,13 @@
439432 if (previousSelection != null)
440433 throw new IllegalStateException(String.format("Some columns ([%s]) have already been selected.", previousSelection));
441434
442- return (Builder)this;
435+ return (Builder) this;
443436 }
444437
445438 /**
446439 * Selects the count of all returned rows (i.e. "SELECT count(*) ...").
447440 *
448441 * @return an in-build SELECT statement.
449- *
450442 * @throws IllegalStateException if some columns had already been selected for this builder.
451443 */
452444 public Builder countAll() {
@@ -456,7 +448,7 @@
456448 throw new IllegalStateException(String.format("Some columns ([%s]) have already been selected.", previousSelection));
457449
458450 columnNames = COUNT_ALL;
459- return (Builder)this;
451+ return (Builder) this;
460452 }
461453
462454 /**
@@ -471,7 +463,7 @@
471463
472464 /**
473465 * Selects the provided raw expression.
474- *
466+ * <p/>
475467 * This method is used internally by the mapper module. It is not exposed on the parent class {@link Selection} to
476468 * avoid breaking binary compatibility. This means that it is not accessible directly via the fluent API (you need
477469 * a cast). This shouldn't be a problem for regular clients because they will use other methods of the DSL
@@ -486,7 +478,7 @@
486478
487479 /**
488480 * Selects the write time of provided column.
489- * <p>
481+ * <p/>
490482 * This is a shortcut for {@code fcall("writetime", QueryBuilder.column(name))}.
491483 *
492484 * @param name the name of the column to select the write time of.
@@ -498,7 +490,7 @@
498490
499491 /**
500492 * Selects the ttl of provided column.
501- * <p>
493+ * <p/>
502494 * This is a shortcut for {@code fcall("ttl", QueryBuilder.column(name))}.
503495 *
504496 * @param name the name of the column to select the ttl of.
@@ -510,13 +502,13 @@
510502
511503 /**
512504 * Creates a function call.
513- * <p>
505+ * <p/>
514506 * Please note that the parameters are interpreted as values, and so
515507 * {@code fcall("textToBlob", "foo")} will generate the string
516508 * {@code "textToBlob('foo')"}. If you want to generate
517509 * {@code "textToBlob(foo)"}, i.e. if the argument must be interpreted
518510 * as a column name (in a select clause), you will need to use the
519- * {@link QueryBuilder#column} method, and so
511+ * {@link QueryBuilder#column} method, and so
520512 * {@code fcall("textToBlob", QueryBuilder.column(foo)}.
521513 */
522514 public SelectionOrAlias fcall(String name, Object... parameters) {
@@ -527,7 +519,7 @@
527519 * Adds the table to select from.
528520 *
529521 * @param keyspace the name of the keyspace to select from.
530- * @param table the name of the table to select from.
522+ * @param table the name of the table to select from.
531523 * @return a newly built SELECT statement that selects from {@code keyspace.table}.
532524 */
533525 @Override
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java +2 −3
@@ -15,11 +15,10 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
19-import java.util.List;
20-
2118 import com.datastax.driver.core.TableMetadata;
2219
20+import java.util.List;
21+
2322 /**
2423 * A built TRUNCATE statement.
2524 */
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +13 −14
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
19-import java.util.ArrayList;
20-import java.util.List;
21-
2218 import com.datastax.driver.core.TableMetadata;
2319 import com.datastax.driver.core.querybuilder.Assignment.CounterAssignment;
2420
21+import java.util.ArrayList;
22+import java.util.List;
23+
2524 /**
2625 * A built UPDATE statement.
2726 */
@@ -92,7 +91,7 @@
9291
9392 /**
9493 * Adds an assignment to this UPDATE statement.
95- *
94+ * <p/>
9695 * This is a shorter/more readable version for {@code with().and(assignment)}.
9796 *
9897 * @param assignment the assignment to add.
@@ -113,7 +112,7 @@
113112
114113 /**
115114 * Adds a WHERE clause to this statement.
116- *
115+ * <p/>
117116 * This is a shorter/more readable version for {@code where().and(clause)}.
118117 *
119118 * @param clause the clause to add.
@@ -134,7 +133,7 @@
134133
135134 /**
136135 * Adds a conditions clause (IF) to this statement.
137- * <p>
136+ * <p/>
138137 * This is a shorter/more readable version for {@code onlyIf().and(condition)}.
139138 *
140139 * @param condition the condition to add.
@@ -274,11 +273,11 @@
274273 public Conditions onlyIf(Clause condition) {
275274 return statement.onlyIf(condition);
276275 }
277-
276+
278277 /**
279278 * Sets the 'IF EXISTS' option for the UPDATE statement this WHERE clause
280279 * is part of.
281- *
280+ * <p/>
282281 * <p>
283282 * An update with that option will report whether the statement actually
284283 * resulted in data being updated. The existence check and update are
@@ -354,10 +353,10 @@
354353
355354 /**
356355 * Conditions for an UPDATE statement.
357- * <p>
356+ * <p/>
358357 * When provided some conditions, an update will not apply unless the
359358 * provided conditions applies.
360- * <p>
359+ * <p/>
361360 * Please keep in mind that provided conditions has a non negligible
362361 * performance impact and should be avoided when possible.
363362 */
@@ -371,7 +370,7 @@
371370
372371 /**
373372 * Adds the provided condition for the update.
374- * <p>
373+ * <p/>
375374 * Note that while the query builder accept any type of {@code Clause}
376375 * as conditions, Cassandra currently only allow equality ones.
377376 *
@@ -413,9 +412,9 @@
413412 public Options using(Using using) {
414413 return statement.using(using);
415414 }
416-
415+
417416 }
418-
417+
419418 public static class IfExists extends BuiltStatement.ForwardingStatement<Update> {
420419 IfExists(Update statement) {
421420 super(statement);
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +34 −32
@@ -15,6 +15,11 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.DataType;
19+import com.datastax.driver.core.ProtocolVersion;
20+import com.datastax.driver.core.TupleValue;
21+import com.datastax.driver.core.UDTValue;
22+
1823 import java.math.BigDecimal;
1924 import java.math.BigInteger;
2025 import java.net.InetAddress;
@@ -24,11 +29,6 @@
2429
2530 import static com.google.common.base.Preconditions.checkNotNull;
2631
27-import com.datastax.driver.core.DataType;
28-import com.datastax.driver.core.ProtocolVersion;
29-import com.datastax.driver.core.TupleValue;
30-import com.datastax.driver.core.UDTValue;
31-
3232 // Static utilities private to the query builder
3333 abstract class Utils {
3434
@@ -111,7 +111,7 @@
111111 msg += " (for blob values, make sure to use a ByteBuffer)";
112112 throw new IllegalArgumentException(msg);
113113 }
114- appendValueString((String)value, sb);
114+ appendValueString((String) value, sb);
115115 }
116116 }
117117
@@ -132,7 +132,7 @@
132132 sb.append(value);
133133 return true;
134134 } else if (value instanceof FCall) {
135- FCall fcall = (FCall)value;
135+ FCall fcall = (FCall) value;
136136 sb.append(fcall.name).append('(');
137137 for (int i = 0; i < fcall.parameters.length; i++) {
138138 if (i > 0)
@@ -142,7 +142,7 @@
142142 sb.append(')');
143143 return true;
144144 } else if (value instanceof CName) {
145- appendName(((CName)value).name, sb);
145+ appendName(((CName) value).name, sb);
146146 return true;
147147 } else if (value == null) {
148148 sb.append("null");
@@ -155,13 +155,13 @@
155155 @SuppressWarnings("rawtypes")
156156 private static boolean appendValueIfCollection(Object value, StringBuilder sb) {
157157 if (value instanceof List) {
158- appendList((List)value, sb);
158+ appendList((List) value, sb);
159159 return true;
160160 } else if (value instanceof Set) {
161- appendSet((Set)value, sb);
161+ appendSet((Set) value, sb);
162162 return true;
163163 } else if (value instanceof Map) {
164- appendMap((Map)value, sb);
164+ appendMap((Map) value, sb);
165165 return true;
166166 } else {
167167 return false;
@@ -183,7 +183,8 @@
183183 sb.append('{');
184184 boolean first = true;
185185 for (Object elt : s) {
186- if (first) first = false; else sb.append(',');
186+ if (first) first = false;
187+ else sb.append(',');
187188 appendValue(elt, sb);
188189 }
189190 sb.append('}');
@@ -208,7 +209,7 @@
208209
209210 private static boolean appendValueIfUdt(Object value, StringBuilder sb) {
210211 if (value instanceof UDTValue) {
211- sb.append(((UDTValue)value).toString());
212+ sb.append(((UDTValue) value).toString());
212213 return true;
213214 } else {
214215 return false;
@@ -217,7 +218,7 @@
217218
218219 private static boolean appendValueIfTuple(Object value, StringBuilder sb) {
219220 if (value instanceof TupleValue) {
220- sb.append(((TupleValue)value).toString());
221+ sb.append(((TupleValue) value).toString());
221222 return true;
222223 } else {
223224 return false;
@@ -228,15 +229,15 @@
228229 if (value instanceof BindMarker)
229230 return true;
230231 if (value instanceof FCall)
231- for (Object param : ((FCall)value).parameters)
232+ for (Object param : ((FCall) value).parameters)
232233 if (containsBindMarker(param))
233234 return true;
234235 if (value instanceof Collection)
235- for (Object elt : (Collection)value)
236+ for (Object elt : (Collection) value)
236237 if (containsBindMarker(elt))
237238 return true;
238239 if (value instanceof Map)
239- for (Map.Entry<?,?> entry : ((Map<?,?>)value).entrySet())
240+ for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet())
240241 if (containsBindMarker(entry.getKey()) || containsBindMarker(entry.getValue()))
241242 return true;
242243 return false;
@@ -246,11 +247,11 @@
246247 if (value instanceof BindMarker || value instanceof FCall || value instanceof CName || value instanceof RawString)
247248 return true;
248249 if (value instanceof Collection)
249- for (Object elt : (Collection)value)
250+ for (Object elt : (Collection) value)
250251 if (containsSpecialValue(elt))
251252 return true;
252253 if (value instanceof Map)
253- for (Map.Entry<?,?> entry : ((Map<?,?>)value).entrySet())
254+ for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet())
254255 if (containsSpecialValue(entry.getKey()) || containsSpecialValue(entry.getValue()))
255256 return true;
256257 return false;
@@ -275,34 +276,34 @@
275276 if (value instanceof Number && !(value instanceof BigInteger || value instanceof BigDecimal))
276277 return false;
277278 if (value instanceof Collection)
278- for (Object elt : (Collection)value)
279+ for (Object elt : (Collection) value)
279280 if (!isSerializable(elt))
280281 return false;
281282 if (value instanceof Map)
282- for (Map.Entry<?,?> entry : ((Map<?,?>)value).entrySet())
283+ for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet())
283284 if (!isSerializable(entry.getKey()) || !isSerializable(entry.getValue()))
284285 return false;
285286 return true;
286287 }
287288
288289 static boolean isIdempotent(Object value) {
289- if(value == null) {
290+ if (value == null) {
290291 return true;
291292 } else if (value instanceof Assignment) {
292- Assignment assignment = (Assignment)value;
293+ Assignment assignment = (Assignment) value;
293294 return assignment.isIdempotent();
294295 } else if (value instanceof FCall) {
295296 return false;
296297 } else if (value instanceof RawString) {
297298 return false;
298- } else if(value instanceof Collection) {
299- for (Object elt : ((Collection)value)) {
300- if(!isIdempotent(elt))
299+ } else if (value instanceof Collection) {
300+ for (Object elt : ((Collection) value)) {
301+ if (!isIdempotent(elt))
301302 return false;
302303 }
303304 return true;
304305 } else if (value instanceof Map) {
305- for (Map.Entry<?, ?> entry : ((Map<?, ?>)value).entrySet()) {
306+ for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
306307 if (!isIdempotent(entry.getKey()) || !isIdempotent(entry.getValue()))
307308 return false;
308309 }
@@ -330,11 +331,11 @@
330331
331332 static StringBuilder appendName(Object name, StringBuilder sb) {
332333 if (name instanceof String) {
333- appendName((String)name, sb);
334+ appendName((String) name, sb);
334335 } else if (name instanceof CName) {
335- appendName(((CName)name).name, sb);
336+ appendName(((CName) name).name, sb);
336337 } else if (name instanceof FCall) {
337- FCall fcall = (FCall)name;
338+ FCall fcall = (FCall) name;
338339 sb.append(fcall.name).append('(');
339340 for (int i = 0; i < fcall.parameters.length; i++) {
340341 if (i > 0)
@@ -343,11 +344,11 @@
343344 }
344345 sb.append(')');
345346 } else if (name instanceof Alias) {
346- Alias alias = (Alias)name;
347+ Alias alias = (Alias) name;
347348 appendName(alias.column, sb);
348349 sb.append(" AS ").append(alias.alias);
349350 } else if (name instanceof RawString) {
350- sb.append(((RawString)name).str);
351+ sb.append(((RawString) name).str);
351352 } else {
352353 throw new IllegalArgumentException(String.format("Invalid column %s of type unknown of the query builder", name));
353354 }
@@ -356,6 +357,7 @@
356357
357358 static abstract class Appendeable {
358359 abstract void appendTo(StringBuilder sb, List<Object> values);
360+
359361 abstract boolean containsBindMarker();
360362 }
361363
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/package-info.java +1 −1
@@ -15,7 +15,7 @@
1515 */
1616 /**
1717 * A CQL3 query builder.
18- * <p>
18+ * <p/>
1919 * The main entry for this package is the {@code QueryBuilder} class.
2020 */
2121 package com.datastax.driver.core.querybuilder;
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AbstractCreateStatement.java +23 −25
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import java.util.LinkedHashMap;
19-import java.util.Map;
20-
18+import com.datastax.driver.core.DataType;
2119 import com.google.common.base.Optional;
2220
23-import com.datastax.driver.core.DataType;
21+import java.util.LinkedHashMap;
22+import java.util.Map;
2423
2524 public abstract class AbstractCreateStatement<T extends AbstractCreateStatement<T>> extends SchemaStatement {
2625
@@ -29,7 +28,7 @@
2928 protected Map<String, ColumnType> simpleColumns = new LinkedHashMap<String, ColumnType>();
3029
3130 @SuppressWarnings("unchecked")
32- private T self = (T)this;
31+ private T self = (T) this;
3332
3433 /**
3534 * Add the 'IF NOT EXISTS' condition to this CREATE statement.
@@ -43,25 +42,25 @@
4342
4443 /**
4544 * Add a column definition to this CREATE statement.
46- *
47- * <p>
45+ * <p/>
46+ * <p/>
4847 * To add a list column:
4948 * <pre class="code"><code class="java">
50- * addColumn("myList",DataType.list(DataType.text()))
49+ * addColumn("myList",DataType.list(DataType.text()))
5150 * </code></pre>
52- *
51+ * <p/>
5352 * To add a set column:
5453 * <pre class="code"><code class="java">
55- * addColumn("mySet",DataType.set(DataType.text()))
54+ * addColumn("mySet",DataType.set(DataType.text()))
5655 * </code></pre>
57- *
56+ * <p/>
5857 * To add a map column:
5958 * <pre class="code"><code class="java">
60- * addColumn("myMap",DataType.map(DataType.cint(),DataType.text()))
59+ * addColumn("myMap",DataType.map(DataType.cint(),DataType.text()))
6160 * </code></pre>
6261 *
6362 * @param columnName the name of the column to be added.
64- * @param dataType the data type of the column to be added.
63+ * @param dataType the data type of the column to be added.
6564 * @return this CREATE statement.
6665 */
6766 public T addColumn(String columnName, DataType dataType) {
@@ -76,7 +75,7 @@
7675 * Add a column definition to this CREATE statement, when the type contains a UDT.
7776 *
7877 * @param columnName the name of the column to be added.
79- * @param udtType the UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
78+ * @param udtType the UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
8079 * @return this CREATE statement.
8180 */
8281 public T addUDTColumn(String columnName, UDTType udtType) {
@@ -91,7 +90,7 @@
9190 * Shorthand to add a column definition to this CREATE statement, when the type is a list of UDT.
9291 *
9392 * @param columnName the name of the column to be added
94- * @param udtType the udt type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
93+ * @param udtType the udt type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
9594 * @return this CREATE statement.
9695 */
9796 public T addUDTListColumn(String columnName, UDTType udtType) {
@@ -106,7 +105,7 @@
106105 * Shorthand to add a column definition to this CREATE statement, when the type is a set of UDT.
107106 *
108107 * @param columnName the name of the column to be added
109- * @param udtType the udt type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
108+ * @param udtType the udt type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
110109 * @return this CREATE statement.
111110 */
112111 public T addUDTSetColumn(String columnName, UDTType udtType) {
@@ -119,14 +118,14 @@
119118
120119 /**
121120 * Shorthand to add a column definition to this CREATE statement, when the type is a map with a UDT value type.
122- * <p>
121+ * <p/>
123122 * Example:
124123 * <pre>
125124 * addUDTMapColumn("addresses", DataType.text(), frozen("address"));
126125 * </pre>
127126 *
128- * @param columnName the name of the column to be added.
129- * @param keyType the key type of the column to be added.
127+ * @param columnName the name of the column to be added.
128+ * @param keyType the key type of the column to be added.
130129 * @param valueUdtType the value UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
131130 * @return this CREATE statement.
132131 */
@@ -141,7 +140,7 @@
141140
142141 /**
143142 * Shorthand to add a column definition to this CREATE statement, when the type is a map with a UDT key type.
144- * <p>
143+ * <p/>
145144 * Example:
146145 * <pre>
147146 * addUDTMapColumn("roles", frozen("user"), DataType.text());
@@ -149,7 +148,7 @@
149148 *
150149 * @param columnName the name of the column to be added.
151150 * @param udtKeyType the key UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
152- * @param valueType the value raw type of the column to be added.
151+ * @param valueType the value raw type of the column to be added.
153152 * @return this CREATE statement.
154153 */
155154 public T addUDTMapColumn(String columnName, UDTType udtKeyType, DataType valueType) {
@@ -163,17 +162,16 @@
163162
164163 /**
165164 * Shorthand to add a column definition to this CREATE statement, when the type is a map with UDT key and value types.
166- * <p>
165+ * <p/>
167166 * Example:
168167 * <pre>
169168 * addUDTMapColumn("users", frozen("user"), frozen("address"));
170169 * </pre>
171170 *
172- * @param columnName the name of the column to be added.
173- * @param udtKeyType the key UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
171+ * @param columnName the name of the column to be added.
172+ * @param udtKeyType the key UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
174173 * @param udtValueType the value UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
175174 * @return this CREATE statement.
176- *
177175 */
178176 public T addUDTMapColumn(String columnName, UDTType udtKeyType, UDTType udtValueType) {
179177 validateNotEmpty(columnName, "Column name");
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Alter.java +15 −16
@@ -15,11 +15,10 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import java.util.List;
19-
18+import com.datastax.driver.core.DataType;
2019 import com.google.common.base.Optional;
2120
22-import com.datastax.driver.core.DataType;
21+import java.util.List;
2322
2423 import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotEmpty;
2524 import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotKeyWord;
@@ -49,7 +48,7 @@
4948
5049 /**
5150 * Add an ALTER column clause (to change the column type) to this ALTER TABLE statement.
52-
51+ *
5352 * @param columnName the name of the column to be altered.
5453 * @return a new {@link Alter.AlterColumn} instance.
5554 */
@@ -85,9 +84,9 @@
8584
8685 /**
8786 * Add a new DROP column clause to this ALTER TABLE statement.
88- * <p>
87+ * <p/>
8988 * Note that you cannot drop a column that is part of the primary key.
90-
89+ *
9190 * @param columnName the name of the column to be dropped.
9291 * @return the final ALTER TABLE DROP COLUMN statement.
9392 */
@@ -99,7 +98,7 @@
9998
10099 /**
101100 * Add a new RENAME column clause to this ALTER TABLE statement.
102- * <p>
101+ * <p/>
103102 * Note that you can only rename a column that is part of the primary key.
104103 *
105104 * @param columnName the name of the column to be renamed.
@@ -141,7 +140,7 @@
141140 */
142141 public SchemaStatement type(DataType type) {
143142 return SchemaStatement.fromQueryString(
144- alter.buildInternal() + " ALTER " + columnName + " TYPE " + type.toString());
143+ alter.buildInternal() + " ALTER " + columnName + " TYPE " + type.toString());
145144 }
146145
147146 /**
@@ -152,7 +151,7 @@
152151 */
153152 public SchemaStatement udtType(UDTType udtType) {
154153 return SchemaStatement.fromQueryString(
155- alter.buildInternal() + " ALTER " + columnName + " TYPE " + udtType.asCQLString());
154+ alter.buildInternal() + " ALTER " + columnName + " TYPE " + udtType.asCQLString());
156155 }
157156 }
158157
@@ -179,8 +178,8 @@
179178 */
180179 public SchemaStatement type(DataType type) {
181180 return SchemaStatement.fromQueryString(
182- alter.buildInternal() + " ADD " + columnName + " " + type.toString()
183- + (staticColumn ? " static" : ""));
181+ alter.buildInternal() + " ADD " + columnName + " " + type.toString()
182+ + (staticColumn ? " static" : ""));
184183 }
185184
186185 /**
@@ -191,8 +190,8 @@
191190 */
192191 public SchemaStatement udtType(UDTType udtType) {
193192 return SchemaStatement.fromQueryString(
194- alter.buildInternal() + " ADD " + columnName + " " + udtType.asCQLString()
195- + (staticColumn ? " static" : ""));
193+ alter.buildInternal() + " ADD " + columnName + " " + udtType.asCQLString()
194+ + (staticColumn ? " static" : ""));
196195 }
197196 }
198197
@@ -219,7 +218,7 @@
219218 validateNotEmpty(newColumnName, "New column name");
220219 validateNotKeyWord(newColumnName, String.format("The new column name '%s' is not allowed because it is a reserved keyword", newColumnName));
221220 return SchemaStatement.fromQueryString(
222- alter.buildInternal() + " RENAME " + columnName + " TO " + newColumnName);
221+ alter.buildInternal() + " RENAME " + columnName + " TO " + newColumnName);
223222 }
224223 }
225224
@@ -241,8 +240,8 @@
241240 @Override
242241 public String buildInternal() {
243242 String tableSpec = keyspaceName.isPresent()
244- ? keyspaceName.get() + "." + tableName
245- : tableName;
243+ ? keyspaceName.get() + "." + tableName
244+ : tableName;
246245
247246 return SchemaStatement.STATEMENT_START + "ALTER TABLE " + tableSpec;
248247 }
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/ColumnType.java +1 −3
@@ -15,11 +15,9 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import com.datastax.driver.core.DataType;
19-
2018 /**
2119 * Wrapper around UDT and non-UDT types.
22- * <p>
20+ * <p/>
2321 * The reason for this interface is that the core API doesn't let us build {@link com.datastax.driver.core.DataType}s representing UDTs, we have to obtain
2422 * them from the cluster metadata. Since we want to use SchemaBuilder without a Cluster instance, UDT types will be provided via
2523 * {@link UDTType} instances.
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Create.java +25 −26
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import java.util.*;
19-
20-import static java.util.Map.Entry;
21-
18+import com.datastax.driver.core.DataType;
2219 import com.google.common.base.Joiner;
2320 import com.google.common.base.Objects;
2421 import com.google.common.base.Optional;
2522 import com.google.common.collect.Lists;
2623
27-import com.datastax.driver.core.DataType;
24+import java.util.*;
25+
26+import static java.util.Map.Entry;
2827
2928 /**
3029 * A built CREATE TABLE statement.
@@ -53,13 +52,13 @@
5352
5453 /**
5554 * Add a partition key column definition to this CREATE TABLE statement.
56- * <p>
55+ * <p/>
5756 * This includes the column declaration (you don't need an additional {@code addColumn} call).
58- * <p>
57+ * <p/>
5958 * Partition key columns are added in the order of their declaration.
6059 *
6160 * @param columnName the name of the partition key column to be added.
62- * @param dataType the data type of the partition key column to be added.
61+ * @param dataType the data type of the partition key column to be added.
6362 * @return this CREATE statement.
6463 */
6564 public Create addPartitionKey(String columnName, DataType dataType) {
@@ -72,13 +71,13 @@
7271
7372 /**
7473 * Add a partition key column definition to this CREATE TABLE statement, when its type contains a UDT.
75- * <p>
74+ * <p/>
7675 * This includes the column declaration (you don't need an additional {@code addColumn} call).
77- * <p>
76+ * <p/>
7877 * Partition key columns are added in the order of their declaration.
7978 *
8079 * @param columnName the name of the partition key column to be added.
81- * @param udtType the UDT type of the partition key column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
80+ * @param udtType the UDT type of the partition key column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
8281 * @return this CREATE statement.
8382 */
8483 public Create addUDTPartitionKey(String columnName, UDTType udtType) {
@@ -91,13 +90,13 @@
9190
9291 /**
9392 * Add a clustering column definition to this CREATE TABLE statement.
94- * <p>
93+ * <p/>
9594 * This includes the column declaration (you don't need an additional {@code addColumn} call).
96- * <p>
95+ * <p/>
9796 * Clustering columns are added in the order of their declaration.
9897 *
9998 * @param columnName the name of the clustering column to be added.
100- * @param dataType the data type of the clustering column to be added.
99+ * @param dataType the data type of the clustering column to be added.
101100 * @return this CREATE statement.
102101 */
103102 public Create addClusteringColumn(String columnName, DataType dataType) {
@@ -110,13 +109,13 @@
110109
111110 /**
112111 * Add a clustering column definition to this CREATE TABLE statement, when its type contains a UDT.
113- * <p>
112+ * <p/>
114113 * This includes the column declaration (you don't need an additional {@code addColumn} call).
115- * <p>
114+ * <p/>
116115 * Clustering columns are added in the order of their declaration.
117116 *
118117 * @param columnName the name of the clustering column to be added.
119- * @param udtType the UDT type of the clustering column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
118+ * @param udtType the UDT type of the clustering column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
120119 * @return this CREATE statement.
121120 */
122121 public Create addUDTClusteringColumn(String columnName, UDTType udtType) {
@@ -131,7 +130,7 @@
131130 * Add a static column definition to this CREATE TABLE statement.
132131 *
133132 * @param columnName the name of the column to be added.
134- * @param dataType the data type of the column to be added.
133+ * @param dataType the data type of the column to be added.
135134 * @return this CREATE statement.
136135 */
137136 public Create addStaticColumn(String columnName, DataType dataType) {
@@ -146,7 +145,7 @@
146145 * Add a static column definition to this CREATE TABLE statement, when its type contains a UDT.
147146 *
148147 * @param columnName the name of the column to be added.
149- * @param udtType the UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
148+ * @param udtType the UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
150149 * @return this CREATE statement.
151150 */
152151 public Create addUDTStaticColumn(String columnName, UDTType udtType) {
@@ -184,11 +183,11 @@
184183
185184 /**
186185 * Add a clustering order for this table.
187- * <p>
186+ * <p/>
188187 * To define the order on multiple columns, call this method repeatedly. The columns will be declared in the call order.
189188 *
190189 * @param columnName the clustering column name.
191- * @param direction the clustering direction (DESC/ASC).
190+ * @param direction the clustering direction (DESC/ASC).
192191 * @return this {@code Options} object.
193192 */
194193 public Options clusteringOrder(String columnName, SchemaBuilder.Direction direction) {
@@ -238,7 +237,7 @@
238237 return true;
239238 }
240239 if (o instanceof ClusteringOrder) {
241- ClusteringOrder that = (ClusteringOrder)o;
240+ ClusteringOrder that = (ClusteringOrder) o;
242241 return Objects.equal(this.clusteringColumnName, that.clusteringColumnName) && Objects.equal(this.direction, that.direction);
243242 }
244243 return false;
@@ -306,12 +305,12 @@
306305 }
307306
308307 String partitionKeyPart = partitionKeyColumns.size() == 1 ?
309- partitionKeyColumns.get(0)
310- : "(" + Joiner.on(", ").join(partitionKeyColumns) + ")";
308+ partitionKeyColumns.get(0)
309+ : "(" + Joiner.on(", ").join(partitionKeyColumns) + ")";
311310
312311 String primaryKeyPart = clusteringKeyColumns.size() == 0 ?
313- partitionKeyPart
314- : partitionKeyPart + ", " + Joiner.on(", ").join(clusteringKeyColumns);
312+ partitionKeyPart
313+ : partitionKeyPart + ", " + Joiner.on(", ").join(clusteringKeyColumns);
315314
316315 createStatement.append("(").append(COLUMN_FORMATTING);
317316 createStatement.append(Joiner.on("," + COLUMN_FORMATTING).join(allColumns));
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateIndex.java +3 −4
@@ -17,9 +17,7 @@
1717
1818 import com.google.common.base.Optional;
1919
20-import static com.datastax.driver.core.schemabuilder.SchemaStatement.STATEMENT_START;
21-import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotEmpty;
22-import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotKeyWord;
20+import static com.datastax.driver.core.schemabuilder.SchemaStatement.*;
2321
2422 /**
2523 * A built CREATE INDEX statement.
@@ -53,7 +51,7 @@
5351 * Specify the keyspace and table to create the index on.
5452 *
5553 * @param keyspaceName the keyspace name.
56- * @param tableName the table name.
54+ * @param tableName the table name.
5755 * @return a {@link CreateIndexOn} that will allow the specification of the column.
5856 */
5957 public CreateIndexOn onTable(String keyspaceName, String tableName) {
@@ -95,6 +93,7 @@
9593
9694 /**
9795 * Create an index on the keys of the given map column.
96+ *
9897 * @param columnName the column name.
9998 * @return the final CREATE INDEX statement.
10099 */
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateType.java +4 −3
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18+import com.google.common.base.Joiner;
19+import com.google.common.base.Optional;
20+
1821 import java.util.ArrayList;
1922 import java.util.List;
2023 import java.util.Map;
2124
22-import com.google.common.base.Joiner;
23-import com.google.common.base.Optional;
24-
2525 /**
2626 * A built CREATE TYPE statement.
2727 */
@@ -46,6 +46,7 @@
4646
4747 /**
4848 * Generate the script for custom type creation
49+ *
4950 * @return a CREATE TYPE statement
5051 */
5152 public String build() {
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Drop.java +1 −0
@@ -72,6 +72,7 @@
7272
7373 /**
7474 * Generate a DROP TABLE statement
75+ *
7576 * @return the final DROP TABLE statement
7677 */
7778 public String build() {
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/NativeColumnType.java +2 −1
@@ -27,7 +27,8 @@
2727 asCQLString = nativeType.toString();
2828 }
2929
30- @Override public String asCQLString() {
30+ @Override
31+ public String asCQLString() {
3132 return asCQLString;
3233 }
3334 }
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaBuilder.java +14 −13
@@ -19,16 +19,17 @@
1919
2020 /**
2121 * Static methods to build a CQL3 DDL statement.
22- * <p>
22+ * <p/>
2323 * The provided builders perform very little validation of the built query.
2424 * There is thus no guarantee that a built query is valid, and it is
2525 * definitively possible to create invalid queries.
26- * <p>
26+ * <p/>
2727 * Note that it could be convenient to use an 'import static' to use the methods of this class.
2828 */
2929 public final class SchemaBuilder {
3030
31- private SchemaBuilder() {}
31+ private SchemaBuilder() {
32+ }
3233
3334 /**
3435 * Start building a new CREATE TABLE statement.
@@ -44,7 +45,7 @@
4445 * Start building a new CREATE TABLE statement.
4546 *
4647 * @param keyspaceName the name of the keyspace to be used.
47- * @param tableName the name of the table to create.
48+ * @param tableName the name of the table to create.
4849 * @return an in-construction CREATE TABLE statement.
4950 */
5051 public static Create createTable(String keyspaceName, String tableName) {
@@ -65,7 +66,7 @@
6566 * Start building a new ALTER TABLE statement.
6667 *
6768 * @param keyspaceName the name of the keyspace to be used.
68- * @param tableName the name of the table to be altered.
69+ * @param tableName the name of the table to be altered.
6970 * @return an in-construction ALTER TABLE statement.
7071 */
7172 public static Alter alterTable(String keyspaceName, String tableName) {
@@ -86,7 +87,7 @@
8687 * Start building a new DROP TABLE statement.
8788 *
8889 * @param keyspaceName the name of the keyspace to be used.
89- * @param tableName the name of the table to be dropped.
90+ * @param tableName the name of the table to be dropped.
9091 * @return an in-construction DROP TABLE statement.
9192 */
9293 public static Drop dropTable(String keyspaceName, String tableName) {
@@ -117,7 +118,7 @@
117118 * Start building a new DROP INDEX statement.
118119 *
119120 * @param keyspaceName the name of the keyspace to be used.
120- * @param indexName the name of the index to be dropped.
121+ * @param indexName the name of the index to be dropped.
121122 * @return an in-construction DROP INDEX statement.
122123 */
123124 public static Drop dropIndex(String keyspaceName, String indexName) {
@@ -138,7 +139,7 @@
138139 * Start building a new CREATE TYPE statement.
139140 *
140141 * @param keyspaceName the name of the keyspace to be used.
141- * @param typeName the name of the custom type to create.
142+ * @param typeName the name of the custom type to create.
142143 * @return an in-construction CREATE TYPE statement.
143144 */
144145 public static CreateType createType(String keyspaceName, String typeName) {
@@ -159,7 +160,7 @@
159160 * Start building a new DROP TYPE statement.
160161 *
161162 * @param keyspaceName the name of the keyspace to be used.
162- * @param typeName the name of the type to be dropped.
163+ * @param typeName the name of the type to be dropped.
163164 * @return an in-construction DROP TYPE statement.
164165 */
165166 public static Drop dropType(String keyspaceName, String typeName) {
@@ -172,7 +173,7 @@
172173
173174 /**
174175 * Build the datatype representation of a frozen UDT, to include in a schema builder statement.
175- * <p>
176+ * <p/>
176177 * <code>frozen("foo")</code> will produce <code>frozen&lt;foo&gt;</code>.
177178 *
178179 * @param udtName the name of the UDT.
@@ -184,7 +185,7 @@
184185
185186 /**
186187 * Build the datatype representation of a complex UDT type, to include in a schema builder statement.
187- * <p>
188+ * <p/>
188189 * As of Cassandra 2.1, this method is not strictly necessary because {@link Create} and {@link Alter}
189190 * provide specialized methods to express simple collections of UDTs, but future versions will make it
190191 * possible to use types such as <code>map&lt;text, map&lt;text, frozen&lt;user&gt;&gt;&gt;</code>.
@@ -216,7 +217,7 @@
216217
217218 /**
218219 * Create options for the date-tiered compaction strategy, to use in a CREATE or ALTER TABLE statement.
219- * <p>
220+ * <p/>
220221 * This strategy was introduced in Cassandra 2.1.1.
221222 *
222223 * @return the options.
@@ -357,7 +358,7 @@
357358
358359 /**
359360 * Return the row caching strategy that caches all rows ({@code all}), to use in a CREATE or ALTER TABLE statement.
360- * <p>
361+ * <p/>
361362 * <strong>Be careful when choosing this option, you can starve Cassandra memory quickly if your partition is very large.</strong>
362363 *
363364 * @return the strategy.
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java +12 −11
@@ -15,15 +15,14 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18+import com.datastax.driver.core.ProtocolVersion;
19+import com.datastax.driver.core.RegularStatement;
20+import com.google.common.base.Strings;
21+
1822 import java.nio.ByteBuffer;
1923 import java.util.Arrays;
2024 import java.util.List;
2125
22-import com.google.common.base.Strings;
23-
24-import com.datastax.driver.core.ProtocolVersion;
25-import com.datastax.driver.core.RegularStatement;
26-
2726 /**
2827 * A DDL statement generated by {@link SchemaBuilder}.
2928 */
@@ -33,10 +32,10 @@
3332 static final String COLUMN_FORMATTING = "\n\t\t";
3433
3534 static final List<String> RESERVED_KEYWORDS = Arrays.asList(
36- ("add,allow,alter,and,any,apply,asc,authorize,batch,begin,by,columnfamily,create,delete,desc,drop,each_quorum,from,grant,in,index,inet,infinity," +
37- "insert,into,keyspace,keyspaces,limit,local_one,local_quorum,modify,nan,norecursive,of,on,order,password,primary,quorum,rename,revoke,schema," +
38- "select,set,table,three,to,token,truncate,two,unlogged,update,use,using,where,with")
39- .split(","));
35+ ("add,allow,alter,and,any,apply,asc,authorize,batch,begin,by,columnfamily,create,delete,desc,drop,each_quorum,from,grant,in,index,inet,infinity," +
36+ "insert,into,keyspace,keyspaces,limit,local_one,local_quorum,modify,nan,norecursive,of,on,order,password,primary,quorum,rename,revoke,schema," +
37+ "select,set,table,three,to,token,truncate,two,unlogged,update,use,using,where,with")
38+ .split(","));
4039
4140 private volatile String cache;
4241
@@ -93,7 +92,8 @@
9392
9493 static SchemaStatement fromQueryString(final String queryString) {
9594 return new SchemaStatement() {
96- @Override public String buildInternal() {
95+ @Override
96+ public String buildInternal() {
9797 return queryString;
9898 }
9999 };
@@ -101,7 +101,8 @@
101101
102102 StatementStart asStatementStart() {
103103 return new StatementStart() {
104- @Override public String buildInternal() {
104+ @Override
105+ public String buildInternal() {
105106 return SchemaStatement.this.buildInternal();
106107 }
107108 };
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/TableOptions.java +78 −82
@@ -15,21 +15,20 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import java.util.ArrayList;
19-import java.util.List;
20-
2118 import com.google.common.base.Joiner;
2219 import com.google.common.base.Optional;
2320 import com.google.common.base.Strings;
2421
22+import java.util.ArrayList;
23+import java.util.List;
24+
2525 /**
2626 * The table options used in a CREATE TABLE or ALTER TABLE statement.
27- * <p>
27+ * <p/>
2828 * Implementation notes: this class is abstract and not meant to use directly.
2929 * The type parameter {@code T} allows usage of <strong>covariant return type</strong> and makes the builder pattern work for different sub-classes.
3030 *
3131 * @param <T> the concrete sub-class of {@link com.datastax.driver.core.schemabuilder.TableOptions}
32- *
3332 * @see <a href="http://docs.datastax.com/en/cql/3.1/cql/cql_reference/tabProp.html" target="_blank">details on table options</a>
3433 */
3534 public abstract class TableOptions<T extends TableOptions> extends SchemaStatement {
@@ -71,15 +70,15 @@
7170 private List<String> customOptions = new ArrayList<String>();
7271
7372 @SuppressWarnings("unchecked")
74- private final T self = (T)this;
73+ private final T self = (T) this;
7574
76- TableOptions(StatementStart statementStart) {
75+ TableOptions(StatementStart statementStart) {
7776 this.statementStart = statementStart;
7877 }
7978
8079 /**
8180 * Define the caching type for Cassandra 2.0.x.
82- * <p>
81+ * <p/>
8382 * If no call is made to this method, the default value set by Cassandra is {@link SchemaBuilder.Caching#KEYS_ONLY}.
8483 *
8584 * @param caching the caching type (all enum values are allowed).
@@ -92,11 +91,11 @@
9291
9392 /**
9493 * Define the caching options for Cassandra 2.1.x.
95- * <p>
94+ * <p/>
9695 * If no call is made to this method, the default values set by Cassandra are keys = {@link SchemaBuilder.Caching#ALL} and
9796 * rows_per_partition = {@link com.datastax.driver.core.schemabuilder.SchemaBuilder#noRows()}.
98-
99- * @param keys the key cache type.
97+ *
98+ * @param keys the key cache type.
10099 * @param rowsPerPartition defines the number of rows to be cached per partition when Row Caching is enabled.
101100 * To create instances, use
102101 * {@link SchemaBuilder#noRows()},
@@ -112,11 +111,11 @@
112111
113112 /**
114113 * Define the desired false-positive probability for SSTable Bloom filters.
115- * <p>
114+ * <p/>
116115 * If no call is made to this method, the default value set by Cassandra is:
117116 * <ul>
118- * <li><strong>0.01</strong> for the size-tiered compaction strategy;</li>
119- * <li><strong>0.1</strong> for the leveled compaction strategy.</li>
117+ * <li><strong>0.01</strong> for the size-tiered compaction strategy;</li>
118+ * <li><strong>0.1</strong> for the leveled compaction strategy.</li>
120119 * </ul>
121120 *
122121 * @param fpChance the false positive change. This value should be between 0 and 1.0.
@@ -141,7 +140,7 @@
141140
142141 /**
143142 * Define the compression options.
144- * <p>
143+ * <p/>
145144 * If no call is made to this method, the default value set by Cassandra is {@link SchemaBuilder#lz4()}.
146145 *
147146 * @param compressionOptions the compression options. To create instances, use
@@ -158,7 +157,7 @@
158157
159158 /**
160159 * Define the compaction options.
161- * <p>
160+ * <p/>
162161 * If no call is made to this method, the default value set by Cassandra is {@link SchemaBuilder#sizedTieredStategy()}.
163162 *
164163 * @param compactionOptions the compaction options. To create instances, use
@@ -174,7 +173,7 @@
174173
175174 /**
176175 * Define the probability of read repairs being invoked over all replicas in the current data center.
177- * <p>
176+ * <p/>
178177 * If no call is made to this method, the default value set by Cassandra is 0.0.
179178 *
180179 * @param dcLocalReadRepairChance the probability.
@@ -188,10 +187,10 @@
188187
189188 /**
190189 * Define the default expiration time in seconds for a table.
191- *
192- * <p>
190+ * <p/>
191+ * <p/>
193192 * Used in MapReduce/Hive scenarios when you have no control of TTL.
194- * <p>
193+ * <p/>
195194 * If no call is made to this method, the default value set by Cassandra is 0.
196195 *
197196 * @param defaultTimeToLive the default time to live in seconds for a table.
@@ -204,10 +203,10 @@
204203
205204 /**
206205 * Define the time to wait before garbage collecting tombstones (deletion markers).
207- *
206+ * <p/>
208207 * The default value allows a great deal of time for consistency to be achieved prior to deletion.
209208 * In many deployments this interval can be reduced, and in a single-node cluster it can be safely set to zero.
210- * <p>
209+ * <p/>
211210 * If no call is made to this method, the default value set by Cassandra is 864000 secs (10 days).
212211 *
213212 * @param gcGraceSeconds the grace period.
@@ -220,7 +219,7 @@
220219
221220 /**
222221 * Define the index interval for Cassandra 2.0.
223- *
222+ * <p/>
224223 * To control the sampling of entries from the primary row index, configure sample frequency of the partition summary by changing the index interval.
225224 * After changing the index interval, SSTables are written to disk with new information. The interval corresponds to the number of index entries that
226225 * are skipped between taking each sample. By default, Cassandra samples one row key out of every 128. The larger the interval, the smaller and less
@@ -228,7 +227,7 @@
228227 * best trade off between memory usage and performance is a value between 128 and 512 in combination with a large table key cache. However, if you have
229228 * small rows (many to an OS page), you may want to increase the sample size, which often lowers memory usage without an impact on performance. For
230229 * large rows, decreasing the sample size may improve read performance.
231- * <p>
230+ * <p/>
232231 * If no call is made to this method, the default value set by Cassandra is 128.
233232 *
234233 * @param indexInterval the index interval.
@@ -241,12 +240,11 @@
241240
242241 /**
243242 * Define the minimum index interval for Cassandra 2.1.
244- * <p>
243+ * <p/>
245244 * If no call is made to this method, the default value set by Cassandra is 128.
246245 *
247246 * @param minIndexInterval the minimum index interval.
248247 * @return this {@code TableOptions} object.
249- *
250248 * @see #indexInterval(Integer)
251249 */
252250 public T minIndexInterval(Integer minIndexInterval) {
@@ -256,12 +254,11 @@
256254
257255 /**
258256 * Define the maximum index interval for Cassandra 2.1.
259- * <p>
257+ * <p/>
260258 * If no call is made to this method, the default value set by Cassandra is 2048.
261259 *
262260 * @param maxIndexInterval the maximum index interval.
263261 * @return this {@code TableOptions} object.
264- *
265262 * @see #indexInterval(Integer)
266263 */
267264 public T maxIndexInterval(Integer maxIndexInterval) {
@@ -271,9 +268,9 @@
271268
272269 /**
273270 * Define the memtable flush period.
274- *
271+ * <p/>
275272 * If set, this forces flushing of the memtable after the specified time elapses.
276- * <p>
273+ * <p/>
277274 * If no call is made to this method, the default value set by Cassandra is 0.
278275 *
279276 * @param memtableFlushPeriodInMillis the memtable flush period in milliseconds.
@@ -286,15 +283,14 @@
286283
287284 /**
288285 * Define whether to populate IO cache on flush of sstables.
289- *
286+ * <p/>
290287 * If set, Cassandra adds newly flushed or compacted sstables to the operating system page cache, potentially evicting other cached data to make room.
291288 * Enable when all data in the table is expected to fit in memory.
292- * <p>
289+ * <p/>
293290 * If no call is made to this method, the default value set by Cassandra is {@code false}.
294291 *
295292 * @param populateIOOnCacheFlush whether to populate IO cache on flush of sstables.
296293 * @return this {@code TableOptions} object.
297- *
298294 * @see <a href="http://docs.datastax.com/en/cassandra/2.0/cassandra/configuration/configCassandra_yaml_r.html?scroll=reference_ds_qfg_n1r_1k__compaction_preheat_key_cache">the global option compaction_preheat_key_cache</a>
299295 */
300296 public T populateIOCacheOnFlush(Boolean populateIOOnCacheFlush) {
@@ -304,7 +300,7 @@
304300
305301 /**
306302 * Define the probability with which read repairs should be invoked on non-quorum reads. The value must be between 0 and 1.
307- * <p>
303+ * <p/>
308304 * If no call is made to this method, the default value set by Cassandra is 0.1.
309305 *
310306 * @param readRepairChance the read repair chance.
@@ -318,10 +314,10 @@
318314
319315 /**
320316 * Define whether to replicate data on write (Cassandra 2.0.x only).
321- *
317+ * <p/>
322318 * When set to {@code true}, replicates writes to all affected replicas regardless of the consistency level specified by the client for a write request.
323319 * For counter tables, this should always be set to {@code true}.
324- * <p>
320+ * <p/>
325321 * If no call is made to this method, the default value set by Cassandra is {@code true}.
326322 *
327323 * @param replicateOnWrite whether to replicate data on write.
@@ -336,17 +332,17 @@
336332 * To override normal read timeout when read_repair_chance is not 1.0, sending another request to read, choose one of these values and use the property to create
337333 * or alter the table:
338334 * <ul>
339- * <li>ALWAYS: Retry reads of all replicas.</li>
340- * <li>Xpercentile: Retry reads based on the effect on throughput and latency.</li>
341- * <li>Yms: Retry reads after specified milliseconds.</li>
342- * <li>NONE: Do not retry reads.</li>
335+ * <li>ALWAYS: Retry reads of all replicas.</li>
336+ * <li>Xpercentile: Retry reads based on the effect on throughput and latency.</li>
337+ * <li>Yms: Retry reads after specified milliseconds.</li>
338+ * <li>NONE: Do not retry reads.</li>
343339 * </ul>
344- *
340+ * <p/>
345341 * Using the speculative retry property, you can configure rapid read protection in Cassandra 2.0.2 and later.
346342 * Use this property to retry a request after some milliseconds have passed or after a percentile of the typical read latency has been reached,
347343 * which is tracked per table.
348- *
349- * <p>
344+ * <p/>
345+ * <p/>
350346 * If no call is made to this method, the default value set by Cassandra is {code 99percentile}.
351347 *
352348 * @param speculativeRetry the speculative retry. To create instances, use
@@ -363,10 +359,10 @@
363359
364360 /**
365361 * Define a free-form option as a key/value pair.
366- * <p>
362+ * <p/>
367363 * This method is provided as a fallback if the SchemaBuilder is used with a more recent version of Cassandra that has new, unsupported options.
368364 *
369- * @param key the name of the option.
365+ * @param key the name of the option.
370366 * @param value the value of the option. If it's a {@code String}, it will be included in single quotes, otherwise the result of invoking its
371367 * {@code toString} method will be used unquoted.
372368 * @return this {@code TableOptions} object.
@@ -381,10 +377,10 @@
381377
382378 private static String buildCustomOption(String key, Object value) {
383379 return String.format("%s = %s",
384- key,
385- (value instanceof String)
386- ? "'" + value + "'"
387- : value.toString());
380+ key,
381+ (value instanceof String)
382+ ? "'" + value + "'"
383+ : value.toString());
388384 }
389385
390386 private List<String> buildCommonOptions() {
@@ -460,8 +456,7 @@
460456 private void buildCachingOptions(List<String> options) {
461457 if (cassandra20Caching.isPresent() && cassandra21KeyCaching.isPresent()) {
462458 throw new IllegalStateException("Can't use Cassandra 2.0 and 2.1 caching at the same time, you must call only one version of caching()");
463- }
464- else if (cassandra20Caching.isPresent()) {
459+ } else if (cassandra20Caching.isPresent()) {
465460 options.add("caching = " + cassandra20Caching.get().value());
466461 } else if (cassandra21KeyCaching.isPresent() && cassandra21RowCaching.isPresent()) {
467462 options.add(String.format("caching = {'keys' : %s, 'rows_per_partition' : %s}",
@@ -476,7 +471,7 @@
476471 List<String> options = buildCommonOptions();
477472 addSpecificOptions(options);
478473 return statementStart.buildInternal() + STATEMENT_START +
479- "WITH " + Joiner.on(" AND ").join(options);
474+ "WITH " + Joiner.on(" AND ").join(options);
480475 }
481476
482477 static void validateRateValue(Double rateValue, String property) {
@@ -487,7 +482,7 @@
487482
488483 /**
489484 * Compaction options for a CREATE or ALTER TABLE statement.
490- * <p>
485+ * <p/>
491486 * To create instances, use
492487 * {@link SchemaBuilder#sizedTieredStategy()},
493488 * {@link SchemaBuilder#leveledStrategy()} or
@@ -508,7 +503,7 @@
508503 private List<String> customOptions = new ArrayList<String>();
509504
510505 @SuppressWarnings("unchecked")
511- private final T self = (T)this;
506+ private final T self = (T) this;
512507
513508 CompactionOptions(Strategy compactionStrategy) {
514509 this.strategy = compactionStrategy;
@@ -516,7 +511,7 @@
516511
517512 /**
518513 * Enable or disable background compaction.
519- * <p>
514+ * <p/>
520515 * If no call is made to this method, the default value set by Cassandra is {code true}.
521516 *
522517 * @param enabled whether to enable background compaction for the table.
@@ -530,7 +525,7 @@
530525 /**
531526 * Define the minimum number of days to wait after an SSTable creation time before considering the SSTable for tombstone compaction.
532527 * Tombstone compaction is the compaction triggered if the SSTable has more garbage-collectable tombstones than tombstone_threshold.
533- * <p>
528+ * <p/>
534529 * If no call is made to this method, the default value set by Cassandra is 1.
535530 *
536531 * @param tombstoneCompactionInterval the tombstone compaction interval in day.
@@ -544,7 +539,7 @@
544539 /**
545540 * Define the ratio of garbage-collectable tombstones to all contained columns,
546541 * which if exceeded by the SSTable triggers compaction (with no other SSTables) for the purpose of purging the tombstones.
547- * <p>
542+ * <p/>
548543 * If no call is made to this method, the default value set by Cassandra is 0.2.
549544 *
550545 * @param tombstoneThreshold the threshold.
@@ -559,7 +554,7 @@
559554 /**
560555 * Enables more aggressive than normal tombstone compactions. A single SSTable tombstone compaction runs without
561556 * checking the likelihood of success (Cassandra 2.0.9 and later).
562- * <p>
557+ * <p/>
563558 * If no call is made to this method, the default value set by Cassandra is {code false}.
564559 *
565560 * @param uncheckedTombstoneCompaction whether to enable the feature.
@@ -572,10 +567,10 @@
572567
573568 /**
574569 * Define a free-form option as a key/value pair.
575- * <p>
570+ * <p/>
576571 * This method is provided as a fallback if the SchemaBuilder is used with a more recent version of Cassandra that has new, unsupported options.
577572 *
578- * @param key the name of the option.
573+ * @param key the name of the option.
579574 * @param value the value of the option. If it's a {@code CharSequence}, it will be included in single quotes, otherwise the result of invoking its
580575 * {@code toString} method will be used unquoted.
581576 * @return this object (for call chaining).
@@ -590,10 +585,10 @@
590585
591586 private static String buildCustomOption(String key, Object value) {
592587 return String.format("'%s' : %s",
593- key,
594- (value instanceof CharSequence)
595- ? "'" + value + "'"
596- : value.toString());
588+ key,
589+ (value instanceof CharSequence)
590+ ? "'" + value + "'"
591+ : value.toString());
597592 }
598593
599594 List<String> buildCommonOptions() {
@@ -648,7 +643,7 @@
648643 /**
649644 * Size-tiered compaction strategy (STCS) considers SSTables to be within the same bucket if the SSTable size diverges by 50%
650645 * or less from the default bucket_low and default bucket_high values: [average-size × bucket_low, average-size × bucket_high].
651- * <p>
646+ * <p/>
652647 * If no call is made to this method, the default value set by Cassandra is 1.5.
653648 *
654649 * @param bucketHigh the new value.
@@ -662,7 +657,7 @@
662657 /**
663658 * Size-tiered compaction strategy (STCS) considers SSTables to be within the same bucket if the SSTable size diverges by 50%
664659 * or less from the default bucket_low and default bucket_high values: [average-size × bucket_low, average-size × bucket_high].
665- * <p>
660+ * <p/>
666661 * If no call is made to this method, the default value set by Cassandra is 0.5.
667662 *
668663 * @param bucketLow the new value.
@@ -679,7 +674,7 @@
679674 * In Cassandra 2.0.3 and later, you can enable the cold_reads_to_omit property to tune performace per table.
680675 * The <a href="http://www.datastax.com/dev/blog/optimizations-around-cold-sstables">Optimizations around Cold SSTables</a> blog includes detailed information tuning performance using this property,
681676 * which avoids compacting cold SSTables. Use the ALTER TABLE command to configure cold_reads_to_omit.
682- * <p>
677+ * <p/>
683678 * If no call is made to this method, the default value set by Cassandra is 0.0 (disabled).
684679 *
685680 * @param coldReadsRatio the new value.
@@ -693,7 +688,7 @@
693688
694689 /**
695690 * Sets the minimum number of SSTables to trigger a minor compaction
696- * <p>
691+ * <p/>
697692 * If no call is made to this method, the default value set by Cassandra is 4.
698693 *
699694 * @param minThreshold the new value.
@@ -707,7 +702,7 @@
707702 /**
708703 * Sets the maximum number of SSTables to allow in a minor compaction.
709704 * In LeveledCompactionStrategy (LCS), it applies to L0 when L0 gets behind, that is, when L0 accumulates more than MAX_COMPACTING_L0 SSTables.
710- * <p>
705+ * <p/>
711706 * If no call is made to this method, the default value set by Cassandra is 32.
712707 *
713708 * @param maxThreshold the new value.
@@ -722,7 +717,7 @@
722717 * The SizeTieredCompactionStrategy groups SSTables for compaction into buckets.
723718 * The bucketing process groups SSTables that differ in size by less than 50%. This results in a bucketing process that is too fine grained for small SSTables.
724719 * If your SSTables are small, use min_sstable_size to define a size threshold (in bytes) below which all SSTables belong to one unique bucket
725- * <p>
720+ * <p/>
726721 * If no call is made to this method, the default value set by Cassandra is 52428800 (50 MB).
727722 *
728723 * @param minSSTableSize the new value.
@@ -781,7 +776,7 @@
781776 * The target size for SSTables that use the leveled compaction strategy.
782777 * Although SSTable sizes should be less or equal to sstable_size_in_mb, it is possible to have a larger SSTable during compaction.
783778 * This occurs when data for a given partition key is exceptionally large. The data is not split into two SSTables
784- * <p>
779+ * <p/>
785780 * If no call is made to this method, the default value set by Cassandra is 160.
786781 *
787782 * @param ssTableSizeInMB the new value.
@@ -829,7 +824,7 @@
829824
830825 /**
831826 * Sets the size of the first window.
832- * <p>
827+ * <p/>
833828 * If no call is made to this method, the default value set by Cassandra is 3600 (1 hour).
834829 *
835830 * @param baseTimeSeconds the size of the first window.
@@ -842,7 +837,7 @@
842837
843838 /**
844839 * Stop compacting SSTables only having data older than these specified days.
845- * <p>
840+ * <p/>
846841 * If no call is made to this method, the default value set by Cassandra is 365.
847842 *
848843 * @param maxSSTableAgeDays the maximum age of the SSTables to compact.
@@ -855,7 +850,7 @@
855850
856851 /**
857852 * Sets the minimum number of SSTables to trigger a minor compaction
858- * <p>
853+ * <p/>
859854 * If no call is made to this method, the default value set by Cassandra is 4.
860855 *
861856 * @param minThreshold the new value.
@@ -869,7 +864,7 @@
869864 /**
870865 * Sets the maximum number of SSTables to allow in a minor compaction.
871866 * In LeveledCompactionStrategy (LCS), it applies to L0 when L0 gets behind, that is, when L0 accumulates more than MAX_COMPACTING_L0 SSTables.
872- * <p>
867+ * <p/>
873868 * If no call is made to this method, the default value set by Cassandra is 32.
874869 *
875870 * @param maxThreshold the new value.
@@ -882,7 +877,7 @@
882877
883878 /**
884879 * Sets the timestamp resolution, depending on the timestamp unit of the data you insert.
885- * <p>
880+ * <p/>
886881 * If no call is made to this method, the default value set by Cassandra is {@code MICROSECONDS}.
887882 *
888883 * @param timestampResolution {@link TimeStampResolution#MICROSECONDS} or {@link TimeStampResolution#MILLISECONDS}.
@@ -893,7 +888,8 @@
893888 return this;
894889 }
895890
896- @Override public String build() {
891+ @Override
892+ public String build() {
897893 final List<String> generalOptions = super.buildCommonOptions();
898894
899895 List<String> options = new ArrayList<String>(generalOptions);
@@ -948,7 +944,7 @@
948944
949945 /**
950946 * The compression options for a CREATE or ALTER TABLE statement.
951- * <p>
947+ * <p/>
952948 * To create instances, use
953949 * {@link SchemaBuilder#noCompression()},
954950 * {@link SchemaBuilder#lz4()},
@@ -973,7 +969,7 @@
973969 * Values larger than the default value might improve the compression rate, but increases the minimum size of data to be read from disk when a read occurs.
974970 * The default value is a good middle-ground for compressing tables.
975971 * Adjust compression size to account for read/write access patterns (how much data is typically requested at once) and the average size of rows in the table.
976- * <p>
972+ * <p/>
977973 * If no call is made to this method, the default value set by Cassandra is 54.
978974 *
979975 * @param chunkLengthInKb the new value.
@@ -988,7 +984,7 @@
988984 * When compression is enabled, each compressed block includes a checksum of that block for the purpose of detecting disk bitrate and avoiding the propagation
989985 * of corruption to other replica. This option defines the probability with which those checksums are checked during read.
990986 * By default they are always checked. Set to 0 to disable checksum checking and to 0.5, for instance, to check them on every other read.
991- * <p>
987+ * <p/>
992988 * If no call is made to this method, the default value set by Cassandra is 1.0 (always check).
993989 *
994990 * @param crcCheckChance the new value.
@@ -1054,7 +1050,7 @@
10541050
10551051 /**
10561052 * The speculative retry options.
1057- * <p>
1053+ * <p/>
10581054 * To create instances, use
10591055 * {@link SchemaBuilder#noSpeculativeRetry()},
10601056 * {@link SchemaBuilder#always()},
@@ -1077,7 +1073,7 @@
10771073 /**
10781074 * Define the number of rows to be cached per partition when row caching is enabled
10791075 * (this feature is only applicable to Cassandra 2.1.x).
1080- * <p>
1076+ * <p/>
10811077 * To create instances, use
10821078 * {@link SchemaBuilder#noRows()},
10831079 * {@link SchemaBuilder#allRows()} or
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/UDTType.java +3 −2
@@ -19,7 +19,7 @@
1919
2020 /**
2121 * Represents a CQL type containing a user-defined type (UDT) in a SchemaBuilder statement.
22- * <p>
22+ * <p/>
2323 * Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)} to build instances of this type.
2424 */
2525 public final class UDTType implements ColumnType {
@@ -29,7 +29,8 @@
2929 this.asCQLString = asCQLString;
3030 }
3131
32- @Override public String asCQLString() {
32+ @Override
33+ public String asCQLString() {
3334 return asCQLString;
3435 }
3536
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/package-info.java +1 −1
@@ -15,7 +15,7 @@
1515 */
1616 /**
1717 * A CQL3 schema builder.
18- * <p>
18+ * <p/>
1919 * The main entry for this package is the {@code SchemaBuilder} class.
2020 */
2121 package com.datastax.driver.core.schemabuilder;
modified driver-core/src/main/java/com/datastax/driver/core/utils/Bytes.java +20 −19
@@ -24,20 +24,22 @@
2424 */
2525 public final class Bytes {
2626
27- private Bytes() {}
27+ private Bytes() {
28+ }
2829
2930 private static final byte[] charToByte = new byte[256];
3031 private static final char[] byteToChar = new char[16];
32+
3133 static {
3234 for (char c = 0; c < charToByte.length; ++c) {
3335 if (c >= '0' && c <= '9')
34- charToByte[c] = (byte)(c - '0');
36+ charToByte[c] = (byte) (c - '0');
3537 else if (c >= 'A' && c <= 'F')
36- charToByte[c] = (byte)(c - 'A' + 10);
38+ charToByte[c] = (byte) (c - 'A' + 10);
3739 else if (c >= 'a' && c <= 'f')
38- charToByte[c] = (byte)(c - 'a' + 10);
40+ charToByte[c] = (byte) (c - 'a' + 10);
3941 else
40- charToByte[c] = (byte)-1;
42+ charToByte[c] = (byte) -1;
4143 }
4244
4345 for (int i = 0; i < 16; ++i) {
@@ -51,6 +53,7 @@
5153 * That's stolen from Cassandra's code.
5254 */
5355 private static final Constructor<String> stringConstructor;
56+
5457 static {
5558 Constructor<String> c;
5659 try {
@@ -79,7 +82,7 @@
7982
8083 /**
8184 * Converts a blob to its CQL hex string representation.
82- * <p>
85+ * <p/>
8386 * A CQL blob string representation consist of the hexadecimal
8487 * representation of the blob bytes prefixed by "0x".
8588 *
@@ -102,7 +105,7 @@
102105
103106 /**
104107 * Converts a blob to its CQL hex string representation.
105- * <p>
108+ * <p/>
106109 * A CQL blob string representation consist of the hexadecimal
107110 * representation of the blob bytes.
108111 *
@@ -125,7 +128,7 @@
125128
126129 /**
127130 * Converts a blob to its CQL hex string representation.
128- * <p>
131+ * <p/>
129132 * A CQL blob string representation consist of the hexadecimal
130133 * representation of the blob bytes prefixed by "0x".
131134 *
@@ -139,7 +142,7 @@
139142
140143 /**
141144 * Parse an hex string representing a CQL blob.
142- * <p>
145+ * <p/>
143146 * The input should be a valid representation of a CQL blob, i.e. it
144147 * must start by "0x" followed by the hexadecimal representation of the
145148 * blob bytes.
@@ -147,9 +150,8 @@
147150 * @param str the CQL blob string representation to parse.
148151 * @return the bytes corresponding to {@code str}. If {@code str}
149152 * is {@code null}, this method returns {@code null}.
150- *
151153 * @throws IllegalArgumentException if {@code str} is not a valid CQL
152- * blob string.
154+ * blob string.
153155 */
154156 public static ByteBuffer fromHexString(String str) {
155157 if ((str.length() & 1) == 1)
@@ -163,7 +165,7 @@
163165
164166 /**
165167 * Extract the content of the provided {@code ByteBuffer} as a byte array.
166- * <p>
168+ * <p/>
167169 * This method work with any type of {@code ByteBuffer} (direct and non-direct
168170 * ones), but when the {@code ByteBuffer} is backed by an array, this method
169171 * will try to avoid copy when possible. As a consequence, changes to the
@@ -188,13 +190,13 @@
188190 bytes.duplicate().get(array);
189191 return array;
190192 }
191-
193+
192194 private static String toRawHexString(ByteBuffer bytes, char[] array, int offset) {
193195 int size = bytes.remaining();
194196 int bytesOffset = bytes.position();
195- assert array.length >= offset + 2*size;
197+ assert array.length >= offset + 2 * size;
196198 for (int i = 0; i < size; i++) {
197- int bint = bytes.get(i+bytesOffset);
199+ int bint = bytes.get(i + bytesOffset);
198200 array[offset + i * 2] = byteToChar[(bint & 0xf0) >> 4];
199201 array[offset + 1 + i * 2] = byteToChar[bint & 0x0f];
200202 }
@@ -203,13 +205,12 @@
203205
204206 /**
205207 * Converts a CQL hex string representation into a byte array.
206- * <p>
208+ * <p/>
207209 * A CQL blob string representation consist of the hexadecimal
208210 * representation of the blob bytes.
209211 *
210- * @param str the string converted in hex representation.
212+ * @param str the string converted in hex representation.
211213 * @param strOffset he offset for starting the string conversion
212- *
213214 * @return the byte array which the String was representing.
214215 */
215216
@@ -220,7 +221,7 @@
220221 byte halfByte2 = charToByte[str.charAt(strOffset + i * 2 + 1)];
221222 if (halfByte1 == -1 || halfByte2 == -1)
222223 throw new IllegalArgumentException("Non-hex characters in " + str);
223- bytes[i] = (byte)((halfByte1 << 4) | halfByte2);
224+ bytes[i] = (byte) ((halfByte1 << 4) | halfByte2);
224225 }
225226 return bytes;
226227 }
modified driver-core/src/main/java/com/datastax/driver/core/utils/UUIDs.java +20 −18
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core.utils;
1717
18+import com.google.common.base.Charsets;
19+
1820 import java.net.InetAddress;
1921 import java.net.NetworkInterface;
2022 import java.net.SocketException;
@@ -24,15 +26,16 @@
2426 import java.util.*;
2527 import java.util.concurrent.atomic.AtomicLong;
2628
27-import com.google.common.base.Charsets;
28-
2929 /**
3030 * Utility methods to work with UUID and most specifically with time-based ones
3131 * (version 1).
3232 */
3333 public final class UUIDs {
3434
35- private UUIDs() {};
35+ private UUIDs() {
36+ }
37+
38+ ;
3639
3740 // http://www.ietf.org/rfc/rfc4122.txt
3841 private static final long START_EPOCH = makeEpoch();
@@ -96,7 +99,7 @@
9699
97100 long node = 0;
98101 for (int i = 0; i < 6; i++)
99- node |= (0x00000000000000ffL & (long)hash[i]) << (i*8);
102+ node |= (0x00000000000000ffL & (long) hash[i]) << (i * 8);
100103 // Since we don't use the mac address, the spec says that multicast
101104 // bit (least significant bit of the first byte of the node ID) must be 1.
102105 return node | 0x0000010000000000L;
@@ -123,7 +126,7 @@
123126
124127 /**
125128 * Creates a new random (version 4) UUID.
126- * <p>
129+ * <p/>
127130 * This method is just a convenience for {@code UUID.randomUUID()}.
128131 *
129132 * @return a newly generated, pseudo random, version 4 UUID.
@@ -134,7 +137,7 @@
134137
135138 /**
136139 * Creates a new time-based (version 1) UUID.
137- * <p>
140+ * <p/>
138141 * UUID generated by this method are suitable for use with the
139142 * {@code timeuuid} Cassandra type. In particular the generated UUID
140143 * includes the timestamp of its generation.
@@ -148,27 +151,27 @@
148151 /**
149152 * Creates a "fake" time-based UUID that sorts as the smallest possible
150153 * version 1 UUID generated at the provided timestamp.
151- * <p>
154+ * <p/>
152155 * Such created UUID are useful in queries to select a time range of a
153156 * {@code timeuuid} column.
154- * <p>
157+ * <p/>
155158 * The UUID created by this method <b>are not unique</b> and as such are
156159 * <b>not</b> suitable for anything else than querying a specific time
157160 * range. In particular, you should not insert such UUID.
158- * <p>
161+ * <p/>
159162 * Also, the timestamp to provide as parameter must be a unix timestamp (as
160163 * returned by {@link System#currentTimeMillis} or {@link java.util.Date#getTime}),
161164 * not a UUID 100-nanoseconds intervals since 15 October 1582. In other
162165 * words, given a UUID {@code uuid}, you should never do
163166 * {@code startOf(uuid.timestamp())} but rather
164167 * {@code startOf(unixTimestamp(uuid.timestamp()))}.
165- * <p>
168+ * <p/>
166169 * Lastly, please note that Cassandra's timeuuid sorting is not compatible
167170 * with {@link UUID#compareTo} and hence the UUID created by this method
168171 * are not necessarily lower bound for that latter method.
169172 *
170173 * @param timestamp the unix timestamp for which the created UUID must be a
171- * lower bound.
174+ * lower bound.
172175 * @return the smallest (for Cassandra timeuuid sorting) UUID of {@code timestamp}.
173176 */
174177 public static UUID startOf(long timestamp) {
@@ -178,27 +181,27 @@
178181 /**
179182 * Creates a "fake" time-based UUID that sorts as the biggest possible
180183 * version 1 UUID generated at the provided timestamp.
181- * <p>
184+ * <p/>
182185 * Such created UUID are useful in queries to select a time range of a
183186 * {@code timeuuid} column.
184- * <p>
187+ * <p/>
185188 * The UUID created by this method <b>are not unique</b> and as such are
186189 * <b>not</b> suitable for anything else than querying a specific time
187190 * range. In particular, you should not insert such UUID.
188- * <p>
191+ * <p/>
189192 * Also, the timestamp to provide as parameter must be a unix timestamp (as
190193 * returned by {@link System#currentTimeMillis} or {@link java.util.Date#getTime}),
191194 * not a UUID 100-nanoseconds intervals since 15 October 1582. In other
192195 * words, given a UUID {@code uuid}, you should never do
193196 * {@code startOf(uuid.timestamp())} but rather
194197 * {@code startOf(unixTimestamp(uuid.timestamp()))}.
195- * <p>
198+ * <p/>
196199 * Lastly, please note that Cassandra's timeuuid sorting is not compatible
197200 * with {@link UUID#compareTo} and hence the UUID created by this method
198201 * are not necessarily upper bound for that latter method.
199202 *
200203 * @param timestamp the unix timestamp for which the created UUID must be an
201- * upper bound.
204+ * upper bound.
202205 * @return the biggest (for Cassandra timeuuid sorting) UUID of {@code timestamp}.
203206 */
204207 public static UUID endOf(long timestamp) {
@@ -208,7 +211,7 @@
208211
209212 /**
210213 * Return the unix timestamp contained by the provided time-based UUID.
211- * <p>
214+ * <p/>
212215 * This method is not equivalent to {@code uuid.timestamp()}. More
213216 * precisely, a version 1 UUID stores a timestamp that represents the
214217 * number of 100-nanoseconds intervals since midnight, 15 October 1582 and
@@ -221,7 +224,6 @@
221224 *
222225 * @param uuid the UUID to return the timestamp of.
223226 * @return the unix timestamp of {@code uuid}.
224- *
225227 * @throws IllegalArgumentException if {@code uuid} is not a version 1 UUID.
226228 */
227229 public static long unixTimestamp(UUID uuid) {
modified driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +5 −4
@@ -20,11 +20,10 @@
2020 import java.util.HashMap;
2121 import java.util.Map;
2222
23-import static org.testng.Assert.*;
24-
2523 import static com.datastax.driver.core.TestUtils.*;
2624 import static com.datastax.driver.core.querybuilder.QueryBuilder.batch;
2725 import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
26+import static org.testng.Assert.*;
2827
2928 public abstract class AbstractPoliciesTest {
3029 private static final boolean DEBUG = false;
@@ -107,7 +106,9 @@
107106 }
108107 }
109108
110- /** Assert that one of the nodes in the list was queried with n, no matter which one */
109+ /**
110+ * Assert that one of the nodes in the list was queried with n, no matter which one
111+ */
111112 protected void assertOneNodeQueried(int n, String... hosts) {
112113 try {
113114 boolean found = false;
@@ -180,7 +181,7 @@
180181 if (batch)
181182 // BUG: WriteType == SIMPLE
182183 c.session.execute(batch()
183- .add(insertInto(SIMPLE_TABLE).values(new String[]{ "k", "i"}, new Object[]{ 0, 0 }))
184+ .add(insertInto(SIMPLE_TABLE).values(new String[]{"k", "i"}, new Object[]{0, 0}))
184185 .setConsistencyLevel(cl));
185186 else
186187 c.session.execute(new SimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", SIMPLE_TABLE)).setConsistencyLevel(cl));
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +18 −19
@@ -15,13 +15,9 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.util.concurrent.CyclicBarrier;
20-import java.util.concurrent.Executors;
21-import java.util.concurrent.ScheduledExecutorService;
22-import java.util.concurrent.TimeUnit;
23-import java.util.concurrent.atomic.AtomicReference;
24-
18+import com.datastax.driver.core.AbstractReconnectionHandler.HandlerFuture;
19+import com.datastax.driver.core.AbstractReconnectionHandlerTest.MockReconnectionWork.ReconnectBehavior;
20+import com.datastax.driver.core.policies.ReconnectionPolicy.ReconnectionSchedule;
2521 import com.google.common.util.concurrent.Futures;
2622 import com.google.common.util.concurrent.ListenableFuture;
2723 import com.google.common.util.concurrent.SettableFuture;
@@ -32,16 +28,17 @@
3228 import org.testng.annotations.BeforeMethod;
3329 import org.testng.annotations.Test;
3430
31+import java.net.InetSocketAddress;
32+import java.util.concurrent.CyclicBarrier;
33+import java.util.concurrent.Executors;
34+import java.util.concurrent.ScheduledExecutorService;
35+import java.util.concurrent.TimeUnit;
36+import java.util.concurrent.atomic.AtomicReference;
37+
3538 import static org.assertj.core.api.Assertions.assertThat;
36-import static org.mockito.Mockito.spy;
37-import static org.mockito.Mockito.timeout;
38-import static org.mockito.Mockito.verify;
39+import static org.mockito.Mockito.*;
3940 import static org.testng.Assert.fail;
4041
41-import com.datastax.driver.core.AbstractReconnectionHandler.HandlerFuture;
42-import com.datastax.driver.core.AbstractReconnectionHandlerTest.MockReconnectionWork.ReconnectBehavior;
43-import com.datastax.driver.core.policies.ReconnectionPolicy.ReconnectionSchedule;
44-
4542 public class AbstractReconnectionHandlerTest {
4643 private static final Logger logger = LoggerFactory.getLogger(AbstractReconnectionHandlerTest.class);
4744
@@ -169,7 +166,7 @@
169166 // The future will be marked cancelled and thus not executed.
170167 ListenableFuture<?> currentAttempt = future.get();
171168 assertThat(currentAttempt).isInstanceOf(HandlerFuture.class);
172- HandlerFuture handlerFuture = (HandlerFuture)currentAttempt;
169+ HandlerFuture handlerFuture = (HandlerFuture) currentAttempt;
173170 assertThat(handlerFuture.isCancelled());
174171
175172 // The next try should also be cancelled.
@@ -276,7 +273,7 @@
276273
277274 /**
278275 * A reconnection schedule that allows manually setting the delay.
279- *
276+ * <p/>
280277 * To make testing easier, nextDelay blocks until tick() is called from the main thread.
281278 */
282279 static class MockReconnectionSchedule implements ReconnectionSchedule {
@@ -321,14 +318,16 @@
321318
322319 /**
323320 * Simulates the work done by the overridable methods of the handler.
324- *
321+ * <p/>
325322 * Allows choosing whether the next reconnect will succeed or throw an exception.
326323 * To make testing easier, tryReconnect blocks until tick() is called from the main thread.
327324 */
328325 static class MockReconnectionWork {
329326 enum ReconnectBehavior {
330327 SUCCEED, THROW_EXCEPTION
331- };
328+ }
329+
330+ ;
332331
333332 private final CyclicBarrier barrier = new CyclicBarrier(2);
334333
@@ -353,7 +352,7 @@
353352 case THROW_EXCEPTION:
354353 logger.debug("simulate reconnection error");
355354 throw new ConnectionException(new InetSocketAddress(8888),
356- "Simulated exception from mock reconnection");
355+ "Simulated exception from mock reconnection");
357356 default:
358357 throw new AssertionError();
359358 }
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +7 −9
@@ -15,6 +15,9 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.collect.ImmutableList;
19+import com.google.common.collect.ImmutableList.Builder;
20+
1821 import java.net.InetAddress;
1922 import java.net.InetSocketAddress;
2023 import java.net.UnknownHostException;
@@ -23,13 +26,8 @@
2326 import java.util.Map;
2427 import java.util.Set;
2528
26-import com.google.common.collect.ImmutableList;
27-import com.google.common.collect.ImmutableList.Builder;
28-
2929 import static org.mockito.Mockito.mock;
30-import static org.testng.Assert.assertEquals;
31-import static org.testng.Assert.assertNotNull;
32-import static org.testng.Assert.assertTrue;
30+import static org.testng.Assert.*;
3331
3432 /**
3533 * Base class for replication strategy tests. Currently only supports testing
@@ -68,7 +66,7 @@
6866 if (!(o instanceof HostMock))
6967 return false;
7068
71- return address.equals(((HostMock)o).address);
69+ return address.equals(((HostMock) o).address);
7270 }
7371
7472 @Override
@@ -102,7 +100,7 @@
102100 * Returns null if parameter host is not a mock
103101 */
104102 protected static HostMock asMock(Host host) {
105- return (host instanceof HostMock ? (HostMock)host : null);
103+ return (host instanceof HostMock ? (HostMock) host : null);
106104 }
107105
108106 /**
@@ -158,7 +156,7 @@
158156 protected static InetSocketAddress socketAddress(String address) {
159157 try {
160158 return new InetSocketAddress(InetAddress.getByName(address), 9042);
161- } catch(UnknownHostException ex) {
159+ } catch (UnknownHostException ex) {
162160 throw new RuntimeException(ex);
163161 }
164162 }
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +2 −2
@@ -20,7 +20,7 @@
2020 /**
2121 * Augment AssertJ with custom assertions for the Java driver.
2222 */
23-public class Assertions extends org.assertj.core.api.Assertions{
23+public class Assertions extends org.assertj.core.api.Assertions {
2424 public static ClusterAssert assertThat(Cluster cluster) {
2525 return new ClusterAssert(cluster);
2626 }
@@ -40,7 +40,7 @@
4040 public static DataTypeAssert assertThat(DataType type) {
4141 return new DataTypeAssert(type);
4242 }
43-
43+
4444 public static IndexMetadataAssert assertThat(IndexMetadata indexMetadata) {
4545 return new IndexMetadataAssert(indexMetadata);
4646 }
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +14 −15
@@ -15,27 +15,26 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.List;
20-import java.util.concurrent.*;
21-
18+import com.datastax.driver.core.exceptions.InvalidQueryException;
2219 import com.google.common.base.Function;
2320 import com.google.common.collect.Lists;
2421 import com.google.common.util.concurrent.*;
2522 import org.testng.annotations.DataProvider;
2623 import org.testng.annotations.Test;
2724
25+import java.util.Collection;
26+import java.util.List;
27+import java.util.concurrent.*;
28+
2829 import static org.assertj.core.api.Assertions.assertThat;
2930 import static org.testng.Assert.assertEquals;
3031 import static org.testng.Assert.assertTrue;
3132
32-import com.datastax.driver.core.exceptions.InvalidQueryException;
33-
3433 public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster {
3534
36- @DataProvider(name="keyspace")
35+ @DataProvider(name = "keyspace")
3736 public static Object[][] keyspace() {
38- return new Object[][]{ { "asyncquerytest" }, { "\"AsyncQueryTest\"" } };
37+ return new Object[][]{{"asyncquerytest"}, {"\"AsyncQueryTest\""}};
3938 }
4039
4140 @Override
@@ -43,7 +42,7 @@
4342 List<String> definitions = Lists.newArrayList();
4443
4544 for (Object[] objects : keyspace()) {
46- String keyspace = (String)objects[0];
45+ String keyspace = (String) objects[0];
4746
4847 definitions.add(String.format("create keyspace %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace));
4948 definitions.add(String.format("create table %s.foo(k int primary key, v int)", keyspace));
@@ -79,8 +78,8 @@
7978 Cluster cluster2 = null;
8079 try {
8180 cluster2 = Cluster.builder()
82- .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress()))
83- .build();
81+ .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress()))
82+ .build();
8483 Session session2 = cluster2.newSession();
8584
8685 // Neither cluster2 nor session2 are initialized at this point
@@ -97,7 +96,7 @@
9796 }
9897
9998 @Test(groups = "short", dataProvider = "keyspace", enabled = false,
100- description = "disabled because the blocking USE call in the current pool implementation makes it deadlock")
99+ description = "disabled because the blocking USE call in the current pool implementation makes it deadlock")
101100 public void should_chain_query_on_async_session_init_with_same_executor(String keyspace) throws Exception {
102101 ListenableFuture<Integer> resultFuture = connectAndQuery(keyspace, MoreExecutors.sameThreadExecutor());
103102
@@ -125,8 +124,8 @@
125124 Uninterruptibles.getUninterruptibly(resultFuture);
126125 } catch (ExecutionException e) {
127126 assertThat(e.getCause())
128- .isInstanceOf(InvalidQueryException.class)
129- .hasMessage("Keyspace 'wrong_keyspace' does not exist");
127+ .isInstanceOf(InvalidQueryException.class)
128+ .hasMessage("Keyspace 'wrong_keyspace' does not exist");
130129 }
131130 }
132131
@@ -147,7 +146,7 @@
147146 }
148147
149148 private static HostConnectionPool getPool(Session session) {
150- Collection<HostConnectionPool> pools = ((SessionManager)session).pools.values();
149+ Collection<HostConnectionPool> pools = ((SessionManager) session).pools.values();
151150 assertEquals(pools.size(), 1);
152151 return pools.iterator().next();
153152 }
modified driver-core/src/test/java/com/datastax/driver/core/AtomicMonotonicTimestampGeneratorTest.java +15 −15
@@ -15,13 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-import java.util.SortedSet;
20-import java.util.concurrent.ConcurrentSkipListSet;
21-import java.util.concurrent.ExecutionException;
22-import java.util.concurrent.Executors;
23-import java.util.concurrent.TimeUnit;
24-
2518 import com.google.common.collect.Lists;
2619 import com.google.common.util.concurrent.Futures;
2720 import com.google.common.util.concurrent.ListenableFuture;
@@ -29,6 +22,13 @@
2922 import com.google.common.util.concurrent.MoreExecutors;
3023 import org.testng.annotations.Test;
3124
25+import java.util.List;
26+import java.util.SortedSet;
27+import java.util.concurrent.ConcurrentSkipListSet;
28+import java.util.concurrent.ExecutionException;
29+import java.util.concurrent.Executors;
30+import java.util.concurrent.TimeUnit;
31+
3232 import static org.testng.Assert.assertEquals;
3333 import static org.testng.Assert.fail;
3434
@@ -49,13 +49,13 @@
4949 List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(testThreadsCount);
5050 for (int i = 0; i < testThreadsCount; i++) {
5151 futures.add(executor.submit(
52- new Runnable() {
53- @Override
54- public void run() {
55- for (int i = 0; i < 1000 / testThreadsCount; i++)
56- allTimestamps.add(generator.next());
57- }
58- }));
52+ new Runnable() {
53+ @Override
54+ public void run() {
55+ for (int i = 0; i < 1000 / testThreadsCount; i++)
56+ allTimestamps.add(generator.next());
57+ }
58+ }));
5959 }
6060 executor.shutdown();
6161 executor.awaitTermination(1, TimeUnit.SECONDS);
@@ -65,7 +65,7 @@
6565 } catch (ExecutionException e) {
6666 Throwable cause = e.getCause();
6767 if (cause instanceof AssertionError)
68- throw (AssertionError)cause;
68+ throw (AssertionError) cause;
6969 else
7070 fail("Error in a test thread", cause);
7171 }
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +8 −9
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.TimeUnit;
19-
18+import com.datastax.driver.core.exceptions.AuthenticationException;
19+import com.datastax.driver.core.exceptions.NoHostAvailableException;
2020 import org.slf4j.Logger;
2121 import org.slf4j.LoggerFactory;
2222 import org.testng.annotations.AfterClass;
2323 import org.testng.annotations.BeforeClass;
2424 import org.testng.annotations.Test;
2525
26-import com.datastax.driver.core.exceptions.AuthenticationException;
27-import com.datastax.driver.core.exceptions.NoHostAvailableException;
26+import java.util.concurrent.TimeUnit;
2827
2928 /**
3029 * Tests for authenticated cluster access
@@ -38,12 +37,12 @@
3837 /**
3938 * creates a cluster and turns on password authentication before starting it.
4039 */
41- @BeforeClass (groups = "short")
40+ @BeforeClass(groups = "short")
4241 public void setupClusterWithAuthentication() throws InterruptedException {
4342 ccm = CCMBridge.builder("test")
44- .withCassandraConfiguration("authenticator", "PasswordAuthenticator")
45- .notStarted()
46- .build();
43+ .withCassandraConfiguration("authenticator", "PasswordAuthenticator")
44+ .notStarted()
45+ .build();
4746 ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
4847
4948 // Even though we've override the default user setup delay, still wait
@@ -51,7 +50,7 @@
5150 TimeUnit.SECONDS.sleep(1);
5251 }
5352
54- @AfterClass (groups = "short")
53+ @AfterClass(groups = "short")
5554 public void shutdownCluster() {
5655 if (ccm != null)
5756 ccm.stop();
modified driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java +5 −6
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
19+import com.datastax.driver.core.utils.CassandraVersion;
20+import org.testng.annotations.Test;
21+
1822 import java.util.Collection;
1923 import java.util.Collections;
2024
21-import org.testng.annotations.Test;
22-
2325 import static org.testng.Assert.assertEquals;
2426 import static org.testng.Assert.assertTrue;
2527
26-import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
27-import com.datastax.driver.core.utils.CassandraVersion;
28-
2928 public class BatchStatementTest extends CCMBridge.PerClassSingleNodeCluster {
3029
3130 @Override
@@ -80,7 +79,7 @@
8079 }
8180
8281 @Test(groups = "short")
83- @CassandraVersion(major=2.0, minor=9, description="This will only work with C* 2.0.9 (CASSANDRA-7337)")
82+ @CassandraVersion(major = 2.0, minor = 9, description = "This will only work with C* 2.0.9 (CASSANDRA-7337)")
8483 public void casBatchTest() throws Throwable {
8584 try {
8685 PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS");
modified driver-core/src/test/java/com/datastax/driver/core/BoundStatementTest.java +9 −11
@@ -15,18 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.Collections;
20-
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
2119 import com.google.common.collect.Lists;
2220 import org.testng.annotations.BeforeClass;
2321 import org.testng.annotations.Test;
2422
23+import java.util.Collection;
24+
2525 import static org.assertj.core.api.Assertions.assertThat;
2626 import static org.assertj.core.api.Assertions.fail;
2727
28-import com.datastax.driver.core.exceptions.InvalidTypeException;
29-
3028 public class BoundStatementTest extends CCMBridge.PerClassSingleNodeCluster {
3129
3230 PreparedStatement prepared;
@@ -47,16 +45,16 @@
4745 BoundStatement statement = prepared.bind(1, "test", Lists.newArrayList(1));
4846
4947 assertThat(statement.getInt(0))
50- .isEqualTo(statement.getInt("k"))
51- .isEqualTo(1);
48+ .isEqualTo(statement.getInt("k"))
49+ .isEqualTo(1);
5250
5351 assertThat(statement.getString(1))
54- .isEqualTo(statement.getString("v1"))
55- .isEqualTo("test");
52+ .isEqualTo(statement.getString("v1"))
53+ .isEqualTo("test");
5654
5755 assertThat(statement.getList(2, Integer.class))
58- .isEqualTo(statement.getList("v2", Integer.class))
59- .isEqualTo(Lists.newArrayList(1));
56+ .isEqualTo(statement.getList("v2", Integer.class))
57+ .isEqualTo(Lists.newArrayList(1));
6058
6159 try {
6260 statement.getString(0);
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +60 −46
@@ -15,17 +15,9 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.io.*;
19-import java.net.InetAddress;
20-import java.net.InetSocketAddress;
21-import java.net.Socket;
22-import java.net.UnknownHostException;
23-import java.util.Collection;
24-import java.util.Collections;
25-import java.util.Map;
26-import java.util.concurrent.TimeUnit;
27-import java.util.concurrent.atomic.AtomicLong;
28-
18+import com.datastax.driver.core.exceptions.AlreadyExistsException;
19+import com.datastax.driver.core.exceptions.DriverException;
20+import com.datastax.driver.core.exceptions.NoHostAvailableException;
2921 import com.google.common.base.Joiner;
3022 import com.google.common.collect.ImmutableMap;
3123 import com.google.common.collect.Maps;
@@ -38,14 +30,20 @@
3830 import org.testng.annotations.AfterClass;
3931 import org.testng.annotations.BeforeClass;
4032
41-import static org.testng.Assert.fail;
42-
43-import com.datastax.driver.core.exceptions.AlreadyExistsException;
44-import com.datastax.driver.core.exceptions.DriverException;
45-import com.datastax.driver.core.exceptions.NoHostAvailableException;
33+import java.io.*;
34+import java.net.InetAddress;
35+import java.net.InetSocketAddress;
36+import java.net.Socket;
37+import java.net.UnknownHostException;
38+import java.util.Collection;
39+import java.util.Collections;
40+import java.util.Map;
41+import java.util.concurrent.TimeUnit;
42+import java.util.concurrent.atomic.AtomicLong;
4643
4744 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
4845 import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
46+import static org.testng.Assert.fail;
4947
5048 public class CCMBridge {
5149
@@ -81,11 +79,11 @@
8179 * The environment variables to use when invoking CCM. Inherits the current processes environment, but will also
8280 * prepend to the PATH variable the value of the 'ccm.path' property and set JAVA_HOME variable to the
8381 * 'ccm.java.home' variable.
84- *
82+ * <p/>
8583 * At times it is necessary to use a separate java install for CCM then what is being used for running tests.
8684 * For example, if you want to run tests with JDK 6 but against Cassandra 2.0, which requires JDK 7.
8785 */
88- private static final Map<String,String> ENVIRONMENT_MAP;
86+ private static final Map<String, String> ENVIRONMENT_MAP;
8987
9088 /**
9189 * The command to use to launch CCM
@@ -98,7 +96,7 @@
9896 String branch = System.getProperty("cassandra.branch");
9997 if (installDirectory != null && !installDirectory.trim().isEmpty()) {
10098 CASSANDRA_INSTALL_ARGS = "--install-dir=" + new File(installDirectory).getAbsolutePath();
101- } else if(branch != null && !branch.trim().isEmpty()) {
99+ } else if (branch != null && !branch.trim().isEmpty()) {
102100 CASSANDRA_INSTALL_ARGS = "-v git:" + branch;
103101 } else {
104102 CASSANDRA_INSTALL_ARGS = "-v " + CASSANDRA_VERSION;
@@ -111,12 +109,12 @@
111109 IP_PREFIX = ip_prefix;
112110
113111 // Inherit the current environment.
114- Map<String,String> envMap = Maps.newHashMap(new ProcessBuilder().environment());
112+ Map<String, String> envMap = Maps.newHashMap(new ProcessBuilder().environment());
115113 // If ccm.path is set, override the PATH variable with it.
116114 String ccmPath = System.getProperty("ccm.path");
117- if(ccmPath != null) {
115+ if (ccmPath != null) {
118116 String existingPath = envMap.get("PATH");
119- if(existingPath == null) {
117+ if (existingPath == null) {
120118 existingPath = "";
121119 }
122120 envMap.put("PATH", ccmPath + File.pathSeparator + existingPath);
@@ -130,7 +128,7 @@
130128
131129 // If ccm.java.home is set, override the JAVA_HOME variable with it.
132130 String ccmJavaHome = System.getProperty("ccm.java.home");
133- if(ccmJavaHome != null) {
131+ if (ccmJavaHome != null) {
134132 envMap.put("JAVA_HOME", ccmJavaHome);
135133 }
136134 ENVIRONMENT_MAP = ImmutableMap.copyOf(envMap);
@@ -138,6 +136,7 @@
138136
139137 /**
140138 * Checks if the operating system is a Windows one
139+ *
141140 * @return <code>true</code> if the operating system is a Windows one, <code>false</code> otherwise.
142141 */
143142 private static boolean isWindows() {
@@ -156,11 +155,12 @@
156155 * <p>
157156 * Extracts a keystore from the classpath into a temporary file.
158157 * </p>
159- *
158+ * <p/>
160159 * <p>
161160 * This is needed as the keystore could be part of a built test jar used by other
162161 * projects, and they need to be extracted to a file system so cassandra may use them.
163162 * </p>
163+ *
164164 * @param storePath Path in classpath where the keystore exists.
165165 * @return The generated File.
166166 */
@@ -228,7 +228,7 @@
228228
229229 public void stop(String clusterName) {
230230 logger.info("Stopping Cluster : " + clusterName);
231- execute(CCM_COMMAND + " stop "+clusterName);
231+ execute(CCM_COMMAND + " stop " + clusterName);
232232 }
233233
234234 public void forceStop(int n) {
@@ -269,7 +269,7 @@
269269 String binaryItf = IP_PREFIX + n + ":" + binaryPort;
270270 String remoteLogItf = IP_PREFIX + n + ":" + remoteDebugPort;
271271 execute(CCM_COMMAND + " add node%d -i %s%d -b -t %s -l %s --binary-itf %s -j %d -r %s -s",
272- n, IP_PREFIX, n, thriftItf, storageItf, binaryItf, jmxPort, remoteLogItf);
272+ n, IP_PREFIX, n, thriftItf, storageItf, binaryItf, jmxPort, remoteLogItf);
273273 execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
274274 }
275275
@@ -294,12 +294,14 @@
294294 Executor executor = new DefaultExecutor();
295295
296296 LogOutputStream outStream = new LogOutputStream() {
297- @Override protected void processLine(String line, int logLevel) {
297+ @Override
298+ protected void processLine(String line, int logLevel) {
298299 logger.debug("ccmout> " + line);
299300 }
300301 };
301302 LogOutputStream errStream = new LogOutputStream() {
302- @Override protected void processLine(String line, int logLevel) {
303+ @Override
304+ protected void processLine(String line, int logLevel) {
303305 logger.error("ccmerr> " + line);
304306 }
305307 };
@@ -408,7 +410,7 @@
408410
409411 protected static CCMBridge ccmBridge;
410412 private static boolean erroredOut;
411- private static boolean clusterInitialized=false;
413+ private static boolean clusterInitialized = false;
412414 private static AtomicLong ksNumber;
413415 protected String keyspace;
414416
@@ -417,7 +419,7 @@
417419
418420 protected static Cluster cluster;
419421 protected static Session session;
420-
422+
421423 protected final VersionNumber cassandraVersion = VersionNumber.parse(System.getProperty("cassandra.version"));
422424
423425 protected abstract Collection<String> getTableDefinitions();
@@ -431,25 +433,25 @@
431433 erroredOut = true;
432434 }
433435
434- @BeforeClass(groups = { "isolated", "short", "long" })
436+ @BeforeClass(groups = {"isolated", "short", "long"})
435437 public void beforeClass() {
436438 maybeInitCluster();
437439 initKeyspace();
438440 }
439441
440- @AfterClass(groups = { "isolated", "short", "long" })
442+ @AfterClass(groups = {"isolated", "short", "long"})
441443 public void afterClass() {
442444 try {
443445 clearSimpleKeyspace();
444446 } finally {
445- if(cluster != null) {
447+ if (cluster != null) {
446448 cluster.close();
447449 }
448450 }
449451 }
450452
451- private void maybeInitCluster(){
452- if (!clusterInitialized){
453+ private void maybeInitCluster() {
454+ if (!clusterInitialized) {
453455 try {
454456 //launch ccm cluster
455457 ccmBridge = CCMBridge.builder("test-class").withoutNodes().notStarted().build();
@@ -483,8 +485,8 @@
483485 builder = configure(builder);
484486
485487 cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress))
486- .withNettyOptions(TestUtils.nonQuietClusterCloseOptions)
487- .build();
488+ .withNettyOptions(TestUtils.nonQuietClusterCloseOptions)
489+ .build();
488490 session = cluster.connect();
489491 keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet();
490492 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
@@ -511,7 +513,7 @@
511513 }
512514
513515 private void clearSimpleKeyspace() {
514- if(keyspace != null) {
516+ if (keyspace != null) {
515517 logger.debug("Removing keyspace {}.", keyspace);
516518 // Temporarily extend read timeout to 1 minute to accommodate dropping keyspaces and
517519 // tables being slow, particularly in a CI environment.
@@ -522,7 +524,7 @@
522524 if (ksm != null) {
523525 // drop each table individually as this seems to be more dependable than dropping
524526 // the entire keyspace at once if it has many tables.
525- if(ksm.getTables().size() > 10) {
527+ if (ksm.getTables().size() > 10) {
526528 for (TableMetadata table : ksm.getTables()) {
527529 logger.debug("Dropping table {}.{}.", keyspace, table.getName());
528530 session.execute("DROP TABLE " + keyspace + "." + table.getName());
@@ -609,10 +611,12 @@
609611 }
610612 }
611613
612- /** use {@link #builder(String)} to get an instance */
614+ /**
615+ * use {@link #builder(String)} to get an instance
616+ */
613617 public static class Builder {
614618 private final String clusterName;
615- private Integer[] nodes = { 1 };
619+ private Integer[] nodes = {1};
616620 private boolean start = true;
617621 private String cassandraInstallArgs = CASSANDRA_INSTALL_ARGS;
618622 private String[] startOptions = new String[0];
@@ -623,7 +627,9 @@
623627 this.clusterName = clusterName;
624628 }
625629
626- /** Number of nodes for each DC. Defaults to [1] (1 DC with 1 node) */
630+ /**
631+ * Number of nodes for each DC. Defaults to [1] (1 DC with 1 node)
632+ */
627633 public Builder withNodes(Integer... nodes) {
628634 this.nodes = nodes;
629635 return this;
@@ -646,25 +652,33 @@
646652 return this;
647653 }
648654
649- /** Whether to start the cluster immediately (defaults to true if this is never called) */
655+ /**
656+ * Whether to start the cluster immediately (defaults to true if this is never called)
657+ */
650658 public Builder notStarted() {
651659 this.start = false;
652660 return this;
653661 }
654662
655- /** Defaults to system property cassandra.version */
663+ /**
664+ * Defaults to system property cassandra.version
665+ */
656666 public Builder withCassandraVersion(String cassandraVersion) {
657667 this.cassandraInstallArgs = "-v " + cassandraVersion;
658668 return this;
659669 }
660670
661- /** Free-form options that will be added at the end of the start command */
671+ /**
672+ * Free-form options that will be added at the end of the start command
673+ */
662674 public Builder withStartOptions(String... options) {
663675 this.startOptions = options;
664676 return this;
665677 }
666678
667- /** Customizes entries in cassandra.yaml (can be called multiple times) */
679+ /**
680+ * Customizes entries in cassandra.yaml (can be called multiple times)
681+ */
668682 public Builder withCassandraConfiguration(String key, String value) {
669683 this.cassandraConfiguration.put(key, value);
670684 return this;
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +11 −14
@@ -17,11 +17,8 @@
1717
1818 import org.testng.annotations.Test;
1919
20-import static org.testng.Assert.assertEquals;
21-import static org.testng.Assert.assertNotNull;
22-import static org.testng.Assert.assertNull;
23-
2420 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
21+import static org.testng.Assert.*;
2522
2623 public class CaseSensitivityTest {
2724
@@ -38,11 +35,11 @@
3835 @Test(groups = "short")
3936 public void testCaseInsensitiveKeyspace() throws Throwable {
4037 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()
41- .withQueryOptions(new QueryOptions()
42- .setRefreshNodeIntervalMillis(0)
43- .setRefreshNodeListIntervalMillis(0)
44- .setRefreshSchemaIntervalMillis(0)
45- )
38+ .withQueryOptions(new QueryOptions()
39+ .setRefreshNodeIntervalMillis(0)
40+ .setRefreshNodeListIntervalMillis(0)
41+ .setRefreshSchemaIntervalMillis(0)
42+ )
4643 );
4744 Session s = c.session;
4845 try {
@@ -64,11 +61,11 @@
6461 @Test(groups = "short")
6562 public void testCaseSensitiveKeyspace() throws Throwable {
6663 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()
67- .withQueryOptions(new QueryOptions()
68- .setRefreshNodeIntervalMillis(0)
69- .setRefreshNodeListIntervalMillis(0)
70- .setRefreshSchemaIntervalMillis(0)
71- )
64+ .withQueryOptions(new QueryOptions()
65+ .setRefreshNodeIntervalMillis(0)
66+ .setRefreshNodeListIntervalMillis(0)
67+ .setRefreshSchemaIntervalMillis(0)
68+ )
7269 );
7370 Session s = c.session;
7471 try {
modified driver-core/src/test/java/com/datastax/driver/core/CassandraTypeParserTest.java +12 −16
@@ -15,17 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.Iterator;
20-
2118 import org.testng.annotations.Test;
2219
23-import static org.testng.Assert.assertEquals;
24-import static org.testng.Assert.assertFalse;
25-import static org.testng.Assert.assertNotNull;
26-import static org.testng.Assert.assertTrue;
20+import java.util.Arrays;
21+import java.util.Iterator;
2722
2823 import static com.datastax.driver.core.Assertions.assertThat;
24+import static org.testng.Assert.*;
2925
3026 public class CassandraTypeParserTest {
3127
@@ -66,7 +62,7 @@
6662 public void parseUserTypes() {
6763
6864 String s = "org.apache.cassandra.db.marshal.UserType(foo,61646472657373,737472656574:org.apache.cassandra.db.marshal.UTF8Type,7a6970636f6465:org.apache.cassandra.db.marshal.Int32Type,70686f6e6573:org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UserType(foo,70686f6e65,6e616d65:org.apache.cassandra.db.marshal.UTF8Type,6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)))";
69- UserType def = (UserType)CassandraTypeParser.parseOne(s);
65+ UserType def = (UserType) CassandraTypeParser.parseOne(s);
7066
7167 assertEquals(def.getKeyspace(), "foo");
7268 assertEquals(def.getTypeName(), "address");
@@ -86,7 +82,7 @@
8682
8783 DataType st = field3.getType();
8884 assertEquals(st.getName(), DataType.Name.SET);
89- UserType subDef = (UserType)st.getTypeArguments().get(0);
85+ UserType subDef = (UserType) st.getTypeArguments().get(0);
9086
9187 assertEquals(subDef.getKeyspace(), "foo");
9288 assertEquals(subDef.getTypeName(), "phone");
@@ -105,7 +101,7 @@
105101 @Test(groups = "unit")
106102 public void parseTupleTest() {
107103 String s = "org.apache.cassandra.db.marshal.TupleType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FloatType)";
108- TupleType type = (TupleType)CassandraTypeParser.parseOne(s);
104+ TupleType type = (TupleType) CassandraTypeParser.parseOne(s);
109105 assertNotNull(type);
110106 assertEquals(type.getComponentTypes().get(0), DataType.cint());
111107 assertEquals(type.getComponentTypes().get(1), DataType.text());
@@ -119,14 +115,14 @@
119115
120116 DataType parentMap = CassandraTypeParser.parseOne(s);
121117 assertThat(parentMap)
122- .hasName(DataType.Name.MAP)
123- .isNotFrozen()
124- .hasTypeArgument(0, DataType.text());
118+ .hasName(DataType.Name.MAP)
119+ .isNotFrozen()
120+ .hasTypeArgument(0, DataType.text());
125121
126122 DataType childMap = parentMap.getTypeArguments().get(1);
127123 assertThat(childMap)
128- .hasName(DataType.Name.MAP)
129- .isFrozen()
130- .hasTypeArguments(DataType.cint(), DataType.cint());
124+ .hasName(DataType.Name.MAP)
125+ .isFrozen()
126+ .hasTypeArguments(DataType.cint(), DataType.cint());
131127 }
132128 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +15 −14
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.collect.Iterators;
19+import org.assertj.core.api.AbstractAssert;
20+
1821 import java.util.Iterator;
1922 import java.util.Set;
2023 import java.util.TreeSet;
2124 import java.util.concurrent.TimeUnit;
2225
23-import com.google.common.collect.Iterators;
24-import org.assertj.core.api.AbstractAssert;
25-
2626 import static org.assertj.core.api.Assertions.assertThat;
2727
2828 public class ClusterAssert extends AbstractAssert<ClusterAssert, Cluster> {
@@ -56,26 +56,27 @@
5656 // Wait for the node to be added if it's not already known.
5757 // In 2.2+ C* does not send an added event until the node is ready so we wait a long time.
5858 Host host = TestUtils.findOrWaitForHost(actual, hostNumber,
59- 60 + Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
59+ 60 + Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
6060 return new HostAssert(host, actual);
6161 }
6262
6363 public HostAssert host(String hostAddress) {
6464 Host host = TestUtils.findOrWaitForHost(actual, hostAddress,
65- 60 + Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
65+ 60 + Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
6666 return new HostAssert(host, actual);
6767 }
6868
6969 /**
7070 * Asserts that {@link Cluster}'s {@link Host}s have valid {@link TokenRange}s with the given keyspace.
71- *
71+ * <p/>
7272 * Ensures that no ranges intersect and that they cover the entire ring.
73+ *
7374 * @param keyspace Keyspace to grab {@link TokenRange}s from.
7475 */
7576 public ClusterAssert hasValidTokenRanges(String keyspace) {
7677 // Sort the token ranges so they are in order (needed for vnodes).
7778 Set<TokenRange> ranges = new TreeSet<TokenRange>();
78- for(Host host : actual.getMetadata().getAllHosts()) {
79+ for (Host host : actual.getMetadata().getAllHosts()) {
7980 ranges.addAll(actual.getMetadata().getTokenRanges(keyspace, host));
8081 }
8182 return hasValidTokenRanges(ranges);
@@ -83,7 +84,7 @@
8384
8485 /**
8586 * Asserts that {@link Cluster}'s {@link Host}s have valid {@link TokenRange}s.
86- *
87+ * <p/>
8788 * Ensures that no ranges intersect and that they cover the entire ring.
8889 */
8990 public ClusterAssert hasValidTokenRanges() {
@@ -94,13 +95,13 @@
9495
9596 /**
9697 * Asserts that given Set of {@link TokenRange}s are valid.
97- *
98+ * <p/>
9899 * Ensures that no ranges intersect and that they cover the entire ring.
99100 */
100101 private ClusterAssert hasValidTokenRanges(Set<TokenRange> ranges) {
101102 // Ensure no ranges intersect.
102103 Iterator<TokenRange> it = ranges.iterator();
103- while(it.hasNext()) {
104+ while (it.hasNext()) {
104105 TokenRange range = it.next();
105106 Assertions.assertThat(range).doesNotIntersect(Iterators.toArray(it, TokenRange.class));
106107 }
@@ -108,15 +109,15 @@
108109 // Ensure the defined ranges cover the entire ring.
109110 it = ranges.iterator();
110111 TokenRange mergedRange = it.next();
111- while(it.hasNext()) {
112+ while (it.hasNext()) {
112113 TokenRange next = it.next();
113114 mergedRange = mergedRange.mergeWith(next);
114115 }
115116 boolean isFullRing = mergedRange.getStart().equals(mergedRange.getEnd())
116- && !mergedRange.isEmpty();
117+ && !mergedRange.isEmpty();
117118 assertThat(isFullRing)
118- .as("Ring is not fully defined for Cluster.")
119- .isTrue();
119+ .as("Ring is not fully defined for Cluster.")
120+ .isTrue();
120121
121122 return this;
122123 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterDelegateTest.java +2 −2
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
2018 import com.google.common.collect.Lists;
2119 import org.testng.annotations.Test;
2220
21+import java.util.Collection;
22+
2323 import static org.assertj.core.api.Assertions.assertThat;
2424
2525 public class ClusterDelegateTest extends CCMBridge.PerClassSingleNodeCluster {
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +58 −64
@@ -15,19 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.net.InetSocketAddress;
20-import java.net.UnknownHostException;
21-import java.util.Collections;
22-import java.util.List;
23-import java.util.Map;
24-import java.util.concurrent.TimeUnit;
25-import java.util.concurrent.TimeoutException;
26-
18+import com.datastax.driver.core.exceptions.NoHostAvailableException;
19+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
2720 import com.google.common.collect.ImmutableMap;
2821 import com.google.common.collect.ImmutableSet;
2922 import com.google.common.collect.Lists;
30-import com.google.common.collect.Maps;
3123 import com.google.common.util.concurrent.Uninterruptibles;
3224 import org.scassandra.Scassandra;
3325 import org.scassandra.http.client.PrimingClient;
@@ -37,13 +29,14 @@
3729 import org.testng.SkipException;
3830 import org.testng.annotations.Test;
3931
40-import static org.mockito.Mockito.atLeast;
41-import static org.mockito.Mockito.atMost;
42-import static org.mockito.Mockito.spy;
43-import static org.mockito.Mockito.verify;
44-
45-import com.datastax.driver.core.exceptions.NoHostAvailableException;
46-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
32+import java.net.InetAddress;
33+import java.net.InetSocketAddress;
34+import java.net.UnknownHostException;
35+import java.util.Collections;
36+import java.util.List;
37+import java.util.Map;
38+import java.util.concurrent.TimeUnit;
39+import java.util.concurrent.TimeoutException;
4740
4841 import static com.datastax.driver.core.Assertions.assertThat;
4942 import static com.datastax.driver.core.Assertions.fail;
@@ -51,6 +44,7 @@
5144 import static com.datastax.driver.core.HostDistance.LOCAL;
5245 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
5346 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
47+import static org.mockito.Mockito.*;
5448
5549 public class ClusterInitTest {
5650 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
@@ -104,19 +98,19 @@
10498 PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(LOCAL, 1, 1);
10599
106100 cluster = Cluster.builder()
107- .withPort(scassandra.getBinaryPort())
108- .addContactPoints(
109- realHostAddress,
110- failingHosts.get(0).address, failingHosts.get(1).address,
111- failingHosts.get(2).address, failingHosts.get(3).address,
112- missingHostAddress
113- )
114- .withSocketOptions(socketOptions)
115- .withReconnectionPolicy(reconnectionPolicy)
116- .withPoolingOptions(poolingOptions)
117- .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
118- .withQueryOptions(nonDebouncingQueryOptions())
119- .build();
101+ .withPort(scassandra.getBinaryPort())
102+ .addContactPoints(
103+ realHostAddress,
104+ failingHosts.get(0).address, failingHosts.get(1).address,
105+ failingHosts.get(2).address, failingHosts.get(3).address,
106+ missingHostAddress
107+ )
108+ .withSocketOptions(socketOptions)
109+ .withReconnectionPolicy(reconnectionPolicy)
110+ .withPoolingOptions(poolingOptions)
111+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
112+ .withQueryOptions(nonDebouncingQueryOptions())
113+ .build();
120114 cluster.connect();
121115
122116 // For information only:
@@ -142,7 +136,7 @@
142136 // There is a possible race here in that the host is marked down in a separate Executor in onDown
143137 // and then starts a periodic reconnection attempt shortly after. Since setDown is called before
144138 // startPeriodicReconnectionAttempt, we add a slight delay here if the future isn't set yet.
145- if(host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone()) {
139+ if (host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone()) {
146140 logger.warn("Periodic Reconnection Attempt hasn't started yet for {}, waiting 1 second and then checking.", host);
147141 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
148142 }
@@ -168,19 +162,19 @@
168162 * @jira_ticket JAVA-954
169163 * @expected_result No reconnection scheduled.
170164 */
171- @Test(groups="short", expectedExceptions = NoHostAvailableException.class)
165+ @Test(groups = "short", expectedExceptions = NoHostAvailableException.class)
172166 public void should_not_schedule_reconnections_before_init_complete() {
173167 // Both contact points time out so we're sure we'll try both of them and init will never complete.
174168 List<FakeHost> hosts = Lists.newArrayList(
175- new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS),
176- new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS));
169+ new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS),
170+ new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS));
177171 // Use a low reconnection interval and keep the default connect timeout (5 seconds). So if a reconnection was scheduled,
178172 // we would see a call to the reconnection policy.
179173 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(100));
180174 Cluster cluster = Cluster.builder()
181- .addContactPoints(hosts.get(0).address, hosts.get(1).address)
182- .withReconnectionPolicy(reconnectionPolicy)
183- .build();
175+ .addContactPoints(hosts.get(0).address, hosts.get(1).address)
176+ .withReconnectionPolicy(reconnectionPolicy)
177+ .build();
184178 try {
185179 cluster.init();
186180 } finally {
@@ -205,9 +199,9 @@
205199 @Test(groups = "short")
206200 public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
207201 Cluster cluster = Cluster.builder()
208- .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
209- .withNettyOptions(nonQuietClusterCloseOptions)
210- .build();
202+ .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
203+ .withNettyOptions(nonQuietClusterCloseOptions)
204+ .build();
211205 try {
212206 cluster.connect();
213207 fail("Should not have been able to connect.");
@@ -228,23 +222,23 @@
228222 * @jira_ticket JAVA-854
229223 * @test_category host:state
230224 */
231- @Test(groups="short")
225+ @Test(groups = "short")
232226 public void should_not_abort_init_if_host_does_not_support_protocol_version() {
233227 ScassandraCluster scassandraCluster = ScassandraCluster.builder()
234- .withIpPrefix(CCMBridge.IP_PREFIX)
235- .withNodes(5)
236- // For node 2, report an older version which uses protocol v1.
237- .forcePeerInfo(1, 2, "release_version", "1.2.19")
238- .build();
228+ .withIpPrefix(CCMBridge.IP_PREFIX)
229+ .withNodes(5)
230+ // For node 2, report an older version which uses protocol v1.
231+ .forcePeerInfo(1, 2, "release_version", "1.2.19")
232+ .build();
239233 Cluster cluster = Cluster.builder()
240- .addContactPoints(scassandraCluster.address(1))
241- .withNettyOptions(nonQuietClusterCloseOptions)
242- .build();
234+ .addContactPoints(scassandraCluster.address(1))
235+ .withNettyOptions(nonQuietClusterCloseOptions)
236+ .build();
243237
244238 try {
245239 scassandraCluster.init();
246240 cluster.init();
247- for(int i = 1; i <= 5; i++) {
241+ for (int i = 1; i <= 5; i++) {
248242 String hostAddress = scassandraCluster.address(i);
249243 if (i == 2) {
250244 // As this host is at an older protocol version, it should be ignored and not marked up.
@@ -263,8 +257,8 @@
263257
264258 private void primePeerRows(Scassandra scassandra, List<FakeHost> otherHosts) throws UnknownHostException {
265259 PrimingClient primingClient = PrimingClient.builder()
266- .withHost("localhost").withPort(scassandra.getAdminPort())
267- .build();
260+ .withHost("localhost").withPort(scassandra.getAdminPort())
261+ .build();
268262
269263 List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(5);
270264
@@ -272,20 +266,20 @@
272266 for (FakeHost otherHost : otherHosts) {
273267 InetAddress address = InetAddress.getByName(otherHost.address);
274268 rows.add(ImmutableMap.<String, Object>builder()
275- .put("peer", address)
276- .put("rpc_address", address)
277- .put("data_center", "datacenter1")
278- .put("rack", "rack1")
279- .put("release_version", "2.0.1")
280- .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++)))
281- .build());
269+ .put("peer", address)
270+ .put("rpc_address", address)
271+ .put("data_center", "datacenter1")
272+ .put("rack", "rack1")
273+ .put("release_version", "2.0.1")
274+ .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++)))
275+ .build());
282276 }
283277
284278 primingClient.prime(
285- PrimingRequest.queryBuilder()
286- .withQuery("SELECT * FROM system.peers")
287- .withColumnTypes(ScassandraCluster.SELECT_PEERS)
288- .withRows(rows)
289- .build());
279+ PrimingRequest.queryBuilder()
280+ .withQuery("SELECT * FROM system.peers")
281+ .withColumnTypes(ScassandraCluster.SELECT_PEERS)
282+ .withRows(rows)
283+ .build());
290284 }
291285 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +5 −5
@@ -108,7 +108,7 @@
108108 if (error == null) {
109109 Throwable cause = e.getCause();
110110 if (cause instanceof AssertionError)
111- error = (AssertionError)cause;
111+ error = (AssertionError) cause;
112112 else
113113 error = assertionError("Error while creating a cluster", cause);
114114 }
@@ -136,7 +136,7 @@
136136 if (error == null) {
137137 Throwable cause = e.getCause();
138138 if (cause instanceof AssertionError)
139- error = (AssertionError)cause;
139+ error = (AssertionError) cause;
140140 else
141141 error = assertionError("Error while closing a cluster", cause);
142142 }
@@ -169,19 +169,19 @@
169169 // There should be 1 control connection after initializing.
170170 cluster.init();
171171 assertEquals(cluster.manager.sessions.size(), 0);
172- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
172+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
173173 assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
174174
175175 // The first session initializes the cluster and its control connection
176176 Session session = cluster.connect();
177177 assertEquals(cluster.manager.sessions.size(), 1);
178- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
178+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
179179 assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
180180
181181 // Closing the session keeps the control connection opened
182182 session.close();
183183 assertEquals(cluster.manager.sessions.size(), 0);
184- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
184+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
185185 assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
186186
187187 return this;
modified driver-core/src/test/java/com/datastax/driver/core/ColumnDefinitionsTest.java +14 −13
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import org.testng.annotations.Test;
19+
1920 import static org.testng.Assert.assertTrue;
2021
2122 public class ColumnDefinitionsTest {
@@ -26,9 +27,9 @@
2627 ColumnDefinitions defs;
2728
2829 defs = new ColumnDefinitions(new ColumnDefinitions.Definition[]{
29- new ColumnDefinitions.Definition("ks", "cf", "aColumn", DataType.text()),
30- new ColumnDefinitions.Definition("ks", "cf", "fOO", DataType.text()),
31- new ColumnDefinitions.Definition("ks", "cf", "anotherColumn", DataType.text())
30+ new ColumnDefinitions.Definition("ks", "cf", "aColumn", DataType.text()),
31+ new ColumnDefinitions.Definition("ks", "cf", "fOO", DataType.text()),
32+ new ColumnDefinitions.Definition("ks", "cf", "anotherColumn", DataType.text())
3233 });
3334
3435 assertTrue(defs.contains("foo"));
@@ -36,13 +37,13 @@
3637 assertTrue(defs.contains("FOO"));
3738
3839 defs = new ColumnDefinitions(new ColumnDefinitions.Definition[]{
39- new ColumnDefinitions.Definition("ks", "cf", "aColumn", DataType.text()),
40- new ColumnDefinitions.Definition("ks", "cf", "foo", DataType.text()),
41- new ColumnDefinitions.Definition("ks", "cf", "anotherColumn", DataType.text()),
42- new ColumnDefinitions.Definition("ks", "cf", "FOO", DataType.cint()),
43- new ColumnDefinitions.Definition("ks", "cf", "with \" quote", DataType.text()),
44- new ColumnDefinitions.Definition("ks", "cf", "\"in quote\"", DataType.text()),
45- new ColumnDefinitions.Definition("ks", "cf", "in quote", DataType.cint()),
40+ new ColumnDefinitions.Definition("ks", "cf", "aColumn", DataType.text()),
41+ new ColumnDefinitions.Definition("ks", "cf", "foo", DataType.text()),
42+ new ColumnDefinitions.Definition("ks", "cf", "anotherColumn", DataType.text()),
43+ new ColumnDefinitions.Definition("ks", "cf", "FOO", DataType.cint()),
44+ new ColumnDefinitions.Definition("ks", "cf", "with \" quote", DataType.text()),
45+ new ColumnDefinitions.Definition("ks", "cf", "\"in quote\"", DataType.text()),
46+ new ColumnDefinitions.Definition("ks", "cf", "in quote", DataType.cint()),
4647 });
4748
4849 assertTrue(defs.getType("foo").equals(DataType.text()));
@@ -61,9 +62,9 @@
6162 public void multiDefinitionTest() {
6263
6364 ColumnDefinitions defs = new ColumnDefinitions(new ColumnDefinitions.Definition[]{
64- new ColumnDefinitions.Definition("ks", "cf1", "column", DataType.text()),
65- new ColumnDefinitions.Definition("ks", "cf2", "column", DataType.cint()),
66- new ColumnDefinitions.Definition("ks", "cf3", "column", DataType.cfloat())
65+ new ColumnDefinitions.Definition("ks", "cf1", "column", DataType.text()),
66+ new ColumnDefinitions.Definition("ks", "cf2", "column", DataType.cint()),
67+ new ColumnDefinitions.Definition("ks", "cf3", "column", DataType.cfloat())
6768 });
6869
6970 assertTrue(defs.getType("column").equals(DataType.text()));
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +6 −5
@@ -15,18 +15,19 @@
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.util.Collection;
1922 import java.util.Collections;
2023
21-import org.testng.annotations.Test;
22-import static org.testng.Assert.*;
23-
24-import com.datastax.driver.core.utils.CassandraVersion;
24+import static org.testng.Assert.assertFalse;
25+import static org.testng.Assert.assertTrue;
2526
2627 /**
2728 * Test {@link ResultSet#wasApplied()} for conditional updates.
2829 */
29-@CassandraVersion(major=2.0, description="Conditional Updates requires 2.0+.")
30+@CassandraVersion(major = 2.0, description = "Conditional Updates requires 2.0+.")
3031 public class ConditionalUpdateTest extends CCMBridge.PerClassSingleNodeCluster {
3132
3233 @Override
modified driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java +16 −16
@@ -34,32 +34,32 @@
3434 public class ConnectionReleaseTest extends ScassandraTestBase {
3535
3636 /**
37- * <p>
37+ * <p/>
3838 * Validates that when a future is set that the stream associated with the future's request is released.
3939 * This prevents situations where a user may not be specifying a separate executor on a callback/
4040 * transform to a ResultSetFuture, which is not recommended, causing executeAsync to block in borrowConnection
4141 * until stream ids become available.
42- *
42+ * <p/>
4343 * Executes the following:
44- *
44+ * <p/>
4545 * <ol>
46- * <li>Sets # of connections per host to 1.</li>
47- * <li>Sends MAX_STREAM_PER_CONNECTION-1 requests that take 10 seconds to execute.</li>
48- * <li>Calls executeAsync to retrieve records from test1 with k=1.</li>
49- * <li>Transforms executeAsync to take the 'c' column from the result and query test2.
50- * This is done without an executor to ensure the netty worker is used and has to wait for the function
51- * completion.</li>
52- * <li>Asserts that the transformed future completes within pool timeout and the value is as expected.</li>
46+ * <li>Sets # of connections per host to 1.</li>
47+ * <li>Sends MAX_STREAM_PER_CONNECTION-1 requests that take 10 seconds to execute.</li>
48+ * <li>Calls executeAsync to retrieve records from test1 with k=1.</li>
49+ * <li>Transforms executeAsync to take the 'c' column from the result and query test2.
50+ * This is done without an executor to ensure the netty worker is used and has to wait for the function
51+ * completion.</li>
52+ * <li>Asserts that the transformed future completes within pool timeout and the value is as expected.</li>
5353 * </ol>
5454 *
5555 * @jira_ticket JAVA-666
5656 * @expected_result Are able to transform a Future without hanging in executeAsync as connection should be freed
57- * before the transform function is called.
57+ * before the transform function is called.
5858 * @test_category queries:async
5959 * @since 2.0.10, 2.1.6
6060 */
6161 @SuppressWarnings("unchecked")
62- @Test(groups="short")
62+ @Test(groups = "short")
6363 public void should_release_connection_before_completing_future() throws Exception {
6464 Cluster cluster = null;
6565 Collection<ResultSetFuture> mockFutures = Lists.newArrayList();
@@ -93,7 +93,7 @@
9393
9494 final Session session = cluster.connect("ks");
9595 // Consume all stream ids except one.
96- for(int i = 0; i < StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2-1; i++)
96+ for (int i = 0; i < StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2 - 1; i++)
9797 mockFutures.add(session.executeAsync("mock query"));
9898
9999
@@ -115,15 +115,15 @@
115115 try {
116116 ResultSet result = future.get(waitTimeInMs, TimeUnit.MILLISECONDS);
117117 assertThat(result.one().getString("n")).isEqualTo("world");
118- } catch (TimeoutException e) {
118+ } catch (TimeoutException e) {
119119 fail("Future timed out after " + waitTimeInMs + "ms. " +
120120 "There is a strong possibility connection is not being released.");
121121 }
122122 } finally {
123123 // Cancel all pending requests.
124- for(ResultSetFuture future : mockFutures)
124+ for (ResultSetFuture future : mockFutures)
125125 future.cancel(true);
126- if(cluster != null)
126+ if (cluster != null)
127127 cluster.close();
128128 }
129129 }
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +91 −92
@@ -15,15 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.EnumSet;
20-import java.util.List;
21-import java.util.Set;
22-
23-import org.slf4j.Logger;
24-import org.slf4j.LoggerFactory;
25-import org.testng.annotations.Test;
26-
2718 import com.datastax.driver.core.exceptions.InvalidQueryException;
2819 import com.datastax.driver.core.exceptions.ReadTimeoutException;
2920 import com.datastax.driver.core.exceptions.UnavailableException;
@@ -32,6 +23,14 @@
3223 import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
3324 import com.datastax.driver.core.policies.RoundRobinPolicy;
3425 import com.datastax.driver.core.policies.TokenAwarePolicy;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+import org.testng.annotations.Test;
29+
30+import java.util.Arrays;
31+import java.util.EnumSet;
32+import java.util.List;
33+import java.util.Set;
3534
3635 import static com.datastax.driver.core.TestUtils.stopAndWait;
3736 import static org.testng.Assert.assertTrue;
@@ -61,13 +60,13 @@
6160 List<ConsistencyLevel> acceptedList = Arrays.asList(ConsistencyLevel.ANY);
6261
6362 List<ConsistencyLevel> failList = Arrays.asList(
64- ConsistencyLevel.ONE,
65- ConsistencyLevel.TWO,
66- ConsistencyLevel.THREE,
67- ConsistencyLevel.QUORUM,
68- ConsistencyLevel.ALL,
69- ConsistencyLevel.LOCAL_QUORUM,
70- ConsistencyLevel.EACH_QUORUM);
63+ ConsistencyLevel.ONE,
64+ ConsistencyLevel.TWO,
65+ ConsistencyLevel.THREE,
66+ ConsistencyLevel.QUORUM,
67+ ConsistencyLevel.ALL,
68+ ConsistencyLevel.LOCAL_QUORUM,
69+ ConsistencyLevel.EACH_QUORUM);
7170
7271 // Test successful writes
7372 for (ConsistencyLevel cl : acceptedList) {
@@ -84,7 +83,7 @@
8483 query(c, 12, cl);
8584 } catch (InvalidQueryException e) {
8685 List<String> acceptableErrorMessages = Arrays.asList(
87- "ANY ConsistencyLevel is only supported for writes");
86+ "ANY ConsistencyLevel is only supported for writes");
8887 assertTrue(acceptableErrorMessages.contains(e.getMessage()));
8988 }
9089 }
@@ -96,8 +95,8 @@
9695 fail(String.format("Test passed at CL.%s.", cl));
9796 } catch (InvalidQueryException e) {
9897 List<String> acceptableErrorMessages = Arrays.asList(
99- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
100- "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
98+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
99+ "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
101100 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
102101 } catch (UnavailableException e) {
103102 // expected to fail when the client has already marked the
@@ -115,8 +114,8 @@
115114 fail(String.format("Test passed at CL.%s.", cl));
116115 } catch (InvalidQueryException e) {
117116 List<String> acceptableErrorMessages = Arrays.asList(
118- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
119- "EACH_QUORUM ConsistencyLevel is only supported for writes");
117+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
118+ "EACH_QUORUM ConsistencyLevel is only supported for writes");
120119 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
121120 } catch (ReadTimeoutException e) {
122121 // expected to fail when the client hasn't marked the
@@ -154,17 +153,17 @@
154153 stopAndWait(c, 2);
155154
156155 List<ConsistencyLevel> acceptedList = Arrays.asList(
157- ConsistencyLevel.ANY,
158- ConsistencyLevel.ONE
159- );
156+ ConsistencyLevel.ANY,
157+ ConsistencyLevel.ONE
158+ );
160159
161160 List<ConsistencyLevel> failList = Arrays.asList(
162- ConsistencyLevel.TWO,
163- ConsistencyLevel.QUORUM,
164- ConsistencyLevel.THREE,
165- ConsistencyLevel.ALL,
166- ConsistencyLevel.LOCAL_QUORUM,
167- ConsistencyLevel.EACH_QUORUM);
161+ ConsistencyLevel.TWO,
162+ ConsistencyLevel.QUORUM,
163+ ConsistencyLevel.THREE,
164+ ConsistencyLevel.ALL,
165+ ConsistencyLevel.LOCAL_QUORUM,
166+ ConsistencyLevel.EACH_QUORUM);
168167
169168 // Test successful writes
170169 for (ConsistencyLevel cl : acceptedList) {
@@ -181,7 +180,7 @@
181180 query(c, 12, cl);
182181 } catch (InvalidQueryException e) {
183182 List<String> acceptableErrorMessages = Arrays.asList(
184- "ANY ConsistencyLevel is only supported for writes");
183+ "ANY ConsistencyLevel is only supported for writes");
185184 assertTrue(acceptableErrorMessages.contains(e.getMessage()));
186185 }
187186 }
@@ -193,8 +192,8 @@
193192 fail(String.format("Test passed at CL.%s.", cl));
194193 } catch (InvalidQueryException e) {
195194 List<String> acceptableErrorMessages = Arrays.asList(
196- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
197- "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
195+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
196+ "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
198197 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
199198 } catch (UnavailableException e) {
200199 // expected to fail when the client has already marked the
@@ -212,8 +211,8 @@
212211 fail(String.format("Test passed at CL.%s.", cl));
213212 } catch (InvalidQueryException e) {
214213 List<String> acceptableErrorMessages = Arrays.asList(
215- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
216- "EACH_QUORUM ConsistencyLevel is only supported for writes");
214+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
215+ "EACH_QUORUM ConsistencyLevel is only supported for writes");
217216 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
218217 } catch (ReadTimeoutException e) {
219218 // expected to fail when the client hasn't marked the
@@ -256,18 +255,18 @@
256255 cls.remove(ConsistencyLevel.LOCAL_SERIAL);
257256
258257 List<ConsistencyLevel> acceptedList = Arrays.asList(
259- ConsistencyLevel.ANY,
260- ConsistencyLevel.ONE,
261- ConsistencyLevel.TWO,
262- ConsistencyLevel.QUORUM,
263- ConsistencyLevel.LOCAL_QUORUM,
264- ConsistencyLevel.EACH_QUORUM
265- );
258+ ConsistencyLevel.ANY,
259+ ConsistencyLevel.ONE,
260+ ConsistencyLevel.TWO,
261+ ConsistencyLevel.QUORUM,
262+ ConsistencyLevel.LOCAL_QUORUM,
263+ ConsistencyLevel.EACH_QUORUM
264+ );
266265
267266 List<ConsistencyLevel> failList = Arrays.asList(
268- ConsistencyLevel.THREE,
269- ConsistencyLevel.ALL
270- );
267+ ConsistencyLevel.THREE,
268+ ConsistencyLevel.ALL
269+ );
271270
272271
273272 // Test successful writes
@@ -285,8 +284,8 @@
285284 query(c, 12, cl);
286285 } catch (InvalidQueryException e) {
287286 List<String> acceptableErrorMessages = Arrays.asList(
288- "ANY ConsistencyLevel is only supported for writes",
289- "EACH_QUORUM ConsistencyLevel is only supported for writes"
287+ "ANY ConsistencyLevel is only supported for writes",
288+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
290289 );
291290 assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
292291 }
@@ -348,17 +347,17 @@
348347 stopAndWait(c, 2);
349348
350349 List<ConsistencyLevel> acceptedList = Arrays.asList(
351- ConsistencyLevel.ANY
352- );
350+ ConsistencyLevel.ANY
351+ );
353352
354353 List<ConsistencyLevel> failList = Arrays.asList(
355- ConsistencyLevel.ONE,
356- ConsistencyLevel.TWO,
357- ConsistencyLevel.THREE,
358- ConsistencyLevel.QUORUM,
359- ConsistencyLevel.ALL,
360- ConsistencyLevel.LOCAL_QUORUM,
361- ConsistencyLevel.EACH_QUORUM);
354+ ConsistencyLevel.ONE,
355+ ConsistencyLevel.TWO,
356+ ConsistencyLevel.THREE,
357+ ConsistencyLevel.QUORUM,
358+ ConsistencyLevel.ALL,
359+ ConsistencyLevel.LOCAL_QUORUM,
360+ ConsistencyLevel.EACH_QUORUM);
362361
363362 // Test successful writes
364363 for (ConsistencyLevel cl : acceptedList) {
@@ -375,7 +374,7 @@
375374 query(c, 12, cl);
376375 } catch (InvalidQueryException e) {
377376 List<String> acceptableErrorMessages = Arrays.asList(
378- "ANY ConsistencyLevel is only supported for writes");
377+ "ANY ConsistencyLevel is only supported for writes");
379378 assertTrue(acceptableErrorMessages.contains(e.getMessage()));
380379 }
381380 }
@@ -401,7 +400,7 @@
401400 fail(String.format("Test passed at CL.%s.", cl));
402401 } catch (InvalidQueryException e) {
403402 List<String> acceptableErrorMessages = Arrays.asList(
404- "EACH_QUORUM ConsistencyLevel is only supported for writes"
403+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
405404 );
406405 assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
407406 } catch (ReadTimeoutException e) {
@@ -425,8 +424,8 @@
425424 @Test(groups = "long")
426425 public void testRFTwoDowngradingCL() throws Throwable {
427426 Cluster.Builder builder = Cluster.builder()
428- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
429- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
427+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
428+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
430429 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
431430 try {
432431
@@ -461,8 +460,8 @@
461460 query(c, 12, cl);
462461 } catch (InvalidQueryException e) {
463462 List<String> acceptableErrorMessages = Arrays.asList(
464- "ANY ConsistencyLevel is only supported for writes",
465- "EACH_QUORUM ConsistencyLevel is only supported for writes"
463+ "ANY ConsistencyLevel is only supported for writes",
464+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
466465 );
467466 assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
468467 }
@@ -486,8 +485,8 @@
486485 @Test(groups = "long")
487486 public void testRFThreeTokenAwareDowngradingCL() throws Throwable {
488487 Cluster.Builder builder = Cluster.builder()
489- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
490- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
488+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
489+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
491490 testRFThreeDowngradingCL(builder);
492491 }
493492
@@ -535,8 +534,8 @@
535534 query(c, 12, cl);
536535 } catch (InvalidQueryException e) {
537536 List<String> acceptableErrorMessages = Arrays.asList(
538- "ANY ConsistencyLevel is only supported for writes",
539- "EACH_QUORUM ConsistencyLevel is only supported for writes"
537+ "ANY ConsistencyLevel is only supported for writes",
538+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
540539 );
541540 assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
542541 }
@@ -554,8 +553,8 @@
554553 @Test(groups = "long")
555554 public void testRFThreeDowngradingCLTwoDCs() throws Throwable {
556555 Cluster.Builder builder = Cluster.builder()
557- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
558- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
556+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
557+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
559558 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder);
560559 try {
561560
@@ -576,15 +575,15 @@
576575 logger.info("Node 3 stopped.");
577576
578577 List<ConsistencyLevel> acceptedList = Arrays.asList(
579- ConsistencyLevel.ANY,
580- ConsistencyLevel.ONE,
581- ConsistencyLevel.TWO,
582- ConsistencyLevel.QUORUM,
583- ConsistencyLevel.THREE,
584- ConsistencyLevel.ALL,
585- ConsistencyLevel.LOCAL_QUORUM,
586- ConsistencyLevel.EACH_QUORUM
587- );
578+ ConsistencyLevel.ANY,
579+ ConsistencyLevel.ONE,
580+ ConsistencyLevel.TWO,
581+ ConsistencyLevel.QUORUM,
582+ ConsistencyLevel.THREE,
583+ ConsistencyLevel.ALL,
584+ ConsistencyLevel.LOCAL_QUORUM,
585+ ConsistencyLevel.EACH_QUORUM
586+ );
588587
589588 List<ConsistencyLevel> failList = Arrays.asList();
590589
@@ -605,8 +604,8 @@
605604 query(c, 12, cl);
606605 } catch (InvalidQueryException e) {
607606 List<String> acceptableErrorMessages = Arrays.asList(
608- "EACH_QUORUM ConsistencyLevel is only supported for writes",
609- "ANY ConsistencyLevel is only supported for writes");
607+ "EACH_QUORUM ConsistencyLevel is only supported for writes",
608+ "ANY ConsistencyLevel is only supported for writes");
610609 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
611610 }
612611 }
@@ -653,8 +652,8 @@
653652 @Test(groups = "long")
654653 public void testRFThreeDowngradingCLTwoDCsDCAware() throws Throwable {
655654 Cluster.Builder builder = Cluster.builder()
656- .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("dc2"), false))
657- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
655+ .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("dc2"), false))
656+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
658657 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder);
659658 try {
660659
@@ -673,15 +672,15 @@
673672 c.cassandraCluster.stop(2);
674673
675674 List<ConsistencyLevel> acceptedList = Arrays.asList(
676- ConsistencyLevel.ANY,
677- ConsistencyLevel.ONE,
678- ConsistencyLevel.TWO,
679- ConsistencyLevel.QUORUM,
680- ConsistencyLevel.THREE,
681- ConsistencyLevel.ALL,
682- ConsistencyLevel.LOCAL_QUORUM,
683- ConsistencyLevel.EACH_QUORUM
684- );
675+ ConsistencyLevel.ANY,
676+ ConsistencyLevel.ONE,
677+ ConsistencyLevel.TWO,
678+ ConsistencyLevel.QUORUM,
679+ ConsistencyLevel.THREE,
680+ ConsistencyLevel.ALL,
681+ ConsistencyLevel.LOCAL_QUORUM,
682+ ConsistencyLevel.EACH_QUORUM
683+ );
685684
686685 List<ConsistencyLevel> failList = Arrays.asList();
687686
@@ -700,8 +699,8 @@
700699 query(c, 12, cl);
701700 } catch (InvalidQueryException e) {
702701 List<String> acceptableErrorMessages = Arrays.asList(
703- "EACH_QUORUM ConsistencyLevel is only supported for writes",
704- "ANY ConsistencyLevel is only supported for writes");
702+ "EACH_QUORUM ConsistencyLevel is only supported for writes",
703+ "ANY ConsistencyLevel is only supported for writes");
705704 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
706705 }
707706 }
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +32 −35
@@ -15,32 +15,29 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.util.Collection;
20-import java.util.Iterator;
21-import java.util.Map;
22-import java.util.concurrent.TimeUnit;
23-import java.util.concurrent.atomic.AtomicInteger;
24-
18+import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy;
19+import com.datastax.driver.core.policies.LoadBalancingPolicy;
20+import com.datastax.driver.core.policies.Policies;
21+import com.datastax.driver.core.policies.ReconnectionPolicy;
22+import com.datastax.driver.core.utils.CassandraVersion;
2523 import com.google.common.base.Function;
2624 import com.google.common.collect.HashMultiset;
27-import com.google.common.collect.Iterables;
2825 import com.google.common.collect.Maps;
2926 import org.slf4j.Logger;
3027 import org.slf4j.LoggerFactory;
3128 import org.testng.annotations.Test;
3229
33-import static com.google.common.collect.Lists.newArrayList;
30+import java.net.InetAddress;
31+import java.util.Collection;
32+import java.util.Iterator;
33+import java.util.Map;
34+import java.util.concurrent.TimeUnit;
35+import java.util.concurrent.atomic.AtomicInteger;
3436
3537 import static com.datastax.driver.core.Assertions.assertThat;
3638 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3739 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
38-
39-import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy;
40-import com.datastax.driver.core.policies.LoadBalancingPolicy;
41-import com.datastax.driver.core.policies.Policies;
42-import com.datastax.driver.core.policies.ReconnectionPolicy;
43-import com.datastax.driver.core.utils.CassandraVersion;
40+import static com.google.common.collect.Lists.newArrayList;
4441
4542 public class ControlConnectionTest {
4643
@@ -75,10 +72,10 @@
7572 ccm = CCMBridge.builder("test").withNodes(2).build();
7673 // We pass only the first host as contact point, so we know the control connection will be on this host
7774 cluster = Cluster.builder()
78- .addContactPoint(CCMBridge.ipOfNode(1))
79- .withReconnectionPolicy(reconnectionPolicy)
80- .withLoadBalancingPolicy(loadBalancingPolicy)
81- .build();
75+ .addContactPoint(CCMBridge.ipOfNode(1))
76+ .withReconnectionPolicy(reconnectionPolicy)
77+ .withLoadBalancingPolicy(loadBalancingPolicy)
78+ .build();
8279 cluster.init();
8380
8481 // Kill the control connection host, there should be exactly one reconnection attempt
@@ -100,12 +97,12 @@
10097
10198 /**
10299 * Test for JAVA-509: UDT definitions were not properly parsed when using the default protocol version.
103- *
100+ * <p/>
104101 * This did not appear with other tests because the UDT needs to already exist when the driver initializes.
105102 * Therefore we use two different driver instances in this test.
106103 */
107104 @Test(groups = "short")
108- @CassandraVersion(major=2.1)
105+ @CassandraVersion(major = 2.1)
109106 public void should_parse_UDT_definitions_when_using_default_protocol_version() {
110107 CCMBridge ccm = null;
111108 Cluster cluster = null;
@@ -132,15 +129,15 @@
132129 ccm.remove();
133130 }
134131 }
135-
132+
136133 /**
137134 * Ensures that if the host that the Control Connection is connected to is removed/decommissioned that the
138135 * Control Connection is reestablished to another host.
139136 *
140- * @since 2.0.9
141137 * @jira_ticket JAVA-597
142138 * @expected_result Control Connection is reestablished to another host.
143139 * @test_category control_connection
140+ * @since 2.0.9
144141 */
145142 @Test(groups = "long")
146143 public void should_reestablish_if_control_node_decommissioned() throws InterruptedException {
@@ -184,7 +181,7 @@
184181 *
185182 * @jira_ticket JAVA-618
186183 * @expected_result All 5 hosts were chosen within 100 attempts. There is a very small possibility
187- * that this may not be the case and this is not actually an error.
184+ * that this may not be the case and this is not actually an error.
188185 * @test_category control_connection
189186 * @since 2.0.11, 2.1.8, 2.2.0
190187 */
@@ -197,15 +194,15 @@
197194
198195 try {
199196 Collection<String> contactPoints = newArrayList();
200- for(int i = 1; i <= hostCount; i++) {
197+ for (int i = 1; i <= hostCount; i++) {
201198 contactPoints.add(scassandras.address(i));
202199 }
203200 final HashMultiset<InetAddress> occurrencesByHost = HashMultiset.create(hostCount);
204- for(int i = 0; i < iterations; i++) {
201+ for (int i = 0; i < iterations; i++) {
205202 Cluster cluster = Cluster.builder()
206- .addContactPoints(contactPoints.toArray(new String[hostCount]))
207- .withNettyOptions(nonQuietClusterCloseOptions)
208- .build();
203+ .addContactPoints(contactPoints.toArray(new String[hostCount]))
204+ .withNettyOptions(nonQuietClusterCloseOptions)
205+ .build();
209206
210207 try {
211208 cluster.init();
@@ -214,7 +211,7 @@
214211 cluster.close();
215212 }
216213 }
217- if(logger.isDebugEnabled()) {
214+ if (logger.isDebugEnabled()) {
218215 Map<InetAddress, Integer> hostCounts = Maps.toMap(occurrencesByHost.elementSet(), new Function<InetAddress, Integer>() {
219216 @Override
220217 public Integer apply(InetAddress input) {
@@ -226,17 +223,17 @@
226223 // There is an incredibly low chance that a host may not be used based on randomness.
227224 // This probability is very low however.
228225 assertThat(occurrencesByHost.elementSet().size())
229- .as("Not all hosts were used as contact points. There is a very small chance"
230- + " of this happening based on randomness, investigate whether or not this"
231- + " is a bug.")
232- .isEqualTo(hostCount);
226+ .as("Not all hosts were used as contact points. There is a very small chance"
227+ + " of this happening based on randomness, investigate whether or not this"
228+ + " is a bug.")
229+ .isEqualTo(hostCount);
233230 } finally {
234231 scassandras.stop();
235232 }
236233
237234 }
238235
239- static class QueryPlanCountingPolicy extends DelegatingLoadBalancingPolicy {
236+ static class QueryPlanCountingPolicy extends DelegatingLoadBalancingPolicy {
240237
241238 final AtomicInteger counter = new AtomicInteger();
242239
modified driver-core/src/test/java/com/datastax/driver/core/CountingReconnectionPolicy.java +2 −2
@@ -15,10 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.atomic.AtomicInteger;
19-
2018 import com.datastax.driver.core.policies.ReconnectionPolicy;
2119
20+import java.util.concurrent.atomic.AtomicInteger;
21+
2222 /**
2323 * A reconnection policy that tracks how many times its schedule has been invoked.
2424 */
modified driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java +14 −13
@@ -15,13 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.Test;
19+
1820 import java.nio.ByteBuffer;
1921 import java.util.ArrayList;
2022 import java.util.Collection;
2123 import java.util.Collections;
2224 import java.util.List;
2325
24-import org.testng.annotations.Test;
2526 import static org.testng.Assert.assertEquals;
2627
2728 /**
@@ -32,12 +33,12 @@
3233 @Override
3334 protected Collection<String> getTableDefinitions() {
3435 return Collections.singleton(
35- "CREATE TABLE test ("
36- + " k int,"
37- + " c 'DynamicCompositeType(s => UTF8Type, i => Int32Type)',"
38- + " v int,"
39- + " PRIMARY KEY (k, c)"
40- + ") WITH COMPACT STORAGE"
36+ "CREATE TABLE test ("
37+ + " k int,"
38+ + " c 'DynamicCompositeType(s => UTF8Type, i => Int32Type)',"
39+ + " v int,"
40+ + " PRIMARY KEY (k, c)"
41+ + ") WITH COMPACT STORAGE"
4142 );
4243 }
4344
@@ -48,20 +49,20 @@
4849 for (Object p : params) {
4950 if (p instanceof Integer) {
5051 ByteBuffer elt = ByteBuffer.allocate(2 + 2 + 4 + 1);
51- elt.putShort((short)(0x8000 | 'i'));
52+ elt.putShort((short) (0x8000 | 'i'));
5253 elt.putShort((short) 4);
53- elt.putInt((Integer)p);
54- elt.put((byte)0);
54+ elt.putInt((Integer) p);
55+ elt.put((byte) 0);
5556 elt.flip();
5657 size += elt.remaining();
5758 l.add(elt);
5859 } else if (p instanceof String) {
59- ByteBuffer bytes = ByteBuffer.wrap(((String)p).getBytes());
60+ ByteBuffer bytes = ByteBuffer.wrap(((String) p).getBytes());
6061 ByteBuffer elt = ByteBuffer.allocate(2 + 2 + bytes.remaining() + 1);
61- elt.putShort((short)(0x8000 | 's'));
62+ elt.putShort((short) (0x8000 | 's'));
6263 elt.putShort((short) bytes.remaining());
6364 elt.put(bytes);
64- elt.put((byte)0);
65+ elt.put((byte) 0);
6566 elt.flip();
6667 size += elt.remaining();
6768 l.add(elt);
modified driver-core/src/test/java/com/datastax/driver/core/DataProviders.java +9 −9
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.Iterator;
20-
2118 import com.google.common.base.Predicate;
2219 import com.google.common.collect.Iterables;
2320 import org.testng.annotations.DataProvider;
2421
22+import java.util.Arrays;
23+import java.util.Iterator;
24+
2525 public class DataProviders {
2626
2727 /**
@@ -37,7 +37,7 @@
3737 }
3838 }).iterator();
3939
40- return new Iterator<Object[]> () {
40+ return new Iterator<Object[]>() {
4141
4242 @Override
4343 public boolean hasNext() {
@@ -46,8 +46,8 @@
4646
4747 @Override
4848 public Object[] next() {
49- return new Object[] {
50- consistencyLevels.next()
49+ return new Object[]{
50+ consistencyLevels.next()
5151 };
5252 }
5353
@@ -63,9 +63,9 @@
6363 */
6464 @DataProvider(name = "serialConsistencyLevels")
6565 public static Object[][] serialConsistencyLevels() {
66- return new Object[][] {
67- { ConsistencyLevel.SERIAL },
68- { ConsistencyLevel.LOCAL_SERIAL }
66+ return new Object[][]{
67+ {ConsistencyLevel.SERIAL},
68+ {ConsistencyLevel.LOCAL_SERIAL}
6969 };
7070 }
7171
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java +1 −1
@@ -32,7 +32,7 @@
3232
3333 public DataTypeAssert isUserType(String keyspaceName, String userTypeName) {
3434 assertThat(actual).isInstanceOf(UserType.class);
35- UserType userType = (UserType)this.actual;
35+ UserType userType = (UserType) this.actual;
3636 assertThat(userType.getKeyspace()).isEqualTo(keyspaceName);
3737 assertThat(userType.getTypeName()).isEqualTo(userTypeName);
3838 return this;
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +34 −36
@@ -15,22 +15,21 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-import java.util.concurrent.atomic.AtomicInteger;
20-
18+import com.datastax.driver.core.utils.CassandraVersion;
2119 import com.google.common.collect.*;
2220 import org.slf4j.Logger;
2321 import org.slf4j.LoggerFactory;
2422 import org.testng.annotations.Test;
2523
24+import java.util.*;
25+import java.util.concurrent.atomic.AtomicInteger;
26+
2627 import static org.assertj.core.api.Assertions.assertThat;
2728 import static org.assertj.core.api.Assertions.fail;
2829
29-import com.datastax.driver.core.utils.CassandraVersion;
30-
3130 /**
3231 * The goal of this test is to cover the serialization and deserialization of datatypes.
33- *
32+ * <p/>
3433 * It creates a table with a column of a given type, inserts a value and then tries to retrieve it.
3534 * There are 3 variants for the insert query: a raw string, a simple statement with a parameter
3635 * (protocol > v2 only) and a prepared statement.
@@ -53,7 +52,7 @@
5352 for (TestTable table : tables) {
5453 if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
5554 logger.debug("Skipping table because it uses a feature not supported by Cassandra {}: {}",
56- cassandraVersion, table.createStatement);
55+ cassandraVersion, table.createStatement);
5756 else
5857 statements.add(table.createStatement);
5958 }
@@ -103,12 +102,12 @@
103102 Object queriedValue = table.testColumnType.deserialize(row.getBytesUnsafe("v"), protocolVersion);
104103
105104 assertThat(queriedValue)
106- .as("Test failure on %s statement with table:%n%s;%n" +
107- "insert statement:%n%s;%n",
108- statementType,
109- table.createStatement,
110- table.insertStatement)
111- .isEqualTo(table.sampleValue);
105+ .as("Test failure on %s statement with table:%n%s;%n" +
106+ "insert statement:%n%s;%n",
107+ statementType,
108+ table.createStatement,
109+ table.insertStatement)
110+ .isEqualTo(table.sampleValue);
112111
113112 session.execute(table.truncateStatement);
114113 }
@@ -191,8 +190,8 @@
191190 Object valueSample = valueEntry.getValue();
192191
193192 tables.add(new TestTable(DataType.map(keyType, valueType),
194- ImmutableMap.builder().put(keySample, valueSample).build(),
195- "1.2.0"));
193+ ImmutableMap.builder().put(keySample, valueSample).build(),
194+ "1.2.0"));
196195 }
197196 }
198197 return tables;
@@ -206,10 +205,10 @@
206205
207206 // Types and samples for the inner collections like frozen<list<int>>
208207 Map<DataType, Object> childCollectionSamples = ImmutableMap.<DataType, Object>builder()
209- .put(DataType.frozenList(DataType.cint()), Lists.newArrayList(1, 1))
210- .put(DataType.frozenSet(DataType.cint()), Sets.newHashSet(1, 2))
211- .put(DataType.frozenMap(DataType.cint(), DataType.cint()), ImmutableMap.<Integer, Integer>builder().put(1, 2).put(3, 4).build())
212- .build();
208+ .put(DataType.frozenList(DataType.cint()), Lists.newArrayList(1, 1))
209+ .put(DataType.frozenSet(DataType.cint()), Sets.newHashSet(1, 2))
210+ .put(DataType.frozenMap(DataType.cint(), DataType.cint()), ImmutableMap.<Integer, Integer>builder().put(1, 2).put(3, 4).build())
211+ .build();
213212
214213 for (Map.Entry<DataType, Object> entry : childCollectionSamples.entrySet()) {
215214 DataType elementType = entry.getKey();
@@ -223,7 +222,7 @@
223222 Object valueSample = valueEntry.getValue();
224223
225224 tables.add(new TestTable(DataType.map(elementType, valueType),
226- ImmutableMap.builder().put(elementSample, valueSample).build(), "2.1.3"));
225+ ImmutableMap.builder().put(elementSample, valueSample).build(), "2.1.3"));
227226 }
228227 }
229228 return tables;
@@ -251,8 +250,8 @@
251250 DataType argument = type.getTypeArguments().get(typeIdx);
252251 boolean isAtBottom = !argument.isCollection();
253252
254- if(isAtBottom) {
255- switch(type.getName()) {
253+ if (isAtBottom) {
254+ switch (type.getName()) {
256255 case LIST:
257256 return Lists.newArrayList(1, 2, 3);
258257 case SET:
@@ -264,24 +263,23 @@
264263 map.put(5, 6);
265264 return map;
266265 }
267- }
268- else {
269- switch(type.getName()) {
266+ } else {
267+ switch (type.getName()) {
270268 case LIST:
271269 List<Object> l = Lists.newArrayListWithExpectedSize(2);
272- for(int i = 0; i < 5; i++) {
270+ for (int i = 0; i < 5; i++) {
273271 l.add(nestedObject(argument));
274272 }
275273 return l;
276274 case SET:
277275 Set<Object> s = Sets.newHashSet();
278- for(int i = 0; i < 5; i++) {
276+ for (int i = 0; i < 5; i++) {
279277 s.add(nestedObject(argument));
280278 }
281279 return s;
282280 case MAP:
283281 Map<Integer, Object> map = Maps.newHashMap();
284- for(int i = 0; i < 5; i++) {
282+ for (int i = 0; i < 5; i++) {
285283 map.put(i, nestedObject(argument));
286284 }
287285 return map;
@@ -292,7 +290,7 @@
292290
293291 /**
294292 * @param baseType The base type to use, one of SET, MAP, LIST.
295- * @param depth How many subcollections to generate.
293+ * @param depth How many subcollections to generate.
296294 * @return a DataType that is a nested collection with the given baseType with the
297295 * given depth.
298296 */
@@ -302,16 +300,16 @@
302300
303301 for (int i = 1; i <= depth; i++) {
304302 int chooser = r.nextInt(3);
305- if(t == null) {
306- if(chooser == 0) {
303+ if (t == null) {
304+ if (chooser == 0) {
307305 t = DataType.frozenList(DataType.cint());
308- } else if(chooser == 1) {
306+ } else if (chooser == 1) {
309307 t = DataType.frozenSet(DataType.cint());
310308 } else {
311309 t = DataType.frozenMap(DataType.cint(), DataType.cint());
312310 }
313- } else if(i == depth) {
314- switch(baseType) {
311+ } else if (i == depth) {
312+ switch (baseType) {
315313 case LIST:
316314 return DataType.list(t);
317315 case SET:
@@ -320,9 +318,9 @@
320318 return DataType.map(DataType.cint(), t);
321319 }
322320 } else {
323- if(chooser == 0) {
321+ if (chooser == 0) {
324322 t = DataType.frozenList(t);
325- } else if(chooser == 1) {
323+ } else if (chooser == 1) {
326324 t = DataType.frozenSet(t);
327325 } else {
328326 t = DataType.frozenMap(DataType.cint(), t);
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +65 −50
@@ -15,23 +15,21 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.datastax.driver.core.utils.Bytes;
20+import com.google.common.reflect.TypeToken;
21+import org.testng.annotations.Test;
22+
1823 import java.math.BigDecimal;
1924 import java.math.BigInteger;
2025 import java.net.InetAddress;
2126 import java.nio.ByteBuffer;
2227 import java.util.*;
2328
24-import com.google.common.reflect.TypeToken;
25-import org.testng.annotations.Test;
26-
29+import static com.datastax.driver.core.Assertions.assertThat;
2730 import static org.testng.Assert.assertEquals;
2831 import static org.testng.Assert.fail;
2932
30-import com.datastax.driver.core.exceptions.InvalidTypeException;
31-import com.datastax.driver.core.utils.Bytes;
32-
33-import static com.datastax.driver.core.Assertions.assertThat;
34-
3533 /**
3634 * DataType simple unit tests.
3735 */
@@ -46,30 +44,30 @@
4644 case ASCII:
4745 case TEXT:
4846 case VARCHAR:
49- return new String[]{ "'foo'", "'fo''o'" };
47+ return new String[]{"'foo'", "'fo''o'"};
5048 case BIGINT:
5149 case TIMESTAMP:
52- return new String[]{ "42", "91294377723", "-133" };
50+ return new String[]{"42", "91294377723", "-133"};
5351 case BLOB:
54- return new String[]{ "0x2450", "0x" };
52+ return new String[]{"0x2450", "0x"};
5553 case BOOLEAN:
56- return new String[]{ "true", "false" };
54+ return new String[]{"true", "false"};
5755 case DECIMAL:
58- return new String[]{ "1.23E+8" };
56+ return new String[]{"1.23E+8"};
5957 case DOUBLE:
60- return new String[]{ "2.39324324", "-12.0" };
58+ return new String[]{"2.39324324", "-12.0"};
6159 case FLOAT:
62- return new String[]{ "2.39", "-12.0" };
60+ return new String[]{"2.39", "-12.0"};
6361 case INET:
64- return new String[]{ "'128.2.12.3'" };
62+ return new String[]{"'128.2.12.3'"};
6563 case INT:
66- return new String[]{ "-2", "42" };
64+ return new String[]{"-2", "42"};
6765 case TIMEUUID:
68- return new String[]{ "fe2b4360-28c6-11e2-81c1-0800200c9a66" };
66+ return new String[]{"fe2b4360-28c6-11e2-81c1-0800200c9a66"};
6967 case UUID:
70- return new String[]{ "fe2b4360-28c6-11e2-81c1-0800200c9a66", "067e6162-3b6f-4ae2-a171-2470b63dff00" };
68+ return new String[]{"fe2b4360-28c6-11e2-81c1-0800200c9a66", "067e6162-3b6f-4ae2-a171-2470b63dff00"};
7169 case VARINT:
72- return new String[]{ "12387290982347987032483422342432" };
70+ return new String[]{"12387290982347987032483422342432"};
7371 default:
7472 throw new RuntimeException("Missing handling of " + dt);
7573 }
@@ -80,35 +78,35 @@
8078 case ASCII:
8179 case TEXT:
8280 case VARCHAR:
83- return new Object[]{ "foo", "fo'o" };
81+ return new Object[]{"foo", "fo'o"};
8482 case BIGINT:
85- return new Object[]{ 42L, 91294377723L, -133L };
83+ return new Object[]{42L, 91294377723L, -133L};
8684 case TIMESTAMP:
87- return new Object[]{ new Date(42L), new Date(91294377723L), new Date(-133L) };
85+ return new Object[]{new Date(42L), new Date(91294377723L), new Date(-133L)};
8886 case BLOB:
89- return new Object[]{ Bytes.fromHexString("0x2450"), ByteBuffer.allocate(0) };
87+ return new Object[]{Bytes.fromHexString("0x2450"), ByteBuffer.allocate(0)};
9088 case BOOLEAN:
91- return new Object[]{ true, false };
89+ return new Object[]{true, false};
9290 case DECIMAL:
93- return new Object[]{ new BigDecimal("1.23E+8") };
91+ return new Object[]{new BigDecimal("1.23E+8")};
9492 case DOUBLE:
95- return new Object[]{ 2.39324324, -12. };
93+ return new Object[]{2.39324324, -12.};
9694 case FLOAT:
97- return new Object[]{ 2.39f, -12.f };
95+ return new Object[]{2.39f, -12.f};
9896 case INET:
9997 try {
100- return new Object[]{ InetAddress.getByName("128.2.12.3") };
98+ return new Object[]{InetAddress.getByName("128.2.12.3")};
10199 } catch (java.net.UnknownHostException e) {
102100 throw new RuntimeException();
103101 }
104102 case INT:
105- return new Object[]{ -2, 42 };
103+ return new Object[]{-2, 42};
106104 case TIMEUUID:
107- return new Object[]{ UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66") };
105+ return new Object[]{UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66")};
108106 case UUID:
109- return new Object[]{ UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"), UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00") };
107+ return new Object[]{UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"), UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00")};
110108 case VARINT:
111- return new Object[]{ new BigInteger("12387290982347987032483422342432") };
109+ return new Object[]{new BigInteger("12387290982347987032483422342432")};
112110 default:
113111 throw new RuntimeException("Missing handling of " + dt);
114112 }
@@ -153,7 +151,11 @@
153151 @Test(groups = "unit")
154152 public void parseFormatSetTest() {
155153 String toParse = "{'Foo', 'Bar', 'Foo''bar'}";
156- Set<String> toFormat = new LinkedHashSet<String>(){{ add("Foo"); add("Bar"); add("Foo'bar"); }};
154+ Set<String> toFormat = new LinkedHashSet<String>() {{
155+ add("Foo");
156+ add("Bar");
157+ add("Foo'bar");
158+ }};
157159 DataType dt = DataType.set(DataType.text());
158160 assertEquals(dt.parse(toParse), toFormat);
159161 assertEquals(dt.format(toFormat), toParse);
@@ -163,7 +165,11 @@
163165 @Test(groups = "unit")
164166 public void parseFormatMapTest() {
165167 String toParse = "{'Foo':3, 'Bar':42, 'Foo''bar':-24}";
166- Map<String, Integer> toFormat = new LinkedHashMap<String, Integer>(){{ put("Foo", 3); put("Bar", 42); put("Foo'bar", -24); }};
168+ Map<String, Integer> toFormat = new LinkedHashMap<String, Integer>() {{
169+ put("Foo", 3);
170+ put("Bar", 42);
171+ put("Foo'bar", -24);
172+ }};
167173 DataType dt = DataType.map(DataType.text(), DataType.cint());
168174 assertEquals(dt.parse(toParse), toFormat);
169175 assertEquals(dt.format(toFormat), toParse);
@@ -177,17 +183,19 @@
177183
178184 final UserType udt1 = new UserType("ks", "t", Arrays.asList(new UserType.Field("a", DataType.blob())));
179185 UserType udt2 = new UserType("ks", "t", Arrays.asList(
180- new UserType.Field("t", DataType.text()),
181- new UserType.Field("i", DataType.cint()),
182- new UserType.Field("l", DataType.list(DataType.text())),
183- new UserType.Field("s", DataType.map(DataType.cint(), udt1))
186+ new UserType.Field("t", DataType.text()),
187+ new UserType.Field("i", DataType.cint()),
188+ new UserType.Field("l", DataType.list(DataType.text())),
189+ new UserType.Field("s", DataType.map(DataType.cint(), udt1))
184190 ));
185191
186192 UDTValue toFormat = udt2.newValue();
187193 toFormat.setString("t", "fo'o");
188194 toFormat.setInt("i", 3);
189195 toFormat.setList("l", Arrays.<String>asList("a", "b"));
190- toFormat.setMap("s", new HashMap<Integer, UDTValue>(){{ put(3, udt1.newValue().setBytes("a", ByteBuffer.wrap(new byte[]{1}))); }});
196+ toFormat.setMap("s", new HashMap<Integer, UDTValue>() {{
197+ put(3, udt1.newValue().setBytes("a", ByteBuffer.wrap(new byte[]{1})));
198+ }});
191199
192200 assertEquals(udt2.parse(toParse), toFormat);
193201 assertEquals(udt2.format(toFormat), toParse);
@@ -254,19 +262,26 @@
254262 @Test(groups = "unit")
255263 public void should_check_which_java_type_it_can_be_deserialized_to() {
256264 assertThat(DataType.cint())
257- .canBeDeserializedAs(TypeToken.of(Integer.class))
258- .canBeDeserializedAs(TypeToken.of(Number.class))
259- .cannotBeDeserializedAs(TypeToken.of(String.class));
265+ .canBeDeserializedAs(TypeToken.of(Integer.class))
266+ .canBeDeserializedAs(TypeToken.of(Number.class))
267+ .cannotBeDeserializedAs(TypeToken.of(String.class));
260268
261269 assertThat(DataType.list(DataType.cint()))
262- .canBeDeserializedAs(new TypeToken<List<Integer>>(){})
263- .canBeDeserializedAs(new TypeToken<Collection<Integer>>(){})
264- .cannotBeDeserializedAs(new TypeToken<Set<Integer>>(){})
265- .cannotBeDeserializedAs(new TypeToken<List<String>>(){});
270+ .canBeDeserializedAs(new TypeToken<List<Integer>>() {
271+ })
272+ .canBeDeserializedAs(new TypeToken<Collection<Integer>>() {
273+ })
274+ .cannotBeDeserializedAs(new TypeToken<Set<Integer>>() {
275+ })
276+ .cannotBeDeserializedAs(new TypeToken<List<String>>() {
277+ });
266278
267279 assertThat(DataType.map(DataType.cint(), DataType.frozenList(DataType.text())))
268- .canBeDeserializedAs(new TypeToken<Map<Integer, List<String>>>(){})
269- .canBeDeserializedAs(new TypeToken<Map<Number, Collection<String>>>(){})
270- .cannotBeDeserializedAs(new TypeToken<Map<Integer, Collection<Integer>>>(){});
280+ .canBeDeserializedAs(new TypeToken<Map<Integer, List<String>>>() {
281+ })
282+ .canBeDeserializedAs(new TypeToken<Map<Number, Collection<String>>>() {
283+ })
284+ .cannotBeDeserializedAs(new TypeToken<Map<Integer, Collection<Integer>>>() {
285+ });
271286 }
272287 }
modified driver-core/src/test/java/com/datastax/driver/core/EventDebouncerIntegrationTest.java +10 −11
@@ -15,18 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.Test;
19+
1820 import java.util.Collection;
1921 import java.util.concurrent.CountDownLatch;
2022 import java.util.concurrent.CyclicBarrier;
2123 import java.util.concurrent.TimeUnit;
2224
23-import org.testng.annotations.Test;
24-
25+import static com.datastax.driver.core.CCMBridge.ipOfNode;
2526 import static org.assertj.core.api.Assertions.assertThat;
2627 import static org.assertj.core.api.Fail.fail;
2728
28-import static com.datastax.driver.core.CCMBridge.ipOfNode;
29-
3029 public class EventDebouncerIntegrationTest {
3130
3231 /**
@@ -43,13 +42,13 @@
4342 TestLoadBalancingPolicy policy = new TestLoadBalancingPolicy();
4443 CCMBridge ccm = CCMBridge.builder("main").withNodes(3).build();
4544 final Cluster cluster = new Cluster.Builder()
46- .addContactPoints(ipOfNode(1))
47- .withLoadBalancingPolicy(policy)
48- .withQueryOptions(new QueryOptions()
49- .setRefreshNodeIntervalMillis(0)
50- .setRefreshNodeListIntervalMillis(0)
51- .setRefreshSchemaIntervalMillis(0)
52- ).build();
45+ .addContactPoints(ipOfNode(1))
46+ .withLoadBalancingPolicy(policy)
47+ .withQueryOptions(new QueryOptions()
48+ .setRefreshNodeIntervalMillis(0)
49+ .setRefreshNodeListIntervalMillis(0)
50+ .setRefreshSchemaIntervalMillis(0)
51+ ).build();
5352 try {
5453 new Thread() {
5554 @Override
modified driver-core/src/test/java/com/datastax/driver/core/EventDebouncerTest.java +12 −11
@@ -15,9 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.EventDebouncer.DeliveryCallback;
19+import com.google.common.util.concurrent.Futures;
20+import com.google.common.util.concurrent.ListenableFuture;
21+import org.testng.annotations.AfterMethod;
22+import org.testng.annotations.BeforeMethod;
23+import org.testng.annotations.Test;
24+
1825 import java.util.ArrayList;
1926 import java.util.List;
20-import java.util.concurrent.*;
27+import java.util.concurrent.CopyOnWriteArrayList;
28+import java.util.concurrent.CountDownLatch;
29+import java.util.concurrent.Executors;
30+import java.util.concurrent.ScheduledExecutorService;
2131 import java.util.concurrent.atomic.AtomicInteger;
2232 import java.util.concurrent.locks.Condition;
2333 import java.util.concurrent.locks.Lock;
@@ -25,17 +35,8 @@
2535
2636 import static java.util.concurrent.TimeUnit.MILLISECONDS;
2737 import static java.util.concurrent.TimeUnit.SECONDS;
28-
29-import com.google.common.util.concurrent.Futures;
30-import com.google.common.util.concurrent.ListenableFuture;
31-import org.testng.annotations.AfterMethod;
32-import org.testng.annotations.BeforeMethod;
33-import org.testng.annotations.Test;
34-
3538 import static org.assertj.core.api.Assertions.assertThat;
3639
37-import com.datastax.driver.core.EventDebouncer.DeliveryCallback;
38-
3940 public class EventDebouncerTest {
4041
4142 private ScheduledExecutorService executor;
@@ -240,7 +241,7 @@
240241 if (o == null || getClass() != o.getClass())
241242 return false;
242243
243- MockEvent mockEvent = (MockEvent)o;
244+ MockEvent mockEvent = (MockEvent) o;
244245
245246 return i == mockEvent.i;
246247
modified driver-core/src/test/java/com/datastax/driver/core/FakeHost.java +4 −3
@@ -63,14 +63,15 @@
6363 this.behavior = behavior;
6464 }
6565
66- @Override public void run() {
66+ @Override
67+ public void run() {
6768 ServerSocket server = null;
6869 Socket client = null;
6970 try {
7071 InetAddress bindAddress = InetAddress.getByName(address);
7172 int backlog = (behavior == Behavior.THROWING_CONNECT_TIMEOUTS)
72- ? 1
73- : -1; // default
73+ ? 1
74+ : -1; // default
7475 server = new ServerSocket(port, backlog, bindAddress);
7576
7677 if (behavior == Behavior.THROWING_CONNECT_TIMEOUTS) {
modified driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java +4 −4
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
19+import org.testng.annotations.Test;
20+
1821 import java.util.Collection;
1922 import java.util.Collections;
2023
21-import org.testng.annotations.Test;
2224 import static org.testng.Assert.*;
2325
24-import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
25-
2626 /**
2727 * Test ResultSet paging correct behavior.
2828 */
@@ -52,7 +52,7 @@
5252 for (int i = 0; i < 100; i++) {
5353 // isExhausted makes sure we do fetch if needed
5454 assertFalse(rs.isExhausted());
55- assertEquals(rs.getAvailableWithoutFetching(), 5-(i%5));
55+ assertEquals(rs.getAvailableWithoutFetching(), 5 - (i % 5));
5656 assertEquals(rs.one().getInt(0), i);
5757 }
5858
modified driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +12 −13
@@ -15,8 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import static java.util.concurrent.TimeUnit.SECONDS;
19-
2018 import org.apache.log4j.Level;
2119 import org.apache.log4j.Logger;
2220 import org.testng.annotations.AfterMethod;
@@ -24,6 +22,7 @@
2422 import org.testng.annotations.Test;
2523
2624 import static com.datastax.driver.core.Assertions.assertThat;
25+import static java.util.concurrent.TimeUnit.SECONDS;
2726
2827 public class HeartbeatTest {
2928
@@ -37,7 +36,7 @@
3736 connectionLogger.addAppender(logs);
3837 }
3938
40- @AfterMethod(groups="long")
39+ @AfterMethod(groups = "long")
4140 public void stopCapturingLogs() {
4241 connectionLogger.setLevel(null);
4342 connectionLogger.removeAppender(logs);
@@ -59,9 +58,9 @@
5958 try {
6059 ccm = CCMBridge.builder("test").withNodes(1).build();
6160 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1))
62- .withPoolingOptions(new PoolingOptions()
63- .setHeartbeatIntervalSeconds(3))
64- .build();
61+ .withPoolingOptions(new PoolingOptions()
62+ .setHeartbeatIntervalSeconds(3))
63+ .build();
6564
6665 // Don't create any session, only the control connection will be established
6766 cluster.init();
@@ -75,14 +74,14 @@
7574 // Ensure heartbeat is sent after no activity.
7675 SECONDS.sleep(4);
7776 assertThat(logs.getNext())
78- .contains("sending heartbeat")
79- .contains("heartbeat query succeeded");
77+ .contains("sending heartbeat")
78+ .contains("heartbeat query succeeded");
8079
8180 // Ensure heartbeat is sent after continued inactivity.
8281 SECONDS.sleep(4);
8382 assertThat(logs.getNext())
84- .contains("sending heartbeat")
85- .contains("heartbeat query succeeded");
83+ .contains("sending heartbeat")
84+ .contains("heartbeat query succeeded");
8685
8786 // Ensure heartbeat is not sent after activity.
8887 logs.getNext();
@@ -95,8 +94,8 @@
9594 // Finally, ensure heartbeat is sent after inactivity.
9695 SECONDS.sleep(4);
9796 assertThat(logs.getNext())
98- .contains("sending heartbeat")
99- .contains("heartbeat query succeeded");
97+ .contains("sending heartbeat")
98+ .contains("heartbeat query succeeded");
10099 } finally {
101100 if (cluster != null)
102101 cluster.close();
@@ -107,7 +106,7 @@
107106
108107 /**
109108 * Ensures that a heartbeat message is not sent if the configured heartbeat interval is 0.
110- *
109+ * <p/>
111110 * While difficult to prove the absence of evidence, the test will wait up to the default heartbeat interval
112111 * (30 seconds + 1) and check to see if the heartbeat was sent.
113112 *
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +8 −9
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.Host.State;
19+import com.datastax.driver.core.Host.StateListener;
20+import com.datastax.driver.core.policies.LoadBalancingPolicy;
21+import org.assertj.core.api.AbstractAssert;
22+
1823 import java.util.concurrent.CountDownLatch;
1924 import java.util.concurrent.TimeUnit;
20-import java.util.concurrent.atomic.AtomicBoolean;
2125
22-import static org.assertj.core.api.Assertions.fail;
23-import org.assertj.core.api.AbstractAssert;
2426 import static org.assertj.core.api.Assertions.assertThat;
25-
26-import com.datastax.driver.core.Host.State;
27-import com.datastax.driver.core.Host.StateListener;
28-import com.datastax.driver.core.policies.LoadBalancingPolicy;
27+import static org.assertj.core.api.Assertions.fail;
2928
3029 public class HostAssert extends AbstractAssert<HostAssert, Host> {
3130
@@ -63,7 +62,7 @@
6362
6463 public HostAssert isReconnectingFromDown() {
6564 assertThat(actual.getReconnectionAttemptFuture() != null && !actual.getReconnectionAttemptFuture().isDone())
66- .isTrue();
65+ .isTrue();
6766 return this;
6867 }
6968
@@ -74,7 +73,7 @@
7473
7574 public HostAssert isNotReconnectingFromDown() {
7675 assertThat(actual.getReconnectionAttemptFuture() != null && !actual.getReconnectionAttemptFuture().isDone())
77- .isFalse();
76+ .isFalse();
7877 return this;
7978 }
8079
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolMultiTest.java +8 −9
@@ -27,7 +27,6 @@
2727 import static com.datastax.driver.core.HostDistance.LOCAL;
2828 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
2929 import static java.util.concurrent.TimeUnit.SECONDS;
30-
3130 import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
3231
3332 public class HostConnectionPoolMultiTest {
@@ -36,15 +35,15 @@
3635
3736 private Cluster cluster;
3837
39- @BeforeMethod(groups={"short", "long"})
38+ @BeforeMethod(groups = {"short", "long"})
4039 private void setUp() {
4140 scassandra = ScassandraCluster.builder().withNodes(2).build();
4241 scassandra.init();
4342 }
4443
45- @AfterMethod(groups={"short", "long"})
44+ @AfterMethod(groups = {"short", "long"})
4645 private void tearDown() {
47- if(cluster != null) {
46+ if (cluster != null) {
4847 cluster.close();
4948 }
5049 scassandra.stop();
@@ -70,11 +69,11 @@
7069 * @test_category connection:connection_pool
7170 * @since 2.0.11
7271 */
73- @Test(groups="short")
72+ @Test(groups = "short")
7473 public void should_mark_host_down_if_all_connections_fail_on_init() {
7574 // Prevent any connections on node 2.
7675 scassandra.node(2).currentClient().disableListener();
77- createCluster(8,8);
76+ createCluster(8, 8);
7877
7978 // Node 2 should be in a down state while node 1 stays up.
8079 assertThat(cluster).host(2).goesDownWithin(10, SECONDS);
@@ -93,16 +92,16 @@
9392 * @test_category connection:connection_pool
9493 * @since 2.0.11
9594 */
96- @Test(groups="short")
95+ @Test(groups = "short")
9796 public void should_replace_control_connection_if_it_goes_down_but_host_remains_up() {
98- createCluster(1,2);
97+ createCluster(1, 2);
9998
10099 // Ensure control connection is on node 1.
101100 assertThat(cluster).usesControlHost(1);
102101
103102 // Identify the socket associated with the control connection.
104103 Connection controlConnection = cluster.manager.controlConnection.connectionRef.get();
105- InetSocketAddress controlSocket = (InetSocketAddress)controlConnection.channel.localAddress();
104+ InetSocketAddress controlSocket = (InetSocketAddress) controlConnection.channel.localAddress();
106105
107106 // Close the control connection.
108107 scassandra.node(1).currentClient()
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +81 −82
@@ -15,6 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.codahale.metrics.Gauge;
19+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
20+import com.google.common.util.concurrent.Uninterruptibles;
21+import org.scassandra.cql.PrimitiveType;
22+import org.scassandra.http.client.PrimingRequest;
23+import org.testng.annotations.BeforeClass;
24+import org.testng.annotations.Test;
25+
1826 import java.net.InetSocketAddress;
1927 import java.util.Iterator;
2028 import java.util.List;
@@ -22,30 +30,19 @@
2230 import java.util.concurrent.atomic.AtomicBoolean;
2331 import java.util.concurrent.atomic.AtomicReference;
2432
33+import static com.datastax.driver.core.Assertions.assertThat;
34+import static com.google.common.collect.Lists.newArrayList;
2535 import static java.util.Collections.singletonList;
2636 import static java.util.concurrent.TimeUnit.SECONDS;
27-
28-import com.codahale.metrics.Gauge;
29-import com.google.common.util.concurrent.Uninterruptibles;
30-import org.scassandra.cql.PrimitiveType;
31-import org.scassandra.http.client.PrimingRequest;
32-import org.testng.annotations.BeforeClass;
33-import org.testng.annotations.Test;
34-
35-import static com.google.common.collect.Lists.newArrayList;
3637 import static org.mockito.Mockito.*;
3738 import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
3839 import static org.scassandra.http.client.PrimingRequest.then;
3940 import static org.testng.Assert.fail;
4041
41-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
42-
43-import static com.datastax.driver.core.Assertions.assertThat;
44-
4542 public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
4643
4744
48- @BeforeClass(groups={"short", "long"})
45+ @BeforeClass(groups = {"short", "long"})
4946 public void reinitializeCluster() {
5047 // Don't use the provided cluster, each test will create its own instead.
5148 cluster.close();
@@ -72,10 +69,10 @@
7269 */
7370 private List<MockRequest> sendRequests(int count, HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
7471 List<MockRequest> requests = newArrayList();
75- for(int i = 0; i < count; i++) {
72+ for (int i = 0; i < count; i++) {
7673 MockRequest request = MockRequest.send(pool);
7774 requests.add(request);
78- if(expectedConnections != null)
75+ if (expectedConnections != null)
7976 assertThat(expectedConnections).contains(request.connection);
8077 }
8178 return requests;
@@ -94,8 +91,8 @@
9491 */
9592 private void completeRequests(int count, List<MockRequest> requests) {
9693 Iterator<MockRequest> requestIt = requests.iterator();
97- for(int i = 0; i < count; i++) {
98- if(requestIt.hasNext()) {
94+ for (int i = 0; i < count; i++) {
95+ if (requestIt.hasNext()) {
9996 MockRequest request = requestIt.next();
10097 request.simulateSuccessResponse();
10198 requestIt.remove();
@@ -109,7 +106,7 @@
109106 * Completes all requests by simulating a successful response.
110107 */
111108 private void completeRequests(List<MockRequest> requests) {
112- for(MockRequest request : requests) {
109+ for (MockRequest request : requests) {
113110 request.simulateSuccessResponse();
114111 }
115112 }
@@ -118,9 +115,9 @@
118115 * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
119116 * of creating a new connection.
120117 *
121- * @since 2.0.10, 2.1.6
122118 * @jira_ticket JAVA-419
123119 * @test_category connection:connection_pool
120+ * @since 2.0.10, 2.1.6
124121 */
125122 @Test(groups = "short")
126123 public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException, BusyConnectionException {
@@ -147,9 +144,9 @@
147144 * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
148145 * timeout instead of creating a new connection.
149146 *
150- * @since 2.0.10, 2.1.6
151147 * @jira_ticket JAVA-419
152148 * @test_category connection:connection_pool
149+ * @since 2.0.10, 2.1.6
153150 */
154151 @Test(groups = "short")
155152 public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception {
@@ -195,9 +192,9 @@
195192 /**
196193 * Ensures that if the core connection pool is full that borrowConnection will create and use a new connection.
197194 *
198- * @since 2.0.10, 2.1.6
199195 * @jira_ticket JAVA-419
200196 * @test_category connection:connection_pool
197+ * @since 2.0.10, 2.1.6
201198 */
202199 @Test(groups = "short")
203200 public void should_add_extra_connection_when_core_full() throws Exception {
@@ -225,9 +222,9 @@
225222 * Ensures that a trashed connection that has not been timed out should be resurrected into the connection pool if
226223 * borrowConnection is called and a new connection is needed.
227224 *
228- * @since 2.0.10, 2.1.6
229225 * @jira_ticket JAVA-419
230226 * @test_category connection:connection_pool
227+ * @since 2.0.10, 2.1.6
231228 */
232229 @Test(groups = "long")
233230 public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception {
@@ -285,9 +282,9 @@
285282 * Ensures that a trashed connection that has been timed out should not be resurrected into the connection pool if
286283 * borrowConnection is called and a new connection is needed.
287284 *
288- * @since 2.0.10, 2.1.6
289285 * @jira_ticket JAVA-419
290286 * @test_category connection:connection_pool
287+ * @since 2.0.10, 2.1.6
291288 */
292289 @Test(groups = "long")
293290 public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception {
@@ -339,8 +336,8 @@
339336 MockRequest request = MockRequest.send(pool);
340337 requests.add(request);
341338 assertThat(request.connection)
342- .isNotEqualTo(connection2) // should not be the full connection
343- .isNotEqualTo(connection1); // should not be the previously trashed one
339+ .isNotEqualTo(connection2) // should not be the full connection
340+ .isNotEqualTo(connection1); // should not be the previously trashed one
344341 } finally {
345342 completeRequests(requests);
346343 cluster.close();
@@ -350,9 +347,9 @@
350347 /**
351348 * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
352349 *
353- * @since 2.0.10, 2.1.6
354350 * @jira_ticket JAVA-419
355351 * @test_category connection:connection_pool
352+ * @since 2.0.10, 2.1.6
356353 */
357354 @Test(groups = "long")
358355 public void should_not_close_trashed_connection_until_no_in_flight() throws Exception {
@@ -402,9 +399,9 @@
402399 * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
403400 * the connection is put in the trash.
404401 *
405- * @since 2.0.10, 2.1.6
406402 * @jira_ticket JAVA-419
407403 * @test_category connection:connection_pool
404+ * @since 2.0.10, 2.1.6
408405 */
409406 @Test(groups = "short")
410407 public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception {
@@ -452,7 +449,7 @@
452449 * @test_category connection:connection_pool
453450 * @since 2.0.11
454451 */
455- @Test(groups="short")
452+ @Test(groups = "short")
456453 public void should_keep_host_up_when_one_connection_lost() throws Exception {
457454 Cluster cluster = createClusterBuilder().build();
458455 try {
@@ -462,7 +459,7 @@
462459
463460 // Drop a connection and ensure the host stays up.
464461 currentClient.disableListener();
465- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
462+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
466463 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
467464
468465 // connection 0 should be down, while connection 1 and the Host should remain up.
@@ -486,22 +483,22 @@
486483 * @test_category connection:connection_pool
487484 * @since 2.0.11
488485 */
489- @Test(groups="short")
486+ @Test(groups = "short")
490487 public void should_mark_host_down_when_no_connections_remaining() throws Exception {
491488 int readTimeout = 1000;
492489 int reconnectInterval = 1000;
493490 Cluster cluster = this.createClusterBuilder()
494- .withSocketOptions(new SocketOptions()
495- .setConnectTimeoutMillis(readTimeout)
496- .setReadTimeoutMillis(reconnectInterval))
497- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
491+ .withSocketOptions(new SocketOptions()
492+ .setConnectTimeoutMillis(readTimeout)
493+ .setReadTimeoutMillis(reconnectInterval))
494+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
498495 try {
499496 cluster.init();
500497
501498 Connection.Factory factory = spy(cluster.manager.connectionFactory);
502499 cluster.manager.connectionFactory = factory;
503500
504- HostConnectionPool pool = createPool(cluster, 8,8);
501+ HostConnectionPool pool = createPool(cluster, 8, 8);
505502 // copy list to track these connections.
506503 List<Connection> connections = newArrayList(pool.connections);
507504
@@ -516,13 +513,13 @@
516513 assertThat(cluster).hasClosedControlConnection();
517514
518515 // Ensure all connections are closed.
519- for(Connection connection : connections) {
516+ for (Connection connection : connections) {
520517 assertThat(connection.isClosed()).isTrue();
521518 }
522519
523520 // Expect a reconnect attempt on host after reconnect interval
524521 // on behalf of the control connection.
525- verify(factory, timeout(reconnectInterval*2).atLeastOnce()).open(host);
522+ verify(factory, timeout(reconnectInterval * 2).atLeastOnce()).open(host);
526523
527524 // Sleep for a bit to allow reconnect to fail.
528525 Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS);
@@ -536,9 +533,9 @@
536533 // Reconnect attempt should have been connected for control connection
537534 // and pool.
538535 // 2 attempts for connection.open (reconnect control connection and initial connection for host state).
539- verify(factory, after(reconnectInterval*2).atLeast(2)).open(host);
536+ verify(factory, after(reconnectInterval * 2).atLeast(2)).open(host);
540537 // 7 attempts for core connections after first initial connection.
541- verify(factory, timeout(reconnectInterval*2)).newConnections(any(HostConnectionPool.class), eq(7));
538+ verify(factory, timeout(reconnectInterval * 2)).newConnections(any(HostConnectionPool.class), eq(7));
542539
543540 // Wait some reasonable amount of time for connection to reestablish.
544541 Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
@@ -561,15 +558,15 @@
561558 * @test_category connection:connection_pool
562559 * @since 2.0.11
563560 */
564- @Test(groups="short")
561+ @Test(groups = "short")
565562 public void should_create_new_connections_when_connection_lost_and_under_core_connections() throws Exception {
566563 int readTimeout = 1000;
567564 int reconnectInterval = 1000;
568565 Cluster cluster = this.createClusterBuilder()
569- .withSocketOptions(new SocketOptions()
570- .setConnectTimeoutMillis(readTimeout)
571- .setReadTimeoutMillis(reconnectInterval))
572- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
566+ .withSocketOptions(new SocketOptions()
567+ .setConnectTimeoutMillis(readTimeout)
568+ .setReadTimeoutMillis(reconnectInterval))
569+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
573570 List<MockRequest> requests = newArrayList();
574571 try {
575572 cluster.init();
@@ -585,8 +582,8 @@
585582 // Drop two core connections.
586583 // Disable new connections initially and we'll eventually reenable it.
587584 currentClient.disableListener();
588- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
589- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core2.channel.localAddress()));
585+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
586+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core2.channel.localAddress()));
590587 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
591588
592589 // Since we have a connection left the host should remain up.
@@ -654,10 +651,10 @@
654651 int readTimeout = 1000;
655652 int reconnectInterval = 1000;
656653 Cluster cluster = this.createClusterBuilder()
657- .withSocketOptions(new SocketOptions()
658- .setConnectTimeoutMillis(readTimeout)
659- .setReadTimeoutMillis(reconnectInterval))
660- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
654+ .withSocketOptions(new SocketOptions()
655+ .setConnectTimeoutMillis(readTimeout)
656+ .setReadTimeoutMillis(reconnectInterval))
657+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
661658 List<MockRequest> requests = newArrayList();
662659 try {
663660 cluster.init();
@@ -687,12 +684,12 @@
687684 Connection extra1 = pool.connections.get(1);
688685
689686 // Drop a connection and disable listening.
690- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
687+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
691688 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
692689 currentClient.disableListener();
693690
694691 // Since core0 was closed, all of it's requests should have errored.
695- for(MockRequest request : core0requests) {
692+ for (MockRequest request : core0requests) {
696693 verify(request, times(1)).onException(any(Connection.class), any(Exception.class), anyLong(), anyInt());
697694 }
698695
@@ -752,15 +749,15 @@
752749 * @test_category connection:connection_pool
753750 * @since 2.0.11
754751 */
755- @Test(groups="short")
752+ @Test(groups = "short")
756753 public void should_not_mark_host_down_if_some_connections_fail_on_init() throws Exception {
757754 int readTimeout = 1000;
758755 int reconnectInterval = 1000;
759756 Cluster cluster = this.createClusterBuilder()
760- .withSocketOptions(new SocketOptions()
761- .setConnectTimeoutMillis(readTimeout)
762- .setReadTimeoutMillis(reconnectInterval))
763- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
757+ .withSocketOptions(new SocketOptions()
758+ .setConnectTimeoutMillis(readTimeout)
759+ .setReadTimeoutMillis(reconnectInterval))
760+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
764761 List<MockRequest> requests = newArrayList();
765762 try {
766763 cluster.init();
@@ -818,10 +815,10 @@
818815 int readTimeout = 1000;
819816 int reconnectInterval = 1000;
820817 Cluster cluster = this.createClusterBuilder()
821- .withSocketOptions(new SocketOptions()
822- .setConnectTimeoutMillis(readTimeout)
823- .setReadTimeoutMillis(reconnectInterval))
824- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
818+ .withSocketOptions(new SocketOptions()
819+ .setConnectTimeoutMillis(readTimeout)
820+ .setReadTimeoutMillis(reconnectInterval))
821+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
825822 try {
826823 // Init cluster so control connection is created.
827824 cluster.init();
@@ -859,15 +856,15 @@
859856 * @test_category connection:connection_pool
860857 * @since 2.0.11
861858 */
862- @Test(groups="short")
859+ @Test(groups = "short")
863860 public void should_wait_on_connection_if_not_convicted_and_no_connections_available() throws Exception {
864861 int readTimeout = 1000;
865862 int reconnectInterval = 1000;
866863 Cluster cluster = this.createClusterBuilder()
867- .withSocketOptions(new SocketOptions()
868- .setConnectTimeoutMillis(readTimeout)
869- .setReadTimeoutMillis(reconnectInterval))
870- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
864+ .withSocketOptions(new SocketOptions()
865+ .setConnectTimeoutMillis(readTimeout)
866+ .setReadTimeoutMillis(reconnectInterval))
867+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
871868 try {
872869 // Init cluster so control connection is created.
873870 cluster.init();
@@ -914,15 +911,15 @@
914911 * @test_category connection:connection_pool
915912 * @since 2.0.11
916913 */
917- @Test(groups="short")
914+ @Test(groups = "short")
918915 public void should_wait_on_connection_if_zero_core_connections() throws Exception {
919916 int readTimeout = 1000;
920917 int reconnectInterval = 1000;
921918 Cluster cluster = this.createClusterBuilder()
922- .withSocketOptions(new SocketOptions()
923- .setConnectTimeoutMillis(readTimeout)
924- .setReadTimeoutMillis(reconnectInterval))
925- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
919+ .withSocketOptions(new SocketOptions()
920+ .setConnectTimeoutMillis(readTimeout)
921+ .setReadTimeoutMillis(reconnectInterval))
922+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
926923 try {
927924 // Init cluster so control connection is created.
928925 cluster.init();
@@ -950,26 +947,26 @@
950947
951948 private HostConnectionPool createPool(Cluster cluster, int coreConnections, int maxConnections) {
952949 cluster.getConfiguration().getPoolingOptions()
953- .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections)
954- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections);
950+ .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections)
951+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections);
955952 Session session = cluster.connect();
956953 Host host = TestUtils.findHost(cluster, 1);
957954
958955 // Replace the existing pool with a spy pool and return it.
959- SessionManager sm = ((SessionManager)session);
956+ SessionManager sm = ((SessionManager) session);
960957 return sm.pools.get(host);
961958 }
962959
963960 /**
964- * <p>
961+ * <p/>
965962 * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
966963 * insertions are being executed, the number of opened connection is monitored.
967964 * <p/>
968965 * If at anytime, the number of opened connections is negative, this test will fail.
969966 *
970- * @since 2.0.6, 2.1.1
971967 * @jira_ticket JAVA-349
972968 * @test_category connection:connection_pool
969+ * @since 2.0.6, 2.1.1
973970 */
974971 @Test(groups = "long", enabled = false /* this test causes timeouts on Jenkins */)
975972 public void open_connections_metric_should_always_be_positive() throws InterruptedException {
@@ -1029,17 +1026,19 @@
10291026 sb.append(");");
10301027
10311028 PrimingRequest preparedStatementPrime = PrimingRequest.preparedStatementBuilder()
1032- .withQuery(sb.toString())
1033- .withThen(then().withVariableTypes(PrimitiveType.INT))
1034- .build();
1029+ .withQuery(sb.toString())
1030+ .withThen(then().withVariableTypes(PrimitiveType.INT))
1031+ .build();
10351032 primingClient.prime(preparedStatementPrime);
10361033 return sb.toString();
10371034 }
10381035
1039- /** Mock ResponseCallback that simulates the behavior of SpeculativeExecution (in terms of borrowing/releasing connections). */
1036+ /**
1037+ * Mock ResponseCallback that simulates the behavior of SpeculativeExecution (in terms of borrowing/releasing connections).
1038+ */
10401039 static class MockRequest implements Connection.ResponseCallback {
10411040
1042- enum State { START, COMPLETED, FAILED, TIMED_OUT }
1041+ enum State {START, COMPLETED, FAILED, TIMED_OUT}
10431042
10441043 final Connection connection;
10451044 private Connection.ResponseHandler responseHandler;
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataAssert.java +15 −16
@@ -15,11 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import static org.assertj.core.api.Assertions.assertThat;
19-
18+import com.datastax.driver.core.ColumnMetadata.IndexMetadata;
2019 import org.assertj.core.api.AbstractAssert;
2120
22-import com.datastax.driver.core.ColumnMetadata.IndexMetadata;
21+import static org.assertj.core.api.Assertions.assertThat;
2322
2423 public class IndexMetadataAssert extends AbstractAssert<IndexMetadataAssert, IndexMetadata> {
2524
@@ -31,55 +30,55 @@
3130 assertThat(actual.getName()).isEqualTo(name);
3231 return this;
3332 }
34-
33+
3534 public IndexMetadataAssert hasOption(String name, String value) {
3635 assertThat(actual.getOption(name)).isEqualTo(value);
3736 return this;
3837 }
39-
38+
4039 public IndexMetadataAssert asCqlQuery(String cqlQuery) {
4140 assertThat(actual.asCQLQuery()).isEqualTo(cqlQuery);
4241 return this;
4342 }
44-
45- public IndexMetadataAssert isKeys(){
43+
44+ public IndexMetadataAssert isKeys() {
4645 assertThat(actual.isKeys()).isTrue();
4746 return this;
4847 }
49-
50- public IndexMetadataAssert isNotKeys(){
48+
49+ public IndexMetadataAssert isNotKeys() {
5150 assertThat(actual.isKeys()).isFalse();
5251 return this;
5352 }
54-
53+
5554 public IndexMetadataAssert isFull() {
5655 assertThat(actual.isFull()).isTrue();
5756 return this;
5857 }
59-
58+
6059 public IndexMetadataAssert isNotFull() {
6160 assertThat(actual.isFull()).isFalse();
6261 return this;
6362 }
64-
63+
6564 public IndexMetadataAssert isEntries() {
6665 assertThat(actual.isEntries()).isTrue();
6766 return this;
6867 }
69-
68+
7069 public IndexMetadataAssert isNotEntries() {
7170 assertThat(actual.isEntries()).isFalse();
7271 return this;
7372 }
74-
73+
7574 public IndexMetadataAssert isCustomIndex() {
7675 assertThat(actual.isCustomIndex()).isTrue();
7776 return this;
7877 }
79-
78+
8079 public IndexMetadataAssert isNotCustomIndex() {
8180 assertThat(actual.isCustomIndex()).isFalse();
8281 return this;
8382 }
84-
83+
8584 }
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +96 −104
@@ -15,38 +15,30 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import static com.datastax.driver.core.Assertions.assertThat;
19-import static com.datastax.driver.core.ColumnMetadata.COLUMN_NAME;
20-import static com.datastax.driver.core.ColumnMetadata.COMPONENT_INDEX;
21-import static com.datastax.driver.core.ColumnMetadata.INDEX_NAME;
22-import static com.datastax.driver.core.ColumnMetadata.INDEX_OPTIONS;
23-import static com.datastax.driver.core.ColumnMetadata.INDEX_TYPE;
24-import static com.datastax.driver.core.ColumnMetadata.KIND;
25-import static com.datastax.driver.core.ColumnMetadata.VALIDATOR;
26-import static com.datastax.driver.core.DataType.cint;
27-import static com.datastax.driver.core.DataType.text;
18+import com.datastax.driver.core.ColumnMetadata.*;
19+import com.datastax.driver.core.Token.M3PToken;
20+import com.datastax.driver.core.utils.CassandraVersion;
21+import com.google.common.collect.ImmutableList;
22+import com.google.common.primitives.Ints;
23+import org.testng.annotations.Test;
2824
2925 import java.nio.ByteBuffer;
3026 import java.util.Collection;
3127 import java.util.List;
3228
33-import org.testng.annotations.Test;
34-
35-import com.datastax.driver.core.ColumnMetadata.IndexMetadata;
36-import com.datastax.driver.core.ColumnMetadata.Raw;
37-import com.datastax.driver.core.Token.M3PToken;
38-import com.datastax.driver.core.utils.CassandraVersion;
39-import com.google.common.collect.ImmutableList;
40-import com.google.common.primitives.Ints;
29+import static com.datastax.driver.core.Assertions.assertThat;
30+import static com.datastax.driver.core.ColumnMetadata.*;
31+import static com.datastax.driver.core.DataType.cint;
32+import static com.datastax.driver.core.DataType.text;
4133
4234 @CassandraVersion(
43- major = 1.2)
35+ major = 1.2)
4436 public class IndexMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
4537
4638 /**
4739 * Column definitions for schema_columns table.
4840 */
49- private static final ColumnDefinitions defs = new ColumnDefinitions(new ColumnDefinitions.Definition[] {
41+ private static final ColumnDefinitions defs = new ColumnDefinitions(new ColumnDefinitions.Definition[]{
5042 definition(COLUMN_NAME, text()),
5143 definition(COMPONENT_INDEX, cint()),
5244 definition(KIND, text()),
@@ -59,162 +51,162 @@
5951 @Override
6052 protected Collection<String> getTableDefinitions() {
6153 String createTable = "CREATE TABLE indexing ("
62- + "id int primary key,"
63- + "map_values map<text, int>,"
64- + "map_keys map<text, int>,"
65- + "map_entries map<text, int>,"
66- + "text_column text"
67- +
68- // Frozen collections was introduced only in C* 2.1.3
69- (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0
70- ?
71- ", map_full frozen<map<text, int>>,"
72- + "set_full frozen<set<text>>,"
73- + "list_full frozen<list<text>>);"
74- :
75- ")");
54+ + "id int primary key,"
55+ + "map_values map<text, int>,"
56+ + "map_keys map<text, int>,"
57+ + "map_entries map<text, int>,"
58+ + "text_column text"
59+ +
60+ // Frozen collections was introduced only in C* 2.1.3
61+ (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0
62+ ?
63+ ", map_full frozen<map<text, int>>,"
64+ + "set_full frozen<set<text>>,"
65+ + "list_full frozen<list<text>>);"
66+ :
67+ ")");
7668 return ImmutableList.of(createTable);
7769 }
78-
70+
7971 @Test(
80- groups = "short")
72+ groups = "short")
8173 public void should_not_flag_text_column_index_type() {
8274 String createValuesIndex = String.format("CREATE INDEX text_column_index ON %s.indexing (text_column);", keyspace);
8375 session.execute(createValuesIndex);
8476 IndexMetadata index = getIndexForColumn("text_column");
8577 assertThat(index).hasName("text_column_index")
86- .isNotKeys()
87- .isNotFull()
88- .isNotEntries()
89- .isNotCustomIndex()
90- .asCqlQuery(createValuesIndex);
78+ .isNotKeys()
79+ .isNotFull()
80+ .isNotEntries()
81+ .isNotCustomIndex()
82+ .asCqlQuery(createValuesIndex);
9183 }
9284
9385 @Test(
94- groups = "short")
86+ groups = "short")
9587 @CassandraVersion(
96- major = 2.1)
88+ major = 2.1)
9789 public void should_not_flag_map_index_type() {
9890 String createValuesIndex = String.format("CREATE INDEX map_values_index ON %s.indexing (map_values);", keyspace);
9991 session.execute(createValuesIndex);
10092 IndexMetadata index = getIndexForColumn("map_values");
10193 assertThat(index).hasName("map_values_index")
102- .isNotKeys()
103- .isNotFull()
104- .isNotEntries()
105- .isNotCustomIndex()
106- .asCqlQuery(createValuesIndex);
94+ .isNotKeys()
95+ .isNotFull()
96+ .isNotEntries()
97+ .isNotCustomIndex()
98+ .asCqlQuery(createValuesIndex);
10799 }
108100
109101 @Test(
110- groups = "short")
102+ groups = "short")
111103 @CassandraVersion(
112- major = 2.1)
104+ major = 2.1)
113105 public void should_flag_map_index_type_as_keys() {
114106 String createKeysIndex = String.format("CREATE INDEX map_keys_index ON %s.indexing (KEYS(map_keys));", keyspace);
115107 session.execute(createKeysIndex);
116108 IndexMetadata index = getIndexForColumn("map_keys");
117109 assertThat(index).hasName("map_keys_index")
118- .isKeys()
119- .isNotFull()
120- .isNotEntries()
121- .isNotCustomIndex()
122- .asCqlQuery(createKeysIndex);
110+ .isKeys()
111+ .isNotFull()
112+ .isNotEntries()
113+ .isNotCustomIndex()
114+ .asCqlQuery(createKeysIndex);
123115 }
124116
125117 @Test(
126- groups = "short")
118+ groups = "short")
127119 @CassandraVersion(
128- major = 2.1,
129- minor = 3)
120+ major = 2.1,
121+ minor = 3)
130122 public void should_flag_map_index_type_as_full() {
131123 String createFullIndex = String.format("CREATE INDEX map_full_index ON %s.indexing (FULL(map_full));", keyspace);
132124 session.execute(createFullIndex);
133125 IndexMetadata index = getIndexForColumn("map_full");
134126 assertThat(index).hasName("map_full_index")
135- .isNotKeys()
136- .isFull()
137- .isNotEntries()
138- .isNotCustomIndex()
139- .asCqlQuery(createFullIndex);
127+ .isNotKeys()
128+ .isFull()
129+ .isNotEntries()
130+ .isNotCustomIndex()
131+ .asCqlQuery(createFullIndex);
140132 }
141133
142134 @Test(
143- groups = "short")
135+ groups = "short")
144136 @CassandraVersion(
145- major = 2.1,
146- minor = 3)
137+ major = 2.1,
138+ minor = 3)
147139 public void should_flag_set_index_type_as_full() {
148140 String createFullIndex = String.format("CREATE INDEX set_full_index ON %s.indexing (FULL(set_full));", keyspace);
149141 session.execute(createFullIndex);
150142 IndexMetadata index = getIndexForColumn("set_full");
151143 assertThat(index).hasName("set_full_index")
152- .isNotKeys()
153- .isFull()
154- .isNotEntries()
155- .isNotCustomIndex()
156- .asCqlQuery(createFullIndex);
144+ .isNotKeys()
145+ .isFull()
146+ .isNotEntries()
147+ .isNotCustomIndex()
148+ .asCqlQuery(createFullIndex);
157149 }
158150
159151 @Test(
160- groups = "short")
152+ groups = "short")
161153 @CassandraVersion(
162- major = 2.1,
163- minor = 3)
154+ major = 2.1,
155+ minor = 3)
164156 public void should_flag_list_index_type_as_full() {
165157 String createFullIndex = String.format("CREATE INDEX list_full_index ON %s.indexing (FULL(list_full));", keyspace);
166158 session.execute(createFullIndex);
167159 IndexMetadata index = getIndexForColumn("list_full");
168160 assertThat(index).hasName("list_full_index")
169- .isNotKeys()
170- .isFull()
171- .isNotEntries()
172- .isNotCustomIndex()
173- .asCqlQuery(createFullIndex);
161+ .isNotKeys()
162+ .isFull()
163+ .isNotEntries()
164+ .isNotCustomIndex()
165+ .asCqlQuery(createFullIndex);
174166 }
175167
176168 @Test(
177- groups = "short")
169+ groups = "short")
178170 @CassandraVersion(
179- major = 3.0)
171+ major = 3.0)
180172 public void should_flag_map_index_type_as_entries() {
181173 String createEntriesIndex = String.format("CREATE INDEX map_entries_index ON %s.indexing (ENTRIES(map_entries));", keyspace);
182174 session.execute(createEntriesIndex);
183175 IndexMetadata index = getIndexForColumn("map_entries");
184176 assertThat(index).hasName("map_entries_index")
185- .isNotKeys()
186- .isNotFull()
187- .isEntries()
188- .isNotCustomIndex()
189- .asCqlQuery(createEntriesIndex);
177+ .isNotKeys()
178+ .isNotFull()
179+ .isEntries()
180+ .isNotCustomIndex()
181+ .asCqlQuery(createEntriesIndex);
190182 }
191183
192184 @Test(
193- groups = "short",
194- description = "This test case builds a ColumnMetadata object programatically to test custom indices,"
195- + "otherwise, it would require deploying an actual custom index class into the C* test cluster")
185+ groups = "short",
186+ description = "This test case builds a ColumnMetadata object programatically to test custom indices,"
187+ + "otherwise, it would require deploying an actual custom index class into the C* test cluster")
196188 public void should_parse_custom_index_options() {
197189 TableMetadata table = getTable("indexing");
198190 List<ByteBuffer> data = ImmutableList.of(
199- wrap("text_column"), // column name
200- wrap(0), // component index
201- wrap("regular"), // kind
202- wrap("custom_index"), // index name
203- wrap("CUSTOM"), // index type
204- wrap("org.apache.cassandra.db.marshal.UTF8Type"), // validator
205- wrap("{\"foo\" : \"bar\", \"class_name\" : \"dummy.DummyIndex\"}") // index options
206- );
191+ wrap("text_column"), // column name
192+ wrap(0), // component index
193+ wrap("regular"), // kind
194+ wrap("custom_index"), // index name
195+ wrap("CUSTOM"), // index type
196+ wrap("org.apache.cassandra.db.marshal.UTF8Type"), // validator
197+ wrap("{\"foo\" : \"bar\", \"class_name\" : \"dummy.DummyIndex\"}") // index options
198+ );
207199 Row row = ArrayBackedRow.fromData(defs, M3PToken.FACTORY, ProtocolVersion.V3, data);
208200 ColumnMetadata column = ColumnMetadata.fromRaw(table, Raw.fromRow(row, VersionNumber.parse("2.1")));
209201 IndexMetadata index = column.getIndex();
210202 assertThat(index).hasName("custom_index")
211- .isNotKeys()
212- .isNotFull()
213- .isNotEntries()
214- .isCustomIndex()
215- .hasOption("foo", "bar")
216- .asCqlQuery(String.format("CREATE CUSTOM INDEX custom_index ON %s.indexing (text_column) "
217- + "USING 'dummy.DummyIndex' WITH OPTIONS = {'foo' : 'bar', 'class_name' : 'dummy.DummyIndex'};", keyspace));
203+ .isNotKeys()
204+ .isNotFull()
205+ .isNotEntries()
206+ .isCustomIndex()
207+ .hasOption("foo", "bar")
208+ .asCqlQuery(String.format("CREATE CUSTOM INDEX custom_index ON %s.indexing (text_column) "
209+ + "USING 'dummy.DummyIndex' WITH OPTIONS = {'foo' : 'bar', 'class_name' : 'dummy.DummyIndex'};", keyspace));
218210 }
219211
220212 /**
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +31 −15
@@ -15,18 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-
20-import org.testng.annotations.Test;
21-import static org.testng.Assert.assertEquals;
22-import static org.testng.Assert.assertTrue;
23-
2418 import com.datastax.driver.core.querybuilder.Batch;
2519 import com.datastax.driver.core.querybuilder.Insert;
2620 import com.datastax.driver.core.utils.CassandraVersion;
21+import org.testng.annotations.Test;
22+
23+import java.nio.ByteBuffer;
2724
2825 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
2926 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
27+import static org.testng.Assert.assertEquals;
28+import static org.testng.Assert.assertTrue;
3029
3130 /**
3231 * Test limitations when using large amounts of data with the driver
@@ -179,10 +178,11 @@
179178
180179 /**
181180 * Test a wide row of size 1,000,000
181+ *
182182 * @throws Throwable
183183 */
184184 @Test(groups = "stress")
185- @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle reading wide rows well.")
185+ @CassandraVersion(major = 2.0, minor = 0, description = "< 2.0 is skipped as 1.2 does not handle reading wide rows well.")
186186 public void wideRows() throws Throwable {
187187 Cluster.Builder builder = Cluster.builder();
188188 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -203,10 +203,11 @@
203203
204204 /**
205205 * Test a batch that writes a row of size 10,000
206+ *
206207 * @throws Throwable
207208 */
208209 @Test(groups = "stress")
209- @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle large batches well.")
210+ @CassandraVersion(major = 2.0, minor = 0, description = "< 2.0 is skipped as 1.2 does not handle large batches well.")
210211 public void wideBatchRows() throws Throwable {
211212 Cluster.Builder builder = Cluster.builder();
212213 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -227,6 +228,7 @@
227228
228229 /**
229230 * Test a wide row of size 1,000,000 consisting of a ByteBuffer
231+ *
230232 * @throws Throwable
231233 */
232234 @Test(groups = "stress")
@@ -250,6 +252,7 @@
250252
251253 /**
252254 * Test a row with a single extra large text value
255+ *
253256 * @throws Throwable
254257 */
255258 @Test(groups = "stress")
@@ -273,6 +276,7 @@
273276
274277 /**
275278 * Creates a table with 330 columns
279+ *
276280 * @throws Throwable
277281 */
278282 @Test(groups = "stress")
@@ -305,6 +309,7 @@
305309
306310 /**
307311 * Tests 10 random tests consisting of the other methods in this class
312+ *
308313 * @throws Throwable
309314 */
310315 @Test(groups = "duration")
@@ -331,13 +336,24 @@
331336
332337 try {
333338 for (int i = 0; i < 10; ++i) {
334- switch ((int) (Math.random() * 5)){
335- case 0: testWideRows(c, 0); break;
336- case 1: testWideBatchRows(c, 0); break;
337- case 2: testByteRows(c, 0); break;
338- case 3: testLargeText(c, 0); break;
339- case 4: testWideTable(c, 0); break;
340- default: break;
339+ switch ((int) (Math.random() * 5)) {
340+ case 0:
341+ testWideRows(c, 0);
342+ break;
343+ case 1:
344+ testWideBatchRows(c, 0);
345+ break;
346+ case 2:
347+ testByteRows(c, 0);
348+ break;
349+ case 3:
350+ testLargeText(c, 0);
351+ break;
352+ case 4:
353+ testWideTable(c, 0);
354+ break;
355+ default:
356+ break;
341357 }
342358 }
343359 } catch (Throwable e) {
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java +21 −22
@@ -15,23 +15,21 @@
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.policies.DelegatingLoadBalancingPolicy;
19+import com.datastax.driver.core.policies.LoadBalancingPolicy;
20+import com.datastax.driver.core.policies.RoundRobinPolicy;
2121 import com.google.common.base.Objects;
2222 import com.google.common.collect.Lists;
2323 import org.slf4j.Logger;
2424 import org.slf4j.LoggerFactory;
2525 import org.testng.annotations.Test;
2626
27-import static org.assertj.core.api.Assertions.assertThat;
28-
29-import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy;
30-import com.datastax.driver.core.policies.LoadBalancingPolicy;
31-import com.datastax.driver.core.policies.RoundRobinPolicy;
27+import java.util.Collection;
28+import java.util.List;
3229
3330 import static com.datastax.driver.core.LoadBalancingPolicyBootstrapTest.HistoryPolicy.Action.*;
3431 import static com.datastax.driver.core.LoadBalancingPolicyBootstrapTest.HistoryPolicy.entry;
32+import static org.assertj.core.api.Assertions.assertThat;
3533
3634 public class LoadBalancingPolicyBootstrapTest {
3735
@@ -53,15 +51,15 @@
5351 try {
5452 ccm = CCMBridge.builder("test").withNodes(2).build();
5553 cluster = Cluster.builder()
56- .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
57- .withLoadBalancingPolicy(policy)
58- .build();
54+ .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
55+ .withLoadBalancingPolicy(policy)
56+ .build();
5957
6058 cluster.init();
6159
6260 assertThat(policy.history).containsOnly(
63- entry(INIT, TestUtils.findHost(cluster, 1)),
64- entry(INIT, TestUtils.findHost(cluster, 2))
61+ entry(INIT, TestUtils.findHost(cluster, 1)),
62+ entry(INIT, TestUtils.findHost(cluster, 2))
6563 );
6664 } finally {
6765 if (cluster != null)
@@ -104,23 +102,23 @@
104102
105103 HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy());
106104 cluster = Cluster.builder()
107- .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
108- .withLoadBalancingPolicy(policy)
109- .build();
105+ .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
106+ .withLoadBalancingPolicy(policy)
107+ .build();
110108
111109 cluster.init();
112110
113111 if (policy.history.contains(entry(DOWN, TestUtils.findHost(cluster, nodeToStop)))) {
114112 // This is the situation we're testing, the control connection tried the stopped node first.
115113 assertThat(policy.history).containsExactly(
116- entry(INIT, TestUtils.findHost(cluster, activeNode)),
117- entry(DOWN, TestUtils.findHost(cluster, nodeToStop))
114+ entry(INIT, TestUtils.findHost(cluster, activeNode)),
115+ entry(DOWN, TestUtils.findHost(cluster, nodeToStop))
118116 );
119117 break;
120118 } else {
121119 assertThat(policy.history).containsOnly(
122- entry(INIT, TestUtils.findHost(cluster, 1)),
123- entry(INIT, TestUtils.findHost(cluster, 2))
120+ entry(INIT, TestUtils.findHost(cluster, 1)),
121+ entry(INIT, TestUtils.findHost(cluster, 2))
124122 );
125123
126124 logger.info("Could not get first contact point to fail, retrying");
@@ -160,7 +158,7 @@
160158 if (other == this)
161159 return true;
162160 if (other instanceof Entry) {
163- Entry that = (Entry)other;
161+ Entry that = (Entry) other;
164162 return this.action == that.action && this.host.equals(that.host);
165163 }
166164 return false;
@@ -171,7 +169,8 @@
171169 return Objects.hashCode(action, host);
172170 }
173171
174- @Override public String toString() {
172+ @Override
173+ public String toString() {
175174 return Objects.toStringHelper(this).add("action", action).add("host", host).toString();
176175 }
177176 }
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyRefreshTest.java +19 −10
@@ -15,15 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.util.*;
20-
18+import com.datastax.driver.core.policies.LoadBalancingPolicy;
2119 import com.google.common.collect.Iterators;
2220 import org.testng.annotations.Test;
2321
24-import static org.testng.Assert.*;
22+import java.net.InetAddress;
23+import java.util.Collection;
24+import java.util.Iterator;
2525
26-import com.datastax.driver.core.policies.LoadBalancingPolicy;
26+import static org.testng.Assert.assertTrue;
2727
2828 // Test that PoolingOpions.refreshConnectedHosts works as expected (JAVA-309)
2929 public class LoadBalancingPolicyRefreshTest {
@@ -57,11 +57,20 @@
5757 return Iterators.<Host>singletonIterator(theHost);
5858 }
5959
60- public void onAdd(Host h) {}
61- public void onRemove(Host h) {}
62- public void onUp(Host h) {}
63- public void onDown(Host h) {}
64- public void onSuspected(Host h) {}
60+ public void onAdd(Host h) {
61+ }
62+
63+ public void onRemove(Host h) {
64+ }
65+
66+ public void onUp(Host h) {
67+ }
68+
69+ public void onDown(Host h) {
70+ }
71+
72+ public void onSuspected(Host h) {
73+ }
6574 }
6675
6776 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenFactoryTest.java +18 −19
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-
2018 import org.testng.annotations.Test;
2119
20+import java.util.List;
21+
2222 import static org.assertj.core.api.Assertions.assertThat;
23-import static org.testng.Assert.fail;
2423
2524 public class M3PTokenFactoryTest {
2625 Token.Factory factory = Token.M3PToken.FACTORY;
@@ -29,8 +28,8 @@
2928 public void should_split_range() {
3029 List<Token> splits = factory.split(factory.fromString("-9223372036854775808"), factory.fromString("4611686018427387904"), 3);
3130 assertThat(splits).containsExactly(
32- factory.fromString("-4611686018427387904"),
33- factory.fromString("0")
31+ factory.fromString("-4611686018427387904"),
32+ factory.fromString("0")
3433 );
3534 }
3635
@@ -38,8 +37,8 @@
3837 public void should_split_range_that_wraps_around_the_ring() {
3938 List<Token> splits = factory.split(factory.fromString("4611686018427387904"), factory.fromString("0"), 3);
4039 assertThat(splits).containsExactly(
41- factory.fromString("-9223372036854775807"),
42- factory.fromString("-4611686018427387903")
40+ factory.fromString("-9223372036854775807"),
41+ factory.fromString("-4611686018427387903")
4342 );
4443 }
4544
@@ -47,8 +46,8 @@
4746 public void should_split_range_when_division_not_integral() {
4847 List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("11"), 3);
4948 assertThat(splits).containsExactly(
50- factory.fromString("4"),
51- factory.fromString("8")
49+ factory.fromString("4"),
50+ factory.fromString("8")
5251 );
5352 }
5453
@@ -56,10 +55,10 @@
5655 public void should_split_range_producing_empty_splits() {
5756 List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("2"), 5);
5857 assertThat(splits).containsExactly(
59- factory.fromString("1"),
60- factory.fromString("2"),
61- factory.fromString("2"),
62- factory.fromString("2")
58+ factory.fromString("1"),
59+ factory.fromString("2"),
60+ factory.fromString("2"),
61+ factory.fromString("2")
6362 );
6463 }
6564
@@ -71,14 +70,14 @@
7170 // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring)
7271 List<Token> splits = factory.split(maxToken, minToken, 3);
7372 assertThat(splits).containsExactly(
74- maxToken,
75- maxToken
73+ maxToken,
74+ maxToken
7675 );
7776
7877 splits = factory.split(minToken, factory.fromString("-9223372036854775807"), 3);
7978 assertThat(splits).containsExactly(
80- factory.fromString("-9223372036854775807"),
81- factory.fromString("-9223372036854775807")
79+ factory.fromString("-9223372036854775807"),
80+ factory.fromString("-9223372036854775807")
8281 );
8382 }
8483
@@ -86,8 +85,8 @@
8685 public void should_split_whole_ring() {
8786 List<Token> splits = factory.split(factory.fromString("-9223372036854775808"), factory.fromString("-9223372036854775808"), 3);
8887 assertThat(splits).containsExactly(
89- factory.fromString("-3074457345618258603"),
90- factory.fromString("3074457345618258602")
88+ factory.fromString("-3074457345618258603"),
89+ factory.fromString("3074457345618258602")
9190 );
9291 }
9392
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenIntegrationTest.java +2 −1
@@ -22,7 +22,8 @@
2222 super("", DataType.bigint());
2323 }
2424
25- @Override protected Token.Factory tokenFactory() {
25+ @Override
26+ protected Token.Factory tokenFactory() {
2627 return M3PToken.FACTORY;
2728 }
2829 }
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenVnodeIntegrationTest.java +2 −1
@@ -20,7 +20,8 @@
2020 super("", DataType.bigint(), true);
2121 }
2222
23- @Override protected Token.Factory tokenFactory() {
23+ @Override
24+ protected Token.Factory tokenFactory() {
2425 return Token.M3PToken.FACTORY;
2526 }
2627 }
modified driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java +5 −6
@@ -15,21 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.apache.log4j.PatternLayout;
19+import org.apache.log4j.WriterAppender;
20+import org.apache.log4j.spi.LoggingEvent;
21+
1822 import java.io.StringWriter;
19-import java.util.concurrent.TimeoutException;
2023 import java.util.concurrent.locks.Condition;
2124 import java.util.concurrent.locks.Lock;
2225 import java.util.concurrent.locks.ReentrantLock;
2326
2427 import static java.util.concurrent.TimeUnit.MILLISECONDS;
2528
26-import org.apache.log4j.PatternLayout;
27-import org.apache.log4j.WriterAppender;
28-import org.apache.log4j.spi.LoggingEvent;
29-
3029 /**
3130 * Simple Log4J appender that captures logs to memory in order to inspect them in unit tests.
32- * <p>
31+ * <p/>
3332 * There is no purging mechanism, so make sure it doesn't stay enabled for too long (this is best
3433 * done with an {@code @After} method that removes it).
3534 */
modified driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +19 −19
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Map;
19-
2018 import com.google.common.collect.Maps;
2119 import org.testng.annotations.Test;
2220
21+import java.util.Map;
22+
2323 import static com.datastax.driver.core.Assertions.assertThat;
2424 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
2525 import static com.datastax.driver.core.TestUtils.waitFor;
@@ -30,18 +30,18 @@
3030 * <p>
3131 * Validates that when the topology of the cluster changes that Cluster Metadata is properly updated.
3232 * </p>
33- *
34- * <p>
33+ * <p/>
34+ * <p/>
3535 * This test does the following:
36- *
36+ * <p/>
3737 * <ol>
38- * <li>Creates a 3 node cluster and capture token range data from the {@link Cluster}'s {@link Metadata}</li>
39- * <li>Decommission node 3.</li>
40- * <li>Validates that the token range data was updated to reflect node 3 leaving and the other nodes
41- * taking on its token range.</li>
42- * <li>Adds a new node, node 4.</li>
43- * <li>Validates that the token range data was updated to reflect node 4 joining the {@link Cluster} and
44- * the token ranges reflecting this.</li>
38+ * <li>Creates a 3 node cluster and capture token range data from the {@link Cluster}'s {@link Metadata}</li>
39+ * <li>Decommission node 3.</li>
40+ * <li>Validates that the token range data was updated to reflect node 3 leaving and the other nodes
41+ * taking on its token range.</li>
42+ * <li>Adds a new node, node 4.</li>
43+ * <li>Validates that the token range data was updated to reflect node 4 joining the {@link Cluster} and
44+ * the token ranges reflecting this.</li>
4545 * </ol>
4646 *
4747 * @test_category metadata:token
@@ -49,7 +49,7 @@
4949 * @jira_ticket JAVA-312
5050 * @since 2.0.10, 2.1.5
5151 */
52- @Test(groups="long")
52+ @Test(groups = "long")
5353 public void should_update_metadata_on_topology_change() {
5454 CCMBridge ccm = null;
5555 Cluster cluster = null;
@@ -58,9 +58,9 @@
5858 ccm = CCMBridge.builder("test").withNodes(3).build();
5959
6060 cluster = Cluster.builder()
61- .addContactPoint(CCMBridge.ipOfNode(1))
62- .withQueryOptions(nonDebouncingQueryOptions())
63- .build();
61+ .addContactPoint(CCMBridge.ipOfNode(1))
62+ .withQueryOptions(nonDebouncingQueryOptions())
63+ .build();
6464 Session session = cluster.connect();
6565
6666 String keyspace = "test";
@@ -99,8 +99,8 @@
9999 TokenRange host4Range = metadata.getTokenRanges(keyspace, host4).iterator().next();
100100
101101 // Ensure no host token range intersects with node 4.
102- for(Host host : metadata.getAllHosts()) {
103- if(!host.equals(host4)) {
102+ for (Host host : metadata.getAllHosts()) {
103+ if (!host.equals(host4)) {
104104 TokenRange hostRange = metadata.getTokenRanges(keyspace, host).iterator().next();
105105 assertThat(host4Range).doesNotIntersect(hostRange);
106106 }
@@ -122,7 +122,7 @@
122122 */
123123 private Map<Host, Token> getTokenForHosts(Metadata metadata) {
124124 Map<Host, Token> tokensByHost = Maps.newHashMap();
125- for(Host host : metadata.getAllHosts()) {
125+ for (Host host : metadata.getAllHosts()) {
126126 tokensByHost.put(host, host.getTokens().iterator().next());
127127 }
128128 return tokensByHost;
modified driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +6 −7
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
18+import com.datastax.driver.core.Metrics.Errors;
19+import com.datastax.driver.core.policies.RetryPolicy;
20+import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
2021 import com.google.common.collect.Lists;
2122 import org.testng.annotations.Test;
2223
23-import static org.testng.Assert.assertEquals;
24+import java.util.Collection;
2425
25-import com.datastax.driver.core.Metrics.Errors;
26-import com.datastax.driver.core.policies.RetryPolicy;
27-import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
26+import static org.testng.Assert.assertEquals;
2827
2928 public class MetricsTest extends CCMBridge.PerClassSingleNodeCluster {
3029 private volatile RetryDecision retryDecision;
@@ -52,7 +51,7 @@
5251 @Override
5352 protected Collection<String> getTableDefinitions() {
5453 return Lists.newArrayList("CREATE TABLE test (k int primary key, v int)",
55- "INSERT INTO test (k, v) VALUES (1, 1)");
54+ "INSERT INTO test (k, v) VALUES (1, 1)");
5655 }
5756
5857 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +13 −14
@@ -15,21 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.net.InetSocketAddress;
20-
18+import com.datastax.driver.core.policies.Policies;
19+import com.datastax.driver.core.policies.WhiteListPolicy;
2120 import com.google.common.collect.Lists;
2221 import org.testng.annotations.Test;
2322
23+import java.net.InetAddress;
24+import java.net.InetSocketAddress;
25+
2426 import static org.testng.Assert.assertEquals;
2527 import static org.testng.Assert.assertNull;
2628
27-import com.datastax.driver.core.policies.Policies;
28-import com.datastax.driver.core.policies.WhiteListPolicy;
29-
3029 /**
3130 * Tests the behavior of the driver when some hosts have no rpc_address in the control host's system tables (JAVA-428).
32- *
31+ * <p/>
3332 * This can happen because of gossip bugs. We want to ignore these hosts because this is most likely indicative of an error state.
3433 */
3534 public class MissingRpcAddressTest {
@@ -43,8 +42,8 @@
4342 deleteNode2RpcAddressFromNode1();
4443 // Use only one contact point to make sure that the control connection is on node1
4544 cluster = Cluster.builder()
46- .addContactPoint(CCMBridge.IP_PREFIX + "1")
47- .build();
45+ .addContactPoint(CCMBridge.IP_PREFIX + "1")
46+ .build();
4847 cluster.connect();
4948
5049 // Since node2's RPC address is unknown on our control host, it should have been ignored
@@ -62,11 +61,11 @@
6261 Cluster cluster = null;
6362 try {
6463 cluster = Cluster.builder()
65- .addContactPoint(CCMBridge.IP_PREFIX + "1")
66- // ensure we will only connect to node1
67- .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
68- Lists.newArrayList(socketAddress(1))))
69- .build();
64+ .addContactPoint(CCMBridge.IP_PREFIX + "1")
65+ // ensure we will only connect to node1
66+ .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
67+ Lists.newArrayList(socketAddress(1))))
68+ .build();
7069 Session session = cluster.connect();
7170 String deleteStmt = String.format("DELETE rpc_address FROM system.peers WHERE peer = '%s'",
7271 InetAddress.getByName(CCMBridge.IP_PREFIX + "2").getHostName());
modified driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +10 −11
@@ -15,8 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.ThreadFactory;
19-
2018 import io.netty.bootstrap.Bootstrap;
2119 import io.netty.channel.ChannelHandler;
2220 import io.netty.channel.ChannelHandlerContext;
@@ -30,17 +28,18 @@
3028 import org.testng.annotations.DataProvider;
3129 import org.testng.annotations.Test;
3230
31+import java.util.concurrent.ThreadFactory;
32+
33+import static com.datastax.driver.core.CCMBridge.ipOfNode;
3334 import static org.mockito.Answers.CALLS_REAL_METHODS;
3435 import static org.mockito.Matchers.any;
3536 import static org.mockito.Mockito.*;
3637
37-import static com.datastax.driver.core.CCMBridge.ipOfNode;
38-
3938 public class NettyOptionsTest {
4039
4140 @DataProvider(name = "NettyOptionsTest")
4241 public static Object[][] parameters() {
43- Object[][] params = new Object[][] { {1,1}, {3,4} };
42+ Object[][] params = new Object[][]{{1, 1}, {3, 4}};
4443 return params;
4544 }
4645
@@ -65,12 +64,12 @@
6564 }
6665 }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
6766 cluster = Cluster.builder()
68- .addContactPoint(ipOfNode(1))
69- .withPoolingOptions(new PoolingOptions()
70- .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
71- )
72- .withNettyOptions(nettyOptions)
73- .build();
67+ .addContactPoint(ipOfNode(1))
68+ .withPoolingOptions(new PoolingOptions()
69+ .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
70+ )
71+ .withNettyOptions(nettyOptions)
72+ .build();
7473 // when
7574 cluster.connect();// force session creation to populate pools
7675
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +262 −262
@@ -15,11 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.util.List;
20-import java.util.Map;
21-import java.util.Set;
22-
2318 import com.google.common.collect.ImmutableList;
2419 import com.google.common.collect.ImmutableMap;
2520 import com.google.common.collect.ImmutableMap.Builder;
@@ -29,6 +24,11 @@
2924 import org.apache.log4j.Logger;
3025 import org.testng.annotations.Test;
3126
27+import java.net.InetSocketAddress;
28+import java.util.List;
29+import java.util.Map;
30+import java.util.Set;
31+
3232 import static org.assertj.core.api.Assertions.assertThat;
3333
3434 public class NetworkTopologyStrategyTest extends AbstractReplicationStrategyTest {
@@ -49,7 +49,7 @@
4949
5050 private static ReplicationStrategy networkTopologyStrategy(ReplicationFactorDefinition... rfs) {
5151 Builder<String, String> builder = ImmutableMap.<String, String>builder()
52- .put("class", "NetworkTopologyStrategy");
52+ .put("class", "NetworkTopologyStrategy");
5353
5454 for (ReplicationFactorDefinition rf : rfs)
5555 builder.put(rf.dc, String.valueOf(rf.replicationFactor));
@@ -124,46 +124,46 @@
124124 }
125125
126126 private static final List<Token> exampleRing = ImmutableList.<Token>builder()
127- .add(TOKEN01)
128- .add(TOKEN02)
129- .add(TOKEN03)
130- .add(TOKEN04)
131- .add(TOKEN05)
132- .add(TOKEN06)
133- .add(TOKEN07)
134- .add(TOKEN08)
135- .add(TOKEN09)
136- .add(TOKEN10)
137- .add(TOKEN11)
138- .add(TOKEN12)
139- .add(TOKEN13)
140- .add(TOKEN14)
141- .add(TOKEN15)
142- .add(TOKEN16)
143- .add(TOKEN17)
144- .add(TOKEN18)
145- .build();
127+ .add(TOKEN01)
128+ .add(TOKEN02)
129+ .add(TOKEN03)
130+ .add(TOKEN04)
131+ .add(TOKEN05)
132+ .add(TOKEN06)
133+ .add(TOKEN07)
134+ .add(TOKEN08)
135+ .add(TOKEN09)
136+ .add(TOKEN10)
137+ .add(TOKEN11)
138+ .add(TOKEN12)
139+ .add(TOKEN13)
140+ .add(TOKEN14)
141+ .add(TOKEN15)
142+ .add(TOKEN16)
143+ .add(TOKEN17)
144+ .add(TOKEN18)
145+ .build();
146146
147147 private static final Map<Token, Host> exampleTokenToPrimary = ImmutableMap.<Token, Host>builder()
148- .put(TOKEN01, host(IP1, DC1, RACK11))
149- .put(TOKEN02, host(IP1, DC1, RACK11))
150- .put(TOKEN03, host(IP5, DC1, RACK12))
151- .put(TOKEN04, host(IP3, DC1, RACK11))
152- .put(TOKEN05, host(IP1, DC1, RACK11))
153- .put(TOKEN06, host(IP5, DC1, RACK12))
154- .put(TOKEN07, host(IP2, DC2, RACK21))
155- .put(TOKEN08, host(IP6, DC2, RACK22))
156- .put(TOKEN09, host(IP3, DC1, RACK11))
157- .put(TOKEN10, host(IP4, DC2, RACK21))
158- .put(TOKEN11, host(IP5, DC1, RACK12))
159- .put(TOKEN12, host(IP4, DC2, RACK21))
160- .put(TOKEN13, host(IP4, DC2, RACK21))
161- .put(TOKEN14, host(IP2, DC2, RACK21))
162- .put(TOKEN15, host(IP6, DC2, RACK22))
163- .put(TOKEN16, host(IP3, DC1, RACK11))
164- .put(TOKEN17, host(IP2, DC2, RACK21))
165- .put(TOKEN18, host(IP6, DC2, RACK22))
166- .build();
148+ .put(TOKEN01, host(IP1, DC1, RACK11))
149+ .put(TOKEN02, host(IP1, DC1, RACK11))
150+ .put(TOKEN03, host(IP5, DC1, RACK12))
151+ .put(TOKEN04, host(IP3, DC1, RACK11))
152+ .put(TOKEN05, host(IP1, DC1, RACK11))
153+ .put(TOKEN06, host(IP5, DC1, RACK12))
154+ .put(TOKEN07, host(IP2, DC2, RACK21))
155+ .put(TOKEN08, host(IP6, DC2, RACK22))
156+ .put(TOKEN09, host(IP3, DC1, RACK11))
157+ .put(TOKEN10, host(IP4, DC2, RACK21))
158+ .put(TOKEN11, host(IP5, DC1, RACK12))
159+ .put(TOKEN12, host(IP4, DC2, RACK21))
160+ .put(TOKEN13, host(IP4, DC2, RACK21))
161+ .put(TOKEN14, host(IP2, DC2, RACK21))
162+ .put(TOKEN15, host(IP6, DC2, RACK22))
163+ .put(TOKEN16, host(IP3, DC1, RACK11))
164+ .put(TOKEN17, host(IP2, DC2, RACK21))
165+ .put(TOKEN18, host(IP6, DC2, RACK22))
166+ .build();
167167
168168 /*
169169 * --------------
@@ -174,18 +174,18 @@
174174 @Test(groups = "unit")
175175 public void networkTopologyWithSimpleDCLayoutTest1() {
176176 List<Token> ring = ImmutableList.<Token>builder()
177- .add(TOKEN01)
178- .add(TOKEN04)
179- .add(TOKEN14)
180- .add(TOKEN19)
181- .build();
177+ .add(TOKEN01)
178+ .add(TOKEN04)
179+ .add(TOKEN14)
180+ .add(TOKEN19)
181+ .build();
182182
183183 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
184- .put(TOKEN01, host(IP1, DC1, RACK11))
185- .put(TOKEN04, host(IP2, DC2, RACK21))
186- .put(TOKEN14, host(IP1, DC1, RACK11))
187- .put(TOKEN19, host(IP2, DC2, RACK21))
188- .build();
184+ .put(TOKEN01, host(IP1, DC1, RACK11))
185+ .put(TOKEN04, host(IP2, DC2, RACK21))
186+ .put(TOKEN14, host(IP1, DC1, RACK11))
187+ .put(TOKEN19, host(IP2, DC2, RACK21))
188+ .build();
189189
190190 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 1), rf(DC2, 1));
191191
@@ -200,26 +200,26 @@
200200 @Test(groups = "unit")
201201 public void networkTopologyWithSimpleDCLayoutTest2() {
202202 List<Token> ring = ImmutableList.<Token>builder()
203- .add(TOKEN01)
204- .add(TOKEN03)
205- .add(TOKEN05)
206- .add(TOKEN07)
207- .add(TOKEN13)
208- .add(TOKEN15)
209- .add(TOKEN17)
210- .add(TOKEN19)
211- .build();
203+ .add(TOKEN01)
204+ .add(TOKEN03)
205+ .add(TOKEN05)
206+ .add(TOKEN07)
207+ .add(TOKEN13)
208+ .add(TOKEN15)
209+ .add(TOKEN17)
210+ .add(TOKEN19)
211+ .build();
212212
213213 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
214- .put(TOKEN01, host(IP1, DC1, RACK11))
215- .put(TOKEN03, host(IP2, DC2, RACK21))
216- .put(TOKEN05, host(IP3, DC1, RACK11))
217- .put(TOKEN07, host(IP4, DC2, RACK21))
218- .put(TOKEN13, host(IP1, DC1, RACK11))
219- .put(TOKEN15, host(IP2, DC2, RACK21))
220- .put(TOKEN17, host(IP3, DC1, RACK11))
221- .put(TOKEN19, host(IP4, DC2, RACK21))
222- .build();
214+ .put(TOKEN01, host(IP1, DC1, RACK11))
215+ .put(TOKEN03, host(IP2, DC2, RACK21))
216+ .put(TOKEN05, host(IP3, DC1, RACK11))
217+ .put(TOKEN07, host(IP4, DC2, RACK21))
218+ .put(TOKEN13, host(IP1, DC1, RACK11))
219+ .put(TOKEN15, host(IP2, DC2, RACK21))
220+ .put(TOKEN17, host(IP3, DC1, RACK11))
221+ .put(TOKEN19, host(IP4, DC2, RACK21))
222+ .build();
223223
224224 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 1), rf(DC2, 1));
225225
@@ -238,22 +238,22 @@
238238 @Test(groups = "unit")
239239 public void networkTopologyWithSimple3DCLayoutTest() {
240240 List<Token> ring = ImmutableList.<Token>builder()
241- .add(TOKEN01)
242- .add(TOKEN05)
243- .add(TOKEN09)
244- .add(TOKEN11)
245- .add(TOKEN15)
246- .add(TOKEN19)
247- .build();
241+ .add(TOKEN01)
242+ .add(TOKEN05)
243+ .add(TOKEN09)
244+ .add(TOKEN11)
245+ .add(TOKEN15)
246+ .add(TOKEN19)
247+ .build();
248248
249249 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
250- .put(TOKEN01, host(IP1, DC1, RACK11))
251- .put(TOKEN05, host(IP2, DC2, RACK21))
252- .put(TOKEN09, host(IP3, DC3, RACK31))
253- .put(TOKEN11, host(IP1, DC1, RACK11))
254- .put(TOKEN15, host(IP2, DC2, RACK21))
255- .put(TOKEN19, host(IP3, DC3, RACK31))
256- .build();
250+ .put(TOKEN01, host(IP1, DC1, RACK11))
251+ .put(TOKEN05, host(IP2, DC2, RACK21))
252+ .put(TOKEN09, host(IP3, DC3, RACK31))
253+ .put(TOKEN11, host(IP1, DC1, RACK11))
254+ .put(TOKEN15, host(IP2, DC2, RACK21))
255+ .put(TOKEN19, host(IP3, DC3, RACK31))
256+ .build();
257257
258258 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 1), rf(DC2, 1), rf(DC3, 1));
259259
@@ -270,30 +270,30 @@
270270 @Test(groups = "unit")
271271 public void networkTopologyWithUnbalancedRingTest() {
272272 List<Token> ring = ImmutableList.<Token>builder()
273- .add(TOKEN01)
274- .add(TOKEN03)
275- .add(TOKEN05)
276- .add(TOKEN07)
277- .add(TOKEN09)
278- .add(TOKEN11)
279- .add(TOKEN13)
280- .add(TOKEN15)
281- .add(TOKEN17)
282- .add(TOKEN19)
283- .build();
273+ .add(TOKEN01)
274+ .add(TOKEN03)
275+ .add(TOKEN05)
276+ .add(TOKEN07)
277+ .add(TOKEN09)
278+ .add(TOKEN11)
279+ .add(TOKEN13)
280+ .add(TOKEN15)
281+ .add(TOKEN17)
282+ .add(TOKEN19)
283+ .build();
284284
285285 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
286- .put(TOKEN01, host(IP1, DC1, RACK11))
287- .put(TOKEN03, host(IP1, DC1, RACK11))
288- .put(TOKEN05, host(IP2, DC2, RACK21))
289- .put(TOKEN07, host(IP3, DC1, RACK11))
290- .put(TOKEN09, host(IP4, DC2, RACK21))
291- .put(TOKEN11, host(IP1, DC1, RACK11))
292- .put(TOKEN13, host(IP1, DC1, RACK11))
293- .put(TOKEN15, host(IP2, DC2, RACK21))
294- .put(TOKEN17, host(IP3, DC1, RACK11))
295- .put(TOKEN19, host(IP4, DC2, RACK21))
296- .build();
286+ .put(TOKEN01, host(IP1, DC1, RACK11))
287+ .put(TOKEN03, host(IP1, DC1, RACK11))
288+ .put(TOKEN05, host(IP2, DC2, RACK21))
289+ .put(TOKEN07, host(IP3, DC1, RACK11))
290+ .put(TOKEN09, host(IP4, DC2, RACK21))
291+ .put(TOKEN11, host(IP1, DC1, RACK11))
292+ .put(TOKEN13, host(IP1, DC1, RACK11))
293+ .put(TOKEN15, host(IP2, DC2, RACK21))
294+ .put(TOKEN17, host(IP3, DC1, RACK11))
295+ .put(TOKEN19, host(IP4, DC2, RACK21))
296+ .build();
297297
298298 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2));
299299
@@ -314,42 +314,42 @@
314314 @Test(groups = "unit")
315315 public void networkTopologyWithDCMultirackLayoutTest() {
316316 List<Token> ring = ImmutableList.<Token>builder()
317- .add(TOKEN01)
318- .add(TOKEN02)
319- .add(TOKEN03)
320- .add(TOKEN04)
321- .add(TOKEN05)
322- .add(TOKEN06)
323- .add(TOKEN07)
324- .add(TOKEN08)
325- .add(TOKEN12)
326- .add(TOKEN13)
327- .add(TOKEN14)
328- .add(TOKEN15)
329- .add(TOKEN16)
330- .add(TOKEN17)
331- .add(TOKEN18)
332- .add(TOKEN19)
333- .build();
317+ .add(TOKEN01)
318+ .add(TOKEN02)
319+ .add(TOKEN03)
320+ .add(TOKEN04)
321+ .add(TOKEN05)
322+ .add(TOKEN06)
323+ .add(TOKEN07)
324+ .add(TOKEN08)
325+ .add(TOKEN12)
326+ .add(TOKEN13)
327+ .add(TOKEN14)
328+ .add(TOKEN15)
329+ .add(TOKEN16)
330+ .add(TOKEN17)
331+ .add(TOKEN18)
332+ .add(TOKEN19)
333+ .build();
334334
335335 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
336- .put(TOKEN01, host(IP1, DC1, RACK11))
337- .put(TOKEN02, host(IP2, DC2, RACK21))
338- .put(TOKEN03, host(IP3, DC1, RACK12))
339- .put(TOKEN04, host(IP4, DC2, RACK22))
340- .put(TOKEN05, host(IP5, DC1, RACK11))
341- .put(TOKEN06, host(IP6, DC2, RACK21))
342- .put(TOKEN07, host(IP7, DC1, RACK12))
343- .put(TOKEN08, host(IP8, DC2, RACK22))
344- .put(TOKEN12, host(IP1, DC1, RACK11))
345- .put(TOKEN13, host(IP2, DC2, RACK21))
346- .put(TOKEN14, host(IP3, DC1, RACK12))
347- .put(TOKEN15, host(IP4, DC2, RACK22))
348- .put(TOKEN16, host(IP5, DC1, RACK11))
349- .put(TOKEN17, host(IP6, DC2, RACK21))
350- .put(TOKEN18, host(IP7, DC1, RACK12))
351- .put(TOKEN19, host(IP8, DC2, RACK22))
352- .build();
336+ .put(TOKEN01, host(IP1, DC1, RACK11))
337+ .put(TOKEN02, host(IP2, DC2, RACK21))
338+ .put(TOKEN03, host(IP3, DC1, RACK12))
339+ .put(TOKEN04, host(IP4, DC2, RACK22))
340+ .put(TOKEN05, host(IP5, DC1, RACK11))
341+ .put(TOKEN06, host(IP6, DC2, RACK21))
342+ .put(TOKEN07, host(IP7, DC1, RACK12))
343+ .put(TOKEN08, host(IP8, DC2, RACK22))
344+ .put(TOKEN12, host(IP1, DC1, RACK11))
345+ .put(TOKEN13, host(IP2, DC2, RACK21))
346+ .put(TOKEN14, host(IP3, DC1, RACK12))
347+ .put(TOKEN15, host(IP4, DC2, RACK22))
348+ .put(TOKEN16, host(IP5, DC1, RACK11))
349+ .put(TOKEN17, host(IP6, DC2, RACK21))
350+ .put(TOKEN18, host(IP7, DC1, RACK12))
351+ .put(TOKEN19, host(IP8, DC2, RACK22))
352+ .build();
353353
354354 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2));
355355
@@ -376,44 +376,44 @@
376376 @Test(groups = "unit")
377377 public void networkTopologyWithMultirackHostSkippingTest1() {
378378 List<Token> ring = ImmutableList.<Token>builder()
379- .add(TOKEN01)
380- .add(TOKEN02)
381- .add(TOKEN03)
382- .add(TOKEN04)
383- .add(TOKEN05)
384- .add(TOKEN06)
385- .add(TOKEN07)
386- .add(TOKEN08)
387- .add(TOKEN12)
388- .add(TOKEN13)
389- .add(TOKEN14)
390- .add(TOKEN15)
391- .add(TOKEN16)
392- .add(TOKEN17)
393- .add(TOKEN18)
394- .add(TOKEN19)
395- .build();
379+ .add(TOKEN01)
380+ .add(TOKEN02)
381+ .add(TOKEN03)
382+ .add(TOKEN04)
383+ .add(TOKEN05)
384+ .add(TOKEN06)
385+ .add(TOKEN07)
386+ .add(TOKEN08)
387+ .add(TOKEN12)
388+ .add(TOKEN13)
389+ .add(TOKEN14)
390+ .add(TOKEN15)
391+ .add(TOKEN16)
392+ .add(TOKEN17)
393+ .add(TOKEN18)
394+ .add(TOKEN19)
395+ .build();
396396
397397 //this is to simulate when we hit the same rack in a DC first as a second replica
398398 //so that'll get skipped and re-added later as a third
399399 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
400- .put(TOKEN01, host(IP1, DC1, RACK11))
401- .put(TOKEN02, host(IP2, DC2, RACK21))
402- .put(TOKEN03, host(IP3, DC1, RACK11))
403- .put(TOKEN04, host(IP4, DC2, RACK21))
404- .put(TOKEN05, host(IP5, DC1, RACK12))
405- .put(TOKEN06, host(IP6, DC2, RACK22))
406- .put(TOKEN07, host(IP7, DC1, RACK12))
407- .put(TOKEN08, host(IP8, DC2, RACK22))
408- .put(TOKEN12, host(IP1, DC1, RACK11))
409- .put(TOKEN13, host(IP2, DC2, RACK21))
410- .put(TOKEN14, host(IP3, DC1, RACK11))
411- .put(TOKEN15, host(IP4, DC2, RACK21))
412- .put(TOKEN16, host(IP5, DC1, RACK12))
413- .put(TOKEN17, host(IP6, DC2, RACK22))
414- .put(TOKEN18, host(IP7, DC1, RACK12))
415- .put(TOKEN19, host(IP8, DC2, RACK22))
416- .build();
400+ .put(TOKEN01, host(IP1, DC1, RACK11))
401+ .put(TOKEN02, host(IP2, DC2, RACK21))
402+ .put(TOKEN03, host(IP3, DC1, RACK11))
403+ .put(TOKEN04, host(IP4, DC2, RACK21))
404+ .put(TOKEN05, host(IP5, DC1, RACK12))
405+ .put(TOKEN06, host(IP6, DC2, RACK22))
406+ .put(TOKEN07, host(IP7, DC1, RACK12))
407+ .put(TOKEN08, host(IP8, DC2, RACK22))
408+ .put(TOKEN12, host(IP1, DC1, RACK11))
409+ .put(TOKEN13, host(IP2, DC2, RACK21))
410+ .put(TOKEN14, host(IP3, DC1, RACK11))
411+ .put(TOKEN15, host(IP4, DC2, RACK21))
412+ .put(TOKEN16, host(IP5, DC1, RACK12))
413+ .put(TOKEN17, host(IP6, DC2, RACK22))
414+ .put(TOKEN18, host(IP7, DC1, RACK12))
415+ .put(TOKEN19, host(IP8, DC2, RACK22))
416+ .build();
417417
418418 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 3), rf(DC2, 3));
419419
@@ -441,42 +441,42 @@
441441 @Test(groups = "unit")
442442 public void networkTopologyWithMultirackHostSkippingTest2() {
443443 List<Token> ring = ImmutableList.<Token>builder()
444- .add(TOKEN01)
445- .add(TOKEN02)
446- .add(TOKEN03)
447- .add(TOKEN04)
448- .add(TOKEN05)
449- .add(TOKEN06)
450- .add(TOKEN07)
451- .add(TOKEN08)
452- .add(TOKEN12)
453- .add(TOKEN13)
454- .add(TOKEN14)
455- .add(TOKEN15)
456- .add(TOKEN16)
457- .add(TOKEN17)
458- .add(TOKEN18)
459- .add(TOKEN19)
460- .build();
444+ .add(TOKEN01)
445+ .add(TOKEN02)
446+ .add(TOKEN03)
447+ .add(TOKEN04)
448+ .add(TOKEN05)
449+ .add(TOKEN06)
450+ .add(TOKEN07)
451+ .add(TOKEN08)
452+ .add(TOKEN12)
453+ .add(TOKEN13)
454+ .add(TOKEN14)
455+ .add(TOKEN15)
456+ .add(TOKEN16)
457+ .add(TOKEN17)
458+ .add(TOKEN18)
459+ .add(TOKEN19)
460+ .build();
461461
462462 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
463- .put(TOKEN01, host(IP1, DC1, RACK11))
464- .put(TOKEN02, host(IP1, DC1, RACK11))
465- .put(TOKEN03, host(IP3, DC1, RACK11))
466- .put(TOKEN04, host(IP3, DC1, RACK11))
467- .put(TOKEN05, host(IP5, DC1, RACK12))
468- .put(TOKEN06, host(IP5, DC1, RACK12))
469- .put(TOKEN07, host(IP7, DC1, RACK12))
470- .put(TOKEN08, host(IP7, DC1, RACK12))
471- .put(TOKEN12, host(IP2, DC2, RACK21))
472- .put(TOKEN13, host(IP2, DC2, RACK21))
473- .put(TOKEN14, host(IP4, DC2, RACK21))
474- .put(TOKEN15, host(IP4, DC2, RACK21))
475- .put(TOKEN16, host(IP6, DC2, RACK22))
476- .put(TOKEN17, host(IP6, DC2, RACK22))
477- .put(TOKEN18, host(IP8, DC2, RACK22))
478- .put(TOKEN19, host(IP8, DC2, RACK22))
479- .build();
463+ .put(TOKEN01, host(IP1, DC1, RACK11))
464+ .put(TOKEN02, host(IP1, DC1, RACK11))
465+ .put(TOKEN03, host(IP3, DC1, RACK11))
466+ .put(TOKEN04, host(IP3, DC1, RACK11))
467+ .put(TOKEN05, host(IP5, DC1, RACK12))
468+ .put(TOKEN06, host(IP5, DC1, RACK12))
469+ .put(TOKEN07, host(IP7, DC1, RACK12))
470+ .put(TOKEN08, host(IP7, DC1, RACK12))
471+ .put(TOKEN12, host(IP2, DC2, RACK21))
472+ .put(TOKEN13, host(IP2, DC2, RACK21))
473+ .put(TOKEN14, host(IP4, DC2, RACK21))
474+ .put(TOKEN15, host(IP4, DC2, RACK21))
475+ .put(TOKEN16, host(IP6, DC2, RACK22))
476+ .put(TOKEN17, host(IP6, DC2, RACK22))
477+ .put(TOKEN18, host(IP8, DC2, RACK22))
478+ .put(TOKEN19, host(IP8, DC2, RACK22))
479+ .build();
480480
481481 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 3), rf(DC2, 3));
482482
@@ -504,42 +504,42 @@
504504 public void networkTopologyWithMultirackHostSkippingTest3() {
505505 //this is the same topology as in the previous test, but with different rfs
506506 List<Token> ring = ImmutableList.<Token>builder()
507- .add(TOKEN01)
508- .add(TOKEN02)
509- .add(TOKEN03)
510- .add(TOKEN04)
511- .add(TOKEN05)
512- .add(TOKEN06)
513- .add(TOKEN07)
514- .add(TOKEN08)
515- .add(TOKEN12)
516- .add(TOKEN13)
517- .add(TOKEN14)
518- .add(TOKEN15)
519- .add(TOKEN16)
520- .add(TOKEN17)
521- .add(TOKEN18)
522- .add(TOKEN19)
523- .build();
507+ .add(TOKEN01)
508+ .add(TOKEN02)
509+ .add(TOKEN03)
510+ .add(TOKEN04)
511+ .add(TOKEN05)
512+ .add(TOKEN06)
513+ .add(TOKEN07)
514+ .add(TOKEN08)
515+ .add(TOKEN12)
516+ .add(TOKEN13)
517+ .add(TOKEN14)
518+ .add(TOKEN15)
519+ .add(TOKEN16)
520+ .add(TOKEN17)
521+ .add(TOKEN18)
522+ .add(TOKEN19)
523+ .build();
524524
525525 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
526- .put(TOKEN01, host(IP1, DC1, RACK11))
527- .put(TOKEN02, host(IP1, DC1, RACK11))
528- .put(TOKEN03, host(IP3, DC1, RACK11))
529- .put(TOKEN04, host(IP3, DC1, RACK11))
530- .put(TOKEN05, host(IP5, DC1, RACK12))
531- .put(TOKEN06, host(IP5, DC1, RACK12))
532- .put(TOKEN07, host(IP7, DC1, RACK12))
533- .put(TOKEN08, host(IP7, DC1, RACK12))
534- .put(TOKEN12, host(IP2, DC2, RACK21))
535- .put(TOKEN13, host(IP2, DC2, RACK21))
536- .put(TOKEN14, host(IP4, DC2, RACK21))
537- .put(TOKEN15, host(IP4, DC2, RACK21))
538- .put(TOKEN16, host(IP6, DC2, RACK22))
539- .put(TOKEN17, host(IP6, DC2, RACK22))
540- .put(TOKEN18, host(IP8, DC2, RACK22))
541- .put(TOKEN19, host(IP8, DC2, RACK22))
542- .build();
526+ .put(TOKEN01, host(IP1, DC1, RACK11))
527+ .put(TOKEN02, host(IP1, DC1, RACK11))
528+ .put(TOKEN03, host(IP3, DC1, RACK11))
529+ .put(TOKEN04, host(IP3, DC1, RACK11))
530+ .put(TOKEN05, host(IP5, DC1, RACK12))
531+ .put(TOKEN06, host(IP5, DC1, RACK12))
532+ .put(TOKEN07, host(IP7, DC1, RACK12))
533+ .put(TOKEN08, host(IP7, DC1, RACK12))
534+ .put(TOKEN12, host(IP2, DC2, RACK21))
535+ .put(TOKEN13, host(IP2, DC2, RACK21))
536+ .put(TOKEN14, host(IP4, DC2, RACK21))
537+ .put(TOKEN15, host(IP4, DC2, RACK21))
538+ .put(TOKEN16, host(IP6, DC2, RACK22))
539+ .put(TOKEN17, host(IP6, DC2, RACK22))
540+ .put(TOKEN18, host(IP8, DC2, RACK22))
541+ .put(TOKEN19, host(IP8, DC2, RACK22))
542+ .build();
543543
544544 //all nodes will contain all data, question is the replica order
545545 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 4), rf(DC2, 4));
@@ -592,24 +592,24 @@
592592 @Test(groups = "unit")
593593 public void networkTopologyStrategyNoNodesInDCTest() {
594594 long t1 = System.currentTimeMillis();
595- Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2))
595+ Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2))
596596 .computeTokenToReplicaMap(keyspace, largeRingTokenToPrimary, largeRing);
597597 assertThat(System.currentTimeMillis() - t1).isLessThan(10000);
598598
599599 InetSocketAddress currNode = null;
600600 InetSocketAddress nextNode;
601601 for (int node = 0; node < 99; node++) { // 100th wraps so doesn't match this, check after
602- if(currNode == null) {
602+ if (currNode == null) {
603603 currNode = socketAddress("127.0.0." + node);
604604 }
605- nextNode = socketAddress("127.0.0." + (node+1));
605+ nextNode = socketAddress("127.0.0." + (node + 1));
606606 for (int vnodes = 0; vnodes < 256; vnodes++) {
607607 Token token = token("" + ((node * 256) + vnodes));
608608 assertReplicaPlacement(replicaMap, token, currNode, nextNode);
609609 }
610610 currNode = nextNode;
611611 }
612- assertReplicaPlacement(replicaMap, token(""+ 99 * 256), currNode, socketAddress("127.0.0.0"));
612+ assertReplicaPlacement(replicaMap, token("" + 99 * 256), currNode, socketAddress("127.0.0.0"));
613613 }
614614
615615
@@ -645,30 +645,30 @@
645645 logger.addAppender(logs);
646646
647647 List<Token> ring = ImmutableList.<Token>builder()
648- .add(TOKEN01)
649- .add(TOKEN02)
650- .add(TOKEN03)
651- .add(TOKEN04)
652- .build();
648+ .add(TOKEN01)
649+ .add(TOKEN02)
650+ .add(TOKEN03)
651+ .add(TOKEN04)
652+ .build();
653653
654654 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
655- .put(TOKEN01, host(IP1, DC1, RACK11))
656- .put(TOKEN02, host(IP2, DC1, RACK12))
657- .put(TOKEN03, host(IP3, DC2, RACK21))
658- .put(TOKEN04, host(IP4, DC2, RACK22))
659- .build();
655+ .put(TOKEN01, host(IP1, DC1, RACK11))
656+ .put(TOKEN02, host(IP2, DC1, RACK12))
657+ .put(TOKEN03, host(IP3, DC2, RACK21))
658+ .put(TOKEN04, host(IP4, DC2, RACK22))
659+ .build();
660660
661661 // Wrong configuration: impossible replication factor for DC2
662662 networkTopologyStrategy(rf(DC1, 2), rf(DC2, 3))
663- .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
663+ .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
664664 assertThat(logs.getNext())
665- .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, DC2));
665+ .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, DC2));
666666
667667 // Wrong configuration: non-existing datacenter
668668 networkTopologyStrategy(rf(DC1, 2), rf("does_not_exist", 2))
669- .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
669+ .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
670670 assertThat(logs.getNext())
671- .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, "does_not_exist"));
671+ .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, "does_not_exist"));
672672
673673 logger.setLevel(null);
674674 logger.removeAppender(logs);
modified driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +12 −14
@@ -15,18 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
20-import org.testng.annotations.*;
18+import org.testng.annotations.AfterClass;
19+import org.testng.annotations.AfterMethod;
20+import org.testng.annotations.BeforeClass;
21+import org.testng.annotations.Test;
2122
22-import static com.google.common.collect.Lists.newArrayList;
23-import static org.mockito.Mockito.reset;
24-import static org.mockito.Mockito.spy;
25-import static org.mockito.Mockito.timeout;
26-import static org.mockito.Mockito.times;
27-import static org.mockito.Mockito.verify;
23+import java.util.Collection;
2824
2925 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
26+import static com.google.common.collect.Lists.newArrayList;
27+import static org.mockito.Mockito.*;
3028
3129 public class NodeListRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
3230
@@ -57,9 +55,9 @@
5755 queryOptions.setRefreshSchemaIntervalMillis(0);
5856 // Create a separate cluster that will receive the schema events on its control connection.
5957 cluster2 = this.configure(Cluster.builder())
60- .addContactPointsWithPorts(newArrayList(hostAddress))
61- .withQueryOptions(queryOptions)
62- .build();
58+ .addContactPointsWithPorts(newArrayList(hostAddress))
59+ .withQueryOptions(queryOptions)
60+ .build();
6361 session2 = cluster2.connect();
6462
6563 // Create a spy of the Cluster's control connection and replace it with the spy.
@@ -77,7 +75,7 @@
7775 public void teardown() {
7876 cluster2.close();
7977 // drop all keyspaces
80- for(String keyspace : keyspaces) {
78+ for (String keyspace : keyspaces) {
8179 session.execute("DROP KEYSPACE " + keyspace);
8280 }
8381 }
@@ -112,7 +110,7 @@
112110 // Create keyspaces 5 times to cause
113111 // refreshNodeListAndTokenMap to be called.
114112 String prefix = "srwmprr";
115- for(int i = 0; i < 5; i++) {
113+ for (int i = 0; i < 5; i++) {
116114 String keyspace = prefix + i;
117115 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
118116 keyspaces.add(keyspace);
modified driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java +10 −13
@@ -15,19 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.concurrent.TimeUnit;
20-
2118 import org.mockito.ArgumentCaptor;
2219 import org.testng.annotations.Test;
2320
24-import static com.google.common.collect.Lists.newArrayList;
25-import static org.mockito.ArgumentCaptor.forClass;
26-import static org.mockito.Mockito.mock;
27-import static org.mockito.Mockito.timeout;
28-import static org.mockito.Mockito.verify;
21+import java.util.Collection;
22+import java.util.concurrent.TimeUnit;
2923
3024 import static com.datastax.driver.core.Assertions.assertThat;
25+import static com.google.common.collect.Lists.newArrayList;
26+import static org.mockito.ArgumentCaptor.forClass;
27+import static org.mockito.Mockito.*;
3128
3229 public class NodeRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
3330
@@ -40,22 +37,22 @@
4037 * Ensures that when a new node is bootstrapped into the cluster, stopped, and then subsequently
4138 * started within {@link QueryOptions#setRefreshNodeIntervalMillis(int)} that an 'onAdd' event
4239 * event is the only one processed and that the {@link Host} is marked up.
43- * <p>
40+ * <p/>
4441 * Since NEW_NODE_DELAY_SECONDS is typically configured with a high value (60 seconds default
4542 * in the maven profile) this test can take a very long time.
4643 *
4744 * @jira_ticket JAVA-657
4845 * @since 2.0.11
4946 */
50- @Test(groups="long")
47+ @Test(groups = "long")
5148 public void should_call_onAdd_with_bootstrap_stop_start() {
5249 int refreshNodeInterval = 10000;
5350 QueryOptions queryOptions = new QueryOptions().setRefreshNodeIntervalMillis(refreshNodeInterval);
5451 CCMBridge ccm = CCMBridge.builder("test").withNodes(1).build();
5552 Cluster cluster = Cluster.builder()
56- .addContactPoint(CCMBridge.ipOfNode(1))
57- .withQueryOptions(queryOptions)
58- .build();
53+ .addContactPoint(CCMBridge.ipOfNode(1))
54+ .withQueryOptions(queryOptions)
55+ .build();
5956
6057 try {
6158 cluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenFactoryTest.java +17 −18
@@ -15,14 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.Test;
19+
1820 import java.math.BigInteger;
1921 import java.nio.ByteBuffer;
2022 import java.util.List;
2123
22-import org.testng.annotations.Test;
23-
2424 import static org.assertj.core.api.Assertions.assertThat;
25-import static org.testng.Assert.fail;
2625
2726 public class OPPTokenFactoryTest {
2827 private static final Token.Factory factory = Token.OPPToken.FACTORY;
@@ -33,52 +32,52 @@
3332 public void should_split_range() {
3433 List<Token> splits = factory.split(token('a'), token('d'), 3);
3534 assertThat(splits).containsExactly(
36- token('b'),
37- token('c')
35+ token('b'),
36+ token('c')
3837 );
3938 }
4039
4140 @Test(groups = "unit")
4241 public void should_split_range_producing_empty_splits_near_ring_end() {
4342 // the first token following min
44- ByteBuffer buffer = ByteBuffer.wrap(new byte[]{ 0 });
43+ ByteBuffer buffer = ByteBuffer.wrap(new byte[]{0});
4544 Token zero = token(buffer);
4645
4746 // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring)
4847 List<Token> splits = factory.split(minToken, zero, 3);
4948 assertThat(splits).containsExactly(
50- zero,
51- zero
49+ zero,
50+ zero
5251 );
5352 }
5453
5554 @Test(groups = "unit")
5655 public void should_strip_trailing_0_bytes() {
57- Token with0Bytes = token(ByteBuffer.wrap(new byte[]{ 4, 0, 0, 0 }));
58- Token without0Bytes = token(ByteBuffer.wrap(new byte[]{ 4 }));
56+ Token with0Bytes = token(ByteBuffer.wrap(new byte[]{4, 0, 0, 0}));
57+ Token without0Bytes = token(ByteBuffer.wrap(new byte[]{4}));
5958 Token fromStringWith0Bytes = factory.fromString("040000");
6059
6160 assertThat(with0Bytes)
62- .isEqualTo(without0Bytes)
63- .isEqualTo(fromStringWith0Bytes);
61+ .isEqualTo(without0Bytes)
62+ .isEqualTo(fromStringWith0Bytes);
6463
6564 Token withMixed0Bytes = factory.fromString("0004000400");
6665 Token withoutMixed0Bytes = factory.fromString("00040004");
6766
6867 assertThat(withMixed0Bytes)
69- .isEqualTo(withoutMixed0Bytes);
68+ .isEqualTo(withoutMixed0Bytes);
7069 }
7170
7271 @Test(groups = "unit")
7372 public void should_split_range_that_wraps_around_the_ring() {
74- for(int start = 1; start < 128; start++) {
75- for(int end = start; end < start; end++) {
73+ for (int start = 1; start < 128; start++) {
74+ for (int end = start; end < start; end++) {
7675 // Take the midpoint of the ring and offset by the midpoint of start+end.
7776 long expected = 0x81 + ((start + end) / 2);
7877 TokenRange tr = new TokenRange(token(start), token(end), factory);
7978 assertThat(factory.split(tr.getStart(), tr.getEnd(), 2))
80- .as("Expected 0x%X for start: %d, end: %d", expected, start, end)
81- .containsExactly(token(expected));
79+ .as("Expected 0x%X for start: %d, end: %d", expected, start, end)
80+ .containsExactly(token(expected));
8281 }
8382 }
8483 }
@@ -89,7 +88,7 @@
8988 }
9089
9190 private static Token token(char c) {
92- return new Token.OPPToken(ByteBuffer.wrap(new byte[]{ (byte)c }));
91+ return new Token.OPPToken(ByteBuffer.wrap(new byte[]{(byte) c}));
9392 }
9493
9594 private static Token token(long i) {
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java +2 −1
@@ -22,7 +22,8 @@
2222 super("-p ByteOrderedPartitioner", DataType.blob());
2323 }
2424
25- @Override protected Token.Factory tokenFactory() {
25+ @Override
26+ protected Token.Factory tokenFactory() {
2627 return OPPToken.FACTORY;
2728 }
2829 }
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java +2 −1
@@ -20,7 +20,8 @@
2020 super("-p ByteOrderedPartitioner", DataType.blob(), true);
2121 }
2222
23- @Override protected Token.Factory tokenFactory() {
23+ @Override
24+ protected Token.Factory tokenFactory() {
2425 return Token.OPPToken.FACTORY;
2526 }
2627 }
modified driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +17 −18
@@ -15,21 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.Collections;
20-import java.util.Iterator;
21-
18+import com.datastax.driver.core.exceptions.PagingStateException;
2219 import com.datastax.driver.core.utils.CassandraVersion;
2320 import org.slf4j.Logger;
2421 import org.slf4j.LoggerFactory;
2522 import org.testng.annotations.BeforeClass;
2623 import org.testng.annotations.Test;
2724
28-import static org.assertj.core.api.Assertions.assertThat;
25+import java.util.Collection;
26+import java.util.Collections;
27+import java.util.Iterator;
2928
30-import com.datastax.driver.core.exceptions.PagingStateException;
29+import static org.assertj.core.api.Assertions.assertThat;
3130
32-@CassandraVersion(major=2.0)
31+@CassandraVersion(major = 2.0)
3332 public class PagingStateTest extends CCMBridge.PerClassSingleNodeCluster {
3433 private static final Logger logger = LoggerFactory.getLogger(PagingStateTest.class);
3534 public static final String KEY = "paging_test";
@@ -51,7 +50,7 @@
5150 *
5251 * @test_category paging
5352 * @expected_result {@link ResultSet} from the query with the provided {@link PagingState} starts from the
54- * subsequent row from the first query.
53+ * subsequent row from the first query.
5554 */
5655 @Test(groups = "short")
5756 public void should_complete_when_using_paging_state() {
@@ -68,13 +67,13 @@
6867 }
6968
7069 /**
71- * <p>
70+ * <p/>
7271 * Validates that if the {@link PagingState} is altered in any way that it may not be reused.
7372 * The paging state is altered in the following ways:
74- *
73+ * <p/>
7574 * <ol>
76- * <li>Altering a byte in the paging state raw bytes.</li>
77- * <li>Setting the {@link PagingState} on a different Statement. (should fail hash validation)</li>
75+ * <li>Altering a byte in the paging state raw bytes.</li>
76+ * <li>Setting the {@link PagingState} on a different Statement. (should fail hash validation)</li>
7877 * </ol>
7978 *
8079 * @test_category paging
@@ -93,7 +92,7 @@
9392 String savedPagingStateString = savedPagingState.toString();
9493
9594 // corrupting the paging state
96- savedPagingStateBuffer[6] = (byte)42;
95+ savedPagingStateBuffer[6] = (byte) 42;
9796
9897 try {
9998 st.setFetchSize(20).setPagingState(PagingState.fromBytes(savedPagingStateBuffer));
@@ -123,10 +122,10 @@
123122 *
124123 * @test_category paging
125124 * @expected_result {@link ResultSet} from the query with the provided paging state starts from the subsequent row
126- * from the first query.
125+ * from the first query.
127126 */
128127 @Test(groups = "short")
129- @CassandraVersion(major=2.0)
128+ @CassandraVersion(major = 2.0)
130129 public void should_be_able_to_use_state_with_bound_statement() {
131130 PreparedStatement prepared = session.prepare("SELECT v from test where k=?");
132131 BoundStatement bs = prepared.bind(KEY);
@@ -149,7 +148,7 @@
149148 * @expected_result A failure is thrown when setting paging state on a different {@link BoundStatement}.
150149 */
151150 @Test(groups = "short", expectedExceptions = {PagingStateException.class})
152- @CassandraVersion(major=2.0)
151+ @CassandraVersion(major = 2.0)
153152 public void should_not_be_able_to_use_state_with_different_bound_statement() {
154153 PreparedStatement prepared = session.prepare("SELECT v from test where k=?");
155154 BoundStatement bs0 = prepared.bind(KEY);
@@ -196,7 +195,7 @@
196195 @Test(groups = "unit", expectedExceptions = {PagingStateException.class})
197196 public void should_fail_when_given_invalid_byte_array() {
198197 // Given an expected page state of size 1 and hash of size 1, we should expect 6 bytes, but only receive 5.
199- byte[] complete = { 0x00, 0x01, 0x00, 0x01, 0x00 };
198+ byte[] complete = {0x00, 0x01, 0x00, 0x01, 0x00};
200199 PagingState.fromBytes(complete);
201200 }
202201
@@ -214,7 +213,7 @@
214213 *
215214 * @test_category paging
216215 * @expected_result {@link ResultSet} from the query with the provided raw paging state starts from the
217- * subsequent row from the first query.
216+ * subsequent row from the first query.
218217 */
219218 @Test(groups = "short")
220219 public void should_complete_when_using_unsafe_paging_state() {
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java +7 −10
@@ -15,20 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.Test;
19+
1820 import java.util.Collection;
1921 import java.util.Collections;
2022 import java.util.concurrent.LinkedBlockingQueue;
2123 import java.util.concurrent.ThreadPoolExecutor;
2224 import java.util.concurrent.TimeUnit;
2325
24-import org.testng.annotations.Test;
25-
2626 import static org.assertj.core.api.Assertions.assertThat;
2727 import static org.mockito.Matchers.any;
28-import static org.mockito.Mockito.atLeastOnce;
29-import static org.mockito.Mockito.reset;
30-import static org.mockito.Mockito.spy;
31-import static org.mockito.Mockito.verify;
28+import static org.mockito.Mockito.*;
3229
3330 public class PoolingOptionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
3431 @Override
@@ -50,14 +47,14 @@
5047 @Test(groups = "short")
5148 public void should_be_able_to_use_custom_initialization_executor() {
5249 ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
53- new LinkedBlockingQueue<Runnable>()));
50+ new LinkedBlockingQueue<Runnable>()));
5451
5552 PoolingOptions poolingOptions = new PoolingOptions();
5653 poolingOptions.setInitializationExecutor(executor);
5754
5855 Cluster cluster = Cluster.builder()
59- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
60- .withPoolingOptions(poolingOptions).build();
56+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
57+ .withPoolingOptions(poolingOptions).build();
6158 try {
6259 cluster.init();
6360 // Ensure executor used.
@@ -73,7 +70,7 @@
7370
7471 // Expect core connections + control connection.
7572 assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
76- TestUtils.numberOfLocalCoreConnections(cluster) + 1);
73+ TestUtils.numberOfLocalCoreConnections(cluster) + 1);
7774
7875 reset();
7976
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +2 −3
@@ -17,11 +17,10 @@
1717
1818 import org.testng.annotations.Test;
1919
20-import static org.assertj.core.api.Assertions.assertThat;
21-import static org.assertj.core.api.Assertions.fail;
22-
2320 import static com.datastax.driver.core.HostDistance.LOCAL;
2421 import static com.datastax.driver.core.HostDistance.REMOTE;
22+import static org.assertj.core.api.Assertions.assertThat;
23+import static org.assertj.core.api.Assertions.fail;
2524
2625 public class PoolingOptionsTest {
2726
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +35 −34
@@ -15,27 +15,22 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.util.*;
20-
21-import com.google.common.collect.ImmutableList;
22-import org.testng.annotations.Test;
23-
24-import static org.assertj.core.api.Assertions.assertThat;
25-import static org.testng.Assert.assertEquals;
26-import static org.testng.Assert.assertFalse;
27-import static org.testng.Assert.assertTrue;
28-
2918 import com.datastax.driver.core.exceptions.InvalidQueryException;
30-import com.datastax.driver.core.exceptions.NoHostAvailableException;
3119 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
3220 import com.datastax.driver.core.utils.CassandraVersion;
21+import com.google.common.collect.ImmutableList;
22+import org.testng.annotations.Test;
23+
24+import java.net.InetAddress;
25+import java.util.*;
3326
3427 import static com.datastax.driver.core.TestUtils.*;
28+import static org.assertj.core.api.Assertions.assertThat;
29+import static org.testng.Assert.*;
3530
3631 /**
3732 * Prepared statement tests.
38- *
33+ * <p/>
3934 * Note: this class also happens to test all the get methods from Row.
4035 */
4136 public class PreparedStatementTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -165,7 +160,8 @@
165160
166161 String name = "c_list_" + rawType;
167162 DataType type = DataType.list(rawType);
168- List<Object> value = (List<Object>)getFixedValue(type);;
163+ List<Object> value = (List<Object>) getFixedValue(type);
164+ ;
169165 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
170166 BoundStatement bs = ps.bind();
171167 session.execute(setBoundValue(bs, name, type, value));
@@ -189,7 +185,8 @@
189185
190186 String name = "c_list_" + rawType;
191187 DataType type = DataType.list(rawType);
192- List<Object> value = (List<Object>)getFixedValue2(type);;
188+ List<Object> value = (List<Object>) getFixedValue2(type);
189+ ;
193190 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
194191 BoundStatement bs = ps.bind();
195192 session.execute(setBoundValue(bs, name, type, value));
@@ -210,7 +207,8 @@
210207
211208 String name = "c_set_" + rawType;
212209 DataType type = DataType.set(rawType);
213- Set<Object> value = (Set<Object>)getFixedValue(type);;
210+ Set<Object> value = (Set<Object>) getFixedValue(type);
211+ ;
214212 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
215213 BoundStatement bs = ps.bind();
216214 session.execute(setBoundValue(bs, name, type, value));
@@ -234,7 +232,8 @@
234232
235233 String name = "c_set_" + rawType;
236234 DataType type = DataType.set(rawType);
237- Set<Object> value = (Set<Object>)getFixedValue2(type);;
235+ Set<Object> value = (Set<Object>) getFixedValue2(type);
236+ ;
238237 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
239238 BoundStatement bs = ps.bind();
240239 session.execute(setBoundValue(bs, name, type, value));
@@ -260,7 +259,8 @@
260259
261260 String name = "c_map_" + rawKeyType + '_' + rawValueType;
262261 DataType type = DataType.map(rawKeyType, rawValueType);
263- Map<Object, Object> value = (Map<Object, Object>)getFixedValue(type);;
262+ Map<Object, Object> value = (Map<Object, Object>) getFixedValue(type);
263+ ;
264264 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
265265 BoundStatement bs = ps.bind();
266266 session.execute(setBoundValue(bs, name, type, value));
@@ -290,7 +290,8 @@
290290
291291 String name = "c_map_" + rawKeyType + '_' + rawValueType;
292292 DataType type = DataType.map(rawKeyType, rawValueType);
293- Map<Object, Object> value = (Map<Object, Object>)getFixedValue2(type);;
293+ Map<Object, Object> value = (Map<Object, Object>) getFixedValue2(type);
294+ ;
294295 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
295296 BoundStatement bs = ps.bind();
296297 session.execute(setBoundValue(bs, name, type, value));
@@ -343,7 +344,7 @@
343344 * Prints the table definitions that will be used in testing
344345 * (for exporting purposes)
345346 */
346- @Test(groups = { "docs" })
347+ @Test(groups = {"docs"})
347348 public void printTableDefinitions() {
348349 for (String definition : getTableDefinitions()) {
349350 System.out.println(definition);
@@ -381,7 +382,7 @@
381382 }
382383 }
383384
384- @Test(groups = "short", expectedExceptions = { IllegalStateException.class })
385+ @Test(groups = "short", expectedExceptions = {IllegalStateException.class})
385386 public void unboundVariableInBoundStatementTest() {
386387 PreparedStatement ps = session.prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
387388 BoundStatement bs = ps.bind("k");
@@ -389,8 +390,8 @@
389390 session.execute(bs);
390391 }
391392
392- @Test(groups = "short", expectedExceptions = { IllegalStateException.class })
393- @CassandraVersion(major=2.0)
393+ @Test(groups = "short", expectedExceptions = {IllegalStateException.class})
394+ @CassandraVersion(major = 2.0)
394395 public void unboundVariableInBatchStatementTest() {
395396 PreparedStatement ps = session.prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
396397 BatchStatement batch = new BatchStatement();
@@ -398,21 +399,21 @@
398399 session.execute(batch);
399400 }
400401
401- @Test(groups="short")
402+ @Test(groups = "short")
402403 public void should_set_routing_key_on_case_insensitive_keyspace_and_table() {
403- session.execute(String.format("CREATE TABLE %s.foo (i int PRIMARY KEY)",keyspace));
404+ session.execute(String.format("CREATE TABLE %s.foo (i int PRIMARY KEY)", keyspace));
404405
405- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)",keyspace));
406+ PreparedStatement ps = session.prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)", keyspace));
406407 BoundStatement bs = ps.bind(1);
407408 assertThat(bs.getRoutingKey()).isNotNull();
408409 }
409410
410- @Test(groups="short")
411+ @Test(groups = "short")
411412 public void should_set_routing_key_on_case_sensitive_keyspace_and_table() {
412413 session.execute("CREATE KEYSPACE \"Test\" WITH replication = { "
413- + " 'class': 'SimpleStrategy',"
414- + " 'replication_factor': '1'"
415- + "}");
414+ + " 'class': 'SimpleStrategy',"
415+ + " 'replication_factor': '1'"
416+ + "}");
416417 session.execute("CREATE TABLE \"Test\".\"Foo\" (i int PRIMARY KEY)");
417418
418419 PreparedStatement ps = session.prepare("INSERT INTO \"Test\".\"Foo\" (i) VALUES (?)");
@@ -420,11 +421,11 @@
420421 assertThat(bs.getRoutingKey()).isNotNull();
421422 }
422423
423- @Test(groups="short", expectedExceptions = InvalidQueryException.class)
424+ @Test(groups = "short", expectedExceptions = InvalidQueryException.class)
424425 public void should_fail_when_prepared_on_another_cluster() throws Exception {
425426 Cluster otherCluster = Cluster.builder()
426- .addContactPointsWithPorts(ImmutableList.of(hostAddress))
427- .build();
427+ .addContactPointsWithPorts(ImmutableList.of(hostAddress))
428+ .build();
428429 try {
429430 PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
430431 BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost"));
@@ -460,7 +461,7 @@
460461 assertThat(bound.isIdempotent()).isTrue();
461462
462463 statement.setIdempotent(false);
463- prepared = (IdempotenceAwarePreparedStatement)session.prepare(statement);
464+ prepared = (IdempotenceAwarePreparedStatement) session.prepare(statement);
464465 bound = prepared.bind(1);
465466
466467 assertThat(prepared.isIdempotent()).isFalse();
modified driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java +22 −23
@@ -15,6 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.Bytes;
19+import com.google.common.collect.ImmutableMap;
20+import com.google.common.collect.Lists;
21+
1822 import java.math.BigDecimal;
1923 import java.math.BigInteger;
2024 import java.net.InetAddress;
@@ -24,16 +28,11 @@
2428 import java.util.Map;
2529 import java.util.UUID;
2630
27-import com.google.common.collect.ImmutableMap;
28-import com.google.common.collect.Lists;
29-
3031 import static org.assertj.core.api.Assertions.assertThat;
3132
32-import com.datastax.driver.core.utils.Bytes;
33-
3433 /**
3534 * This class provides sample values for each primitive data type.
36- *
35+ * <p/>
3736 * These values have no particular meaning, the goal is just to have an instance that can be used in automated tests.
3837 */
3938 public class PrimitiveTypeSamples {
@@ -43,28 +42,28 @@
4342 private static Map<DataType, Object> generateAll() {
4443 try {
4544 ImmutableMap<DataType, Object> result = ImmutableMap.<DataType, Object>builder()
46- .put(DataType.ascii(), "ascii")
47- .put(DataType.bigint(), Long.MAX_VALUE)
48- .put(DataType.blob(), Bytes.fromHexString("0xCAFE"))
49- .put(DataType.cboolean(), Boolean.TRUE)
50- .put(DataType.decimal(), new BigDecimal("12.3E+7"))
51- .put(DataType.cdouble(), Double.MAX_VALUE)
52- .put(DataType.cfloat(), Float.MAX_VALUE)
53- .put(DataType.inet(), InetAddress.getByName("123.123.123.123"))
54- .put(DataType.cint(), Integer.MAX_VALUE)
55- .put(DataType.text(), "text")
56- .put(DataType.timestamp(), new Date(872835240000L))
57- .put(DataType.timeuuid(), UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"))
58- .put(DataType.uuid(), UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"))
59- .put(DataType.varint(), new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000"))
60- .build();
45+ .put(DataType.ascii(), "ascii")
46+ .put(DataType.bigint(), Long.MAX_VALUE)
47+ .put(DataType.blob(), Bytes.fromHexString("0xCAFE"))
48+ .put(DataType.cboolean(), Boolean.TRUE)
49+ .put(DataType.decimal(), new BigDecimal("12.3E+7"))
50+ .put(DataType.cdouble(), Double.MAX_VALUE)
51+ .put(DataType.cfloat(), Float.MAX_VALUE)
52+ .put(DataType.inet(), InetAddress.getByName("123.123.123.123"))
53+ .put(DataType.cint(), Integer.MAX_VALUE)
54+ .put(DataType.text(), "text")
55+ .put(DataType.timestamp(), new Date(872835240000L))
56+ .put(DataType.timeuuid(), UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"))
57+ .put(DataType.uuid(), UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"))
58+ .put(DataType.varint(), new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000"))
59+ .build();
6160
6261 // Check that we cover all types (except counter)
6362 List<DataType> tmp = Lists.newArrayList(DataType.allPrimitiveTypes());
6463 tmp.removeAll(result.keySet());
6564 assertThat(tmp)
66- .as("new datatype not covered in test")
67- .containsOnly(DataType.counter());
65+ .as("new datatype not covered in test")
66+ .containsOnly(DataType.counter());
6867
6968 return result;
7069 } catch (UnknownHostException e) {
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +53 −55
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.*;
1819 import org.apache.log4j.Logger;
1920 import org.scassandra.http.client.PrimingRequest;
2021 import org.testng.annotations.AfterMethod;
@@ -22,6 +23,7 @@
2223 import org.testng.annotations.DataProvider;
2324 import org.testng.annotations.Test;
2425
26+import static com.datastax.driver.core.QueryLogger.builder;
2527 import static org.apache.log4j.Level.DEBUG;
2628 import static org.apache.log4j.Level.INFO;
2729 import static org.assertj.core.api.Assertions.assertThat;
@@ -30,10 +32,6 @@
3032 import static org.scassandra.http.client.PrimingRequest.queryBuilder;
3133 import static org.scassandra.http.client.PrimingRequest.then;
3234
33-import com.datastax.driver.core.exceptions.*;
34-
35-import static com.datastax.driver.core.QueryLogger.builder;
36-
3735 /**
3836 * Tests for {@link QueryLogger} using Scassandra.
3937 * Contains only tests for exceptions (client timeout, read timeout, unavailable...);
@@ -51,7 +49,7 @@
5149 private Session session = null;
5250 private QueryLogger queryLogger = null;
5351
54- @BeforeMethod(groups = { "short", "unit" })
52+ @BeforeMethod(groups = {"short", "unit"})
5553 public void setUp() {
5654 slow.setLevel(INFO);
5755 error.setLevel(INFO);
@@ -64,7 +62,7 @@
6462 session = cluster.connect();
6563 }
6664
67- @AfterMethod(groups = { "short", "unit" })
65+ @AfterMethod(groups = {"short", "unit"})
6866 public void tearDown() {
6967 slow.setLevel(null);
7068 error.setLevel(null);
@@ -73,7 +71,7 @@
7371
7472 queryLogger = null;
7573
76- if(cluster != null) {
74+ if (cluster != null) {
7775 cluster.close();
7876 }
7977 }
@@ -83,24 +81,24 @@
8381 // given
8482 slow.setLevel(DEBUG);
8583 queryLogger = builder(cluster)
86- .withConstantThreshold(10)
87- .build();
84+ .withConstantThreshold(10)
85+ .build();
8886 cluster.register(queryLogger);
8987 String query = "SELECT foo FROM bar";
9088 primingClient.prime(
91- queryBuilder()
92- .withQuery(query)
93- .withThen(then().withFixedDelay(100L))
94- .build()
89+ queryBuilder()
90+ .withQuery(query)
91+ .withThen(then().withFixedDelay(100L))
92+ .build()
9593 );
9694 // when
9795 session.execute(query);
9896 // then
9997 String line = slowAppender.waitAndGet(5000);
10098 assertThat(line)
101- .contains("Query too slow")
102- .contains(ip)
103- .contains(query);
99+ .contains("Query too slow")
100+ .contains(ip)
101+ .contains(query);
104102 }
105103
106104 @Test(groups = "short")
@@ -112,10 +110,10 @@
112110 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
113111 String query = "SELECT foo FROM bar";
114112 primingClient.prime(
115- queryBuilder()
116- .withQuery(query)
117- .withThen(then().withFixedDelay(100L))
118- .build()
113+ queryBuilder()
114+ .withQuery(query)
115+ .withThen(then().withFixedDelay(100L))
116+ .build()
119117 );
120118 // when
121119 try {
@@ -127,34 +125,34 @@
127125 // then
128126 String line = errorAppender.waitAndGet(5000);
129127 assertThat(line)
130- .contains("Query error")
131- .contains(ip)
132- .contains(Integer.toString(scassandra.getBinaryPort()))
133- .contains(query)
134- .contains(OperationTimedOutException.class.getName());
128+ .contains("Query error")
129+ .contains(ip)
130+ .contains(Integer.toString(scassandra.getBinaryPort()))
131+ .contains(query)
132+ .contains(OperationTimedOutException.class.getName());
135133 }
136134
137- @DataProvider(name="errors")
135+ @DataProvider(name = "errors")
138136 public static Object[][] createErrors() {
139- return new Object[][] {
140- { unavailable, NoHostAvailableException.class, UnavailableException.class },
141- { write_request_timeout, WriteTimeoutException.class, WriteTimeoutException.class },
142- { read_request_timeout, ReadTimeoutException.class, ReadTimeoutException.class },
143- { server_error, NoHostAvailableException.class, ServerError.class },
144- { protocol_error, ProtocolError.class, ProtocolError.class },
145- { bad_credentials, AuthenticationException.class, AuthenticationException.class },
146- { overloaded, NoHostAvailableException.class, OverloadedException.class },
147- { is_bootstrapping, NoHostAvailableException.class, BootstrappingException.class },
148- { truncate_error, TruncateException.class, TruncateException.class },
149- { syntax_error, SyntaxError.class, SyntaxError.class },
150- { invalid, InvalidQueryException.class, InvalidQueryException.class },
151- { config_error, InvalidConfigurationInQueryException.class, InvalidConfigurationInQueryException.class },
152- { already_exists, AlreadyExistsException.class, AlreadyExistsException.class },
153- { unprepared, DriverInternalError.class, UnpreparedException.class }
137+ return new Object[][]{
138+ {unavailable, NoHostAvailableException.class, UnavailableException.class},
139+ {write_request_timeout, WriteTimeoutException.class, WriteTimeoutException.class},
140+ {read_request_timeout, ReadTimeoutException.class, ReadTimeoutException.class},
141+ {server_error, NoHostAvailableException.class, ServerError.class},
142+ {protocol_error, ProtocolError.class, ProtocolError.class},
143+ {bad_credentials, AuthenticationException.class, AuthenticationException.class},
144+ {overloaded, NoHostAvailableException.class, OverloadedException.class},
145+ {is_bootstrapping, NoHostAvailableException.class, BootstrappingException.class},
146+ {truncate_error, TruncateException.class, TruncateException.class},
147+ {syntax_error, SyntaxError.class, SyntaxError.class},
148+ {invalid, InvalidQueryException.class, InvalidQueryException.class},
149+ {config_error, InvalidConfigurationInQueryException.class, InvalidConfigurationInQueryException.class},
150+ {already_exists, AlreadyExistsException.class, AlreadyExistsException.class},
151+ {unprepared, DriverInternalError.class, UnpreparedException.class}
154152 };
155153 }
156154
157- @Test(groups = "short", dataProvider="errors")
155+ @Test(groups = "short", dataProvider = "errors")
158156 public void should_log_exception_from_the_given_result(PrimingRequest.Result result, Class<? extends Exception> expectedException, Class<? extends Exception> loggedException) throws Exception {
159157 // given
160158 error.setLevel(DEBUG);
@@ -162,22 +160,22 @@
162160 cluster.register(queryLogger);
163161 String query = "SELECT foo FROM bar";
164162 primingClient.prime(
165- queryBuilder()
166- .withQuery(query)
167- .withThen(then().withResult(result))
168- .build()
163+ queryBuilder()
164+ .withQuery(query)
165+ .withThen(then().withResult(result))
166+ .build()
169167 );
170168 // when
171169 try {
172170 session.execute(query);
173171 fail("Should have thrown NoHostAvailableException");
174- } catch(Exception e) {
175- if(e instanceof NoHostAvailableException) {
172+ } catch (Exception e) {
173+ if (e instanceof NoHostAvailableException) {
176174 assertThat(expectedException).isEqualTo(NoHostAvailableException.class);
177175 // ok
178- Throwable error = ((NoHostAvailableException)e).getErrors().get(hostAddress);
176+ Throwable error = ((NoHostAvailableException) e).getErrors().get(hostAddress);
179177 assertThat(error).isNotNull();
180- if(loggedException.getSuperclass() == DriverInternalError.class) {
178+ if (loggedException.getSuperclass() == DriverInternalError.class) {
181179 assertThat(error).isOfAnyClassIn(DriverException.class);
182180 } else {
183181 assertThat(error).isOfAnyClassIn(loggedException);
@@ -189,11 +187,11 @@
189187 // then
190188 String line = errorAppender.waitAndGet(5000);
191189 assertThat(line)
192- .contains("Query error")
193- .contains(ip)
194- .contains(Integer.toString(scassandra.getBinaryPort()))
195- .contains(query)
196- .contains(loggedException.getName());
190+ .contains("Query error")
191+ .contains(ip)
192+ .contains(Integer.toString(scassandra.getBinaryPort()))
193+ .contains(query)
194+ .contains(loggedException.getName());
197195 }
198196
199197 }
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +173 −176
@@ -15,10 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.ArrayList;
20-import java.util.List;
21-
18+import com.datastax.driver.core.exceptions.DriverException;
2219 import com.datastax.driver.core.utils.CassandraVersion;
2320 import com.google.common.base.Function;
2421 import com.google.common.base.Joiner;
@@ -31,19 +28,18 @@
3128 import org.testng.annotations.BeforeMethod;
3229 import org.testng.annotations.Test;
3330
34-import static com.datastax.driver.core.BatchStatement.Type.COUNTER;
35-import static org.apache.log4j.Level.DEBUG;
36-import static org.apache.log4j.Level.INFO;
37-import static org.apache.log4j.Level.TRACE;
38-import static org.assertj.core.api.Assertions.assertThat;
39-import static org.mockito.Mockito.mock;
40-
41-import com.datastax.driver.core.exceptions.DriverException;
31+import java.nio.ByteBuffer;
32+import java.util.ArrayList;
33+import java.util.List;
4234
35+import static com.datastax.driver.core.BatchStatement.Type.COUNTER;
4336 import static com.datastax.driver.core.BatchStatement.Type.UNLOGGED;
4437 import static com.datastax.driver.core.CCMBridge.ipOfNode;
4538 import static com.datastax.driver.core.QueryLogger.*;
4639 import static com.datastax.driver.core.TestUtils.getFixedValue;
40+import static org.apache.log4j.Level.*;
41+import static org.assertj.core.api.Assertions.assertThat;
42+import static org.mockito.Mockito.mock;
4743
4844 /**
4945 * Main tests for {@link QueryLogger} using {@link com.datastax.driver.core.CCMBridge}.
@@ -60,31 +56,31 @@
6056 }));
6157
6258 private static final List<Object> values = Lists.transform(dataTypes, new Function<DataType, Object>() {
63- @Override
64- public Object apply(DataType type) {
65- return getFixedValue(type);
59+ @Override
60+ public Object apply(DataType type) {
61+ return getFixedValue(type);
62+ }
6663 }
67- }
6864 );
6965
7066 private static final String definitions = Joiner.on(", ").join(
71- Lists.transform(dataTypes, new Function<DataType, String>() {
72- @Override
73- public String apply(DataType type) {
74- return "c_" + type + " " + type;
75- }
76- }
77- )
67+ Lists.transform(dataTypes, new Function<DataType, String>() {
68+ @Override
69+ public String apply(DataType type) {
70+ return "c_" + type + " " + type;
71+ }
72+ }
73+ )
7874 );
7975
8076 private static final String assignments = Joiner.on(", ").join(
81- Lists.transform(dataTypes, new Function<DataType, String>() {
82- @Override
83- public String apply(DataType type) {
84- return "c_" + type + " = ?";
85- }
86- }
87- )
77+ Lists.transform(dataTypes, new Function<DataType, String>() {
78+ @Override
79+ public String apply(DataType type) {
80+ return "c_" + type + " = ?";
81+ }
82+ }
83+ )
8884 );
8985
9086 private Logger normal = Logger.getLogger(NORMAL_LOGGER.getName());
@@ -97,14 +93,14 @@
9793
9894 private QueryLogger queryLogger;
9995
100- @BeforeMethod(groups = { "short", "unit" })
96+ @BeforeMethod(groups = {"short", "unit"})
10197 public void startCapturingLogs() {
10298 normal.addAppender(normalAppender = new MemoryAppender());
10399 slow.addAppender(slowAppender = new MemoryAppender());
104100 error.addAppender(errorAppender = new MemoryAppender());
105101 }
106102
107- @AfterMethod(groups = { "short", "unit" })
103+ @AfterMethod(groups = {"short", "unit"})
108104 public void stopCapturingLogs() {
109105 normal.setLevel(null);
110106 slow.setLevel(null);
@@ -114,16 +110,16 @@
114110 error.removeAppender(errorAppender);
115111 }
116112
117- @BeforeMethod(groups = { "short", "unit" })
113+ @BeforeMethod(groups = {"short", "unit"})
118114 public void resetLogLevels() {
119115 normal.setLevel(INFO);
120116 slow.setLevel(INFO);
121117 error.setLevel(INFO);
122118 }
123119
124- @AfterMethod(groups = { "short", "unit" })
120+ @AfterMethod(groups = {"short", "unit"})
125121 public void unregisterQueryLogger() {
126- if(cluster != null && queryLogger != null) {
122+ if (cluster != null && queryLogger != null) {
127123 cluster.unregister(queryLogger);
128124 }
129125 }
@@ -135,18 +131,18 @@
135131 // given
136132 normal.setLevel(DEBUG);
137133 queryLogger = QueryLogger.builder(cluster)
138- .withConstantThreshold(Long.MAX_VALUE)
139- .build();
134+ .withConstantThreshold(Long.MAX_VALUE)
135+ .build();
140136 cluster.register(queryLogger);
141137 String query = "SELECT c_text FROM test WHERE pk = 42";
142138 session.execute(query);
143139 // then
144140 String line = normalAppender.waitAndGet(10000);
145141 assertThat(line)
146- .contains("Query completed normally")
147- .contains(ipOfNode(1))
148- .contains(query)
149- .doesNotContain("parameters");
142+ .contains("Query completed normally")
143+ .contains(ipOfNode(1))
144+ .contains(query)
145+ .doesNotContain("parameters");
150146 }
151147
152148 @Test(groups = "short")
@@ -154,8 +150,8 @@
154150 // given
155151 normal.setLevel(DEBUG);
156152 queryLogger = QueryLogger.builder(cluster)
157- .withConstantThreshold(Long.MAX_VALUE)
158- .build();
153+ .withConstantThreshold(Long.MAX_VALUE)
154+ .build();
159155 cluster.register(queryLogger);
160156 String query = "SELECT * FROM test where pk = ?";
161157 PreparedStatement ps = session.prepare(query);
@@ -164,21 +160,21 @@
164160 // then
165161 String line = normalAppender.waitAndGet(10000);
166162 assertThat(line)
167- .contains("Query completed normally")
168- .contains(ipOfNode(1))
169- .contains(query)
170- .doesNotContain("actual parameters");
163+ .contains("Query completed normally")
164+ .contains(ipOfNode(1))
165+ .contains(query)
166+ .doesNotContain("actual parameters");
171167 }
172168
173169 @Test(groups = "short")
174- @CassandraVersion(major=2.0)
170+ @CassandraVersion(major = 2.0)
175171 public void should_log_batch_statements() throws Exception {
176172 // given
177173 normal.setLevel(DEBUG);
178174 queryLogger = QueryLogger.builder(cluster)
179- .withConstantThreshold(Long.MAX_VALUE)
180- .withMaxQueryStringLength(Integer.MAX_VALUE)
181- .build();
175+ .withConstantThreshold(Long.MAX_VALUE)
176+ .withMaxQueryStringLength(Integer.MAX_VALUE)
177+ .build();
182178 cluster.register(queryLogger);
183179 // when
184180 String query1 = "INSERT INTO test (pk) VALUES (?)";
@@ -192,24 +188,24 @@
192188 // then
193189 String line = normalAppender.waitAndGet(10000);
194190 assertThat(line)
195- .contains("Query completed normally")
196- .contains(ipOfNode(1))
197- .contains("BEGIN BATCH")
198- .contains("APPLY BATCH")
199- .contains(query1)
200- .contains(query2)
201- .doesNotContain("c_int:");
191+ .contains("Query completed normally")
192+ .contains(ipOfNode(1))
193+ .contains("BEGIN BATCH")
194+ .contains("APPLY BATCH")
195+ .contains(query1)
196+ .contains(query2)
197+ .doesNotContain("c_int:");
202198 }
203199
204200 @Test(groups = "short")
205- @CassandraVersion(major=2.0)
201+ @CassandraVersion(major = 2.0)
206202 public void should_log_unlogged_batch_statements() throws Exception {
207203 // given
208204 normal.setLevel(DEBUG);
209205 queryLogger = QueryLogger.builder(cluster)
210- .withConstantThreshold(Long.MAX_VALUE)
211- .withMaxQueryStringLength(Integer.MAX_VALUE)
212- .build();
206+ .withConstantThreshold(Long.MAX_VALUE)
207+ .withMaxQueryStringLength(Integer.MAX_VALUE)
208+ .build();
213209 cluster.register(queryLogger);
214210 // when
215211 String query1 = "INSERT INTO test (pk) VALUES (?)";
@@ -223,17 +219,17 @@
223219 // then
224220 String line = normalAppender.waitAndGet(10000);
225221 assertThat(line)
226- .contains("Query completed normally")
227- .contains(ipOfNode(1))
228- .contains("BEGIN UNLOGGED BATCH")
229- .contains("APPLY BATCH")
230- .contains(query1)
231- .contains(query2)
232- .doesNotContain("c_int:");
222+ .contains("Query completed normally")
223+ .contains(ipOfNode(1))
224+ .contains("BEGIN UNLOGGED BATCH")
225+ .contains("APPLY BATCH")
226+ .contains(query1)
227+ .contains(query2)
228+ .doesNotContain("c_int:");
233229 }
234230
235231 @Test(groups = "short")
236- @CassandraVersion(major=2.0)
232+ @CassandraVersion(major = 2.0)
237233 public void should_log_counter_batch_statements() throws Exception {
238234 // Create a special table for testing with counters.
239235 session.execute(
@@ -276,6 +272,7 @@
276272 public ByteBuffer getRoutingKey() {
277273 return null;
278274 }
275+
279276 @Override
280277 public String getKeyspace() {
281278 return null;
@@ -348,9 +345,9 @@
348345 // given
349346 normal.setLevel(DEBUG);
350347 queryLogger = QueryLogger.builder(cluster)
351- .withConstantThreshold(Long.MAX_VALUE)
352- .withMaxQueryStringLength(Integer.MAX_VALUE)
353- .build();
348+ .withConstantThreshold(Long.MAX_VALUE)
349+ .withMaxQueryStringLength(Integer.MAX_VALUE)
350+ .build();
354351 cluster.register(queryLogger);
355352 // when
356353 String query = "SELECT * FROM test where pk = ?";
@@ -360,10 +357,10 @@
360357 // then
361358 String line = normalAppender.waitAndGet(10000);
362359 assertThat(line)
363- .contains("Query completed normally")
364- .contains(ipOfNode(1))
365- .contains(query)
366- .doesNotContain("pk:42");
360+ .contains("Query completed normally")
361+ .contains(ipOfNode(1))
362+ .contains(query)
363+ .doesNotContain("pk:42");
367364 }
368365
369366 // Tests for slow and error queries are in QueryLoggerErrorsTest
@@ -371,14 +368,14 @@
371368 // Tests with query parameters (log level TRACE)
372369
373370 @Test(groups = "short")
374- @CassandraVersion(major=2.0)
371+ @CassandraVersion(major = 2.0)
375372 public void should_log_non_null_named_parameter() throws Exception {
376373 // given
377374 normal.setLevel(TRACE);
378375 queryLogger = QueryLogger.builder(cluster)
379- .withConstantThreshold(Long.MAX_VALUE)
380- .withMaxQueryStringLength(Integer.MAX_VALUE)
381- .build();
376+ .withConstantThreshold(Long.MAX_VALUE)
377+ .withMaxQueryStringLength(Integer.MAX_VALUE)
378+ .build();
382379 cluster.register(queryLogger);
383380 // when
384381 String query = "UPDATE test SET c_text = :param1 WHERE pk = :param2";
@@ -390,11 +387,11 @@
390387 // then
391388 String line = normalAppender.waitAndGet(10000);
392389 assertThat(line)
393- .contains("Query completed normally")
394- .contains(ipOfNode(1))
395- .contains(query)
396- .contains("param2:42")
397- .contains("param1:'foo'");
390+ .contains("Query completed normally")
391+ .contains(ipOfNode(1))
392+ .contains(query)
393+ .contains("param2:42")
394+ .contains("param1:'foo'");
398395 }
399396
400397 @Test(groups = "short")
@@ -413,11 +410,11 @@
413410 // then
414411 String line = normalAppender.waitAndGet(10000);
415412 assertThat(line)
416- .contains("Query completed normally")
417- .contains(ipOfNode(1))
418- .contains(query)
419- .contains("pk:42")
420- .contains("c_text:'foo'");
413+ .contains("Query completed normally")
414+ .contains(ipOfNode(1))
415+ .contains(query)
416+ .contains("pk:42")
417+ .contains("c_text:'foo'");
421418 }
422419
423420 @Test(groups = "short")
@@ -436,15 +433,15 @@
436433 // then
437434 String line = normalAppender.waitAndGet(10000);
438435 assertThat(line)
439- .contains("Query completed normally")
440- .contains(ipOfNode(1))
441- .contains(query)
442- .contains("pk:42")
443- .contains("c_text:NULL");
436+ .contains("Query completed normally")
437+ .contains(ipOfNode(1))
438+ .contains(query)
439+ .contains("pk:42")
440+ .contains("c_text:NULL");
444441 }
445442
446443 @Test(groups = "short")
447- @CassandraVersion(major=2.0)
444+ @CassandraVersion(major = 2.0)
448445 public void should_log_bound_statement_parameters_inside_batch_statement() throws Exception {
449446 // given
450447 normal.setLevel(TRACE);
@@ -460,14 +457,14 @@
460457 // then
461458 String line = normalAppender.waitAndGet(10000);
462459 assertThat(line)
463- .contains("Query completed normally")
464- .contains(ipOfNode(1))
465- .contains(query1)
466- .contains(query2)
467- .contains("pk:42")
468- .contains("pk:43")
469- .contains("c_text:'foo'")
470- .contains("c_int:12345");
460+ .contains("Query completed normally")
461+ .contains(ipOfNode(1))
462+ .contains(query1)
463+ .contains(query2)
464+ .contains("pk:42")
465+ .contains("pk:43")
466+ .contains("c_text:'foo'")
467+ .contains("c_int:12345");
471468 }
472469 // Test different CQL types
473470
@@ -476,8 +473,8 @@
476473 // given
477474 normal.setLevel(TRACE);
478475 queryLogger = QueryLogger.builder(cluster)
479- .withMaxParameterValueLength(Integer.MAX_VALUE)
480- .build();
476+ .withMaxParameterValueLength(Integer.MAX_VALUE)
477+ .build();
481478 cluster.register(queryLogger);
482479 // when
483480 String query = "UPDATE test SET " + assignments + " WHERE pk = 42";
@@ -487,9 +484,9 @@
487484 // then
488485 String line = normalAppender.waitAndGet(10000);
489486 assertThat(line)
490- .contains("Query completed normally")
491- .contains(ipOfNode(1))
492- .contains(query);
487+ .contains("Query completed normally")
488+ .contains(ipOfNode(1))
489+ .contains(query);
493490 for (DataType type : dataTypes) {
494491 assertThat(line).contains(type.format(getFixedValue(type)));
495492 }
@@ -502,8 +499,8 @@
502499 // given
503500 normal.setLevel(DEBUG);
504501 queryLogger = QueryLogger.builder(cluster)
505- .withMaxQueryStringLength(5)
506- .build();
502+ .withMaxQueryStringLength(5)
503+ .build();
507504 cluster.register(queryLogger);
508505 // when
509506 String query = "SELECT * FROM test WHERE pk = 42";
@@ -511,20 +508,20 @@
511508 // then
512509 String line = normalAppender.waitAndGet(10000);
513510 assertThat(line)
514- .contains("Query completed normally")
515- .contains(ipOfNode(1))
516- .contains("SELEC" + TRUNCATED_OUTPUT)
517- .doesNotContain(query);
511+ .contains("Query completed normally")
512+ .contains(ipOfNode(1))
513+ .contains("SELEC" + TRUNCATED_OUTPUT)
514+ .doesNotContain(query);
518515 }
519516
520- @CassandraVersion(major=2.0)
517+ @CassandraVersion(major = 2.0)
521518 @Test(groups = "short")
522519 public void should_show_total_statements_for_batches_even_if_query_truncated() throws Exception {
523520 // given
524521 normal.setLevel(DEBUG);
525522 queryLogger = QueryLogger.builder(cluster)
526- .withMaxQueryStringLength(5)
527- .build();
523+ .withMaxQueryStringLength(5)
524+ .build();
528525 cluster.register(queryLogger);
529526 // when
530527 String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
@@ -536,12 +533,12 @@
536533 // then
537534 String line = normalAppender.waitAndGet(10000);
538535 assertThat(line)
539- .contains("Query completed normally")
540- .contains(ipOfNode(1))
541- .contains("BEGIN" + TRUNCATED_OUTPUT)
542- .doesNotContain(query1)
543- .doesNotContain(query2)
544- .contains(" [2 statements");
536+ .contains("Query completed normally")
537+ .contains(ipOfNode(1))
538+ .contains("BEGIN" + TRUNCATED_OUTPUT)
539+ .doesNotContain(query1)
540+ .doesNotContain(query2)
541+ .contains(" [2 statements");
545542 }
546543
547544 @Test(groups = "short")
@@ -549,8 +546,8 @@
549546 // given
550547 normal.setLevel(DEBUG);
551548 queryLogger = QueryLogger.builder(cluster)
552- .withMaxQueryStringLength(-1)
553- .build();
549+ .withMaxQueryStringLength(-1)
550+ .build();
554551 cluster.register(queryLogger);
555552 // when
556553 String query = "SELECT * FROM test WHERE pk = 42";
@@ -558,20 +555,20 @@
558555 // then
559556 String line = normalAppender.waitAndGet(10000);
560557 assertThat(line)
561- .contains("Query completed normally")
562- .contains(ipOfNode(1))
563- .contains(query)
564- .doesNotContain(TRUNCATED_OUTPUT);
558+ .contains("Query completed normally")
559+ .contains(ipOfNode(1))
560+ .contains(query)
561+ .doesNotContain(TRUNCATED_OUTPUT);
565562 }
566563
567- @CassandraVersion(major=2.0)
564+ @CassandraVersion(major = 2.0)
568565 @Test(groups = "short")
569566 public void should_truncate_parameter_when_max_length_exceeded() throws Exception {
570567 // given
571568 normal.setLevel(TRACE);
572569 queryLogger = QueryLogger.builder(cluster)
573- .withMaxParameterValueLength(5)
574- .build();
570+ .withMaxParameterValueLength(5)
571+ .build();
575572 cluster.register(queryLogger);
576573 // when
577574 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
@@ -583,10 +580,10 @@
583580 // then
584581 String line = normalAppender.waitAndGet(10000);
585582 assertThat(line)
586- .contains("Query completed normally")
587- .contains(ipOfNode(1))
588- .contains("c_int:12345" + TRUNCATED_OUTPUT)
589- .doesNotContain("123456");
583+ .contains("Query completed normally")
584+ .contains(ipOfNode(1))
585+ .contains("c_int:12345" + TRUNCATED_OUTPUT)
586+ .doesNotContain("123456");
590587 }
591588
592589 @Test(groups = "short")
@@ -594,23 +591,23 @@
594591 // given
595592 normal.setLevel(TRACE);
596593 queryLogger = QueryLogger.builder(cluster)
597- .withMaxParameterValueLength(6)
598- .build();
594+ .withMaxParameterValueLength(6)
595+ .build();
599596 cluster.register(queryLogger);
600597 // when
601598 String query = "UPDATE test SET c_blob = ? WHERE pk = ?";
602599 PreparedStatement ps = session.prepare(query);
603600 BoundStatement bs = ps.bind();
604- bs.setBytes("c_blob", ByteBuffer.wrap(Bytes.toArray(Lists.newArrayList(1,2,3))));
601+ bs.setBytes("c_blob", ByteBuffer.wrap(Bytes.toArray(Lists.newArrayList(1, 2, 3))));
605602 bs.setInt("pk", 42);
606603 session.execute(bs);
607604 // then
608605 String line = normalAppender.waitAndGet(10000);
609606 assertThat(line)
610- .contains("Query completed normally")
611- .contains(ipOfNode(1))
612- .contains("c_blob:0x0102" + TRUNCATED_OUTPUT)
613- .doesNotContain("123456");
607+ .contains("Query completed normally")
608+ .contains(ipOfNode(1))
609+ .contains("c_blob:0x0102" + TRUNCATED_OUTPUT)
610+ .doesNotContain("123456");
614611 }
615612
616613 @Test(groups = "short")
@@ -618,8 +615,8 @@
618615 // given
619616 normal.setLevel(TRACE);
620617 queryLogger = QueryLogger.builder(cluster)
621- .withMaxParameterValueLength(-1)
622- .build();
618+ .withMaxParameterValueLength(-1)
619+ .build();
623620 cluster.register(queryLogger);
624621 // when
625622 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
@@ -631,10 +628,10 @@
631628 // then
632629 String line = normalAppender.waitAndGet(10000);
633630 assertThat(line)
634- .contains("Query completed normally")
635- .contains(ipOfNode(1))
636- .contains("c_int:123456")
637- .doesNotContain(TRUNCATED_OUTPUT);
631+ .contains("Query completed normally")
632+ .contains(ipOfNode(1))
633+ .contains("c_int:123456")
634+ .doesNotContain(TRUNCATED_OUTPUT);
638635 }
639636
640637 @Test(groups = "short")
@@ -642,8 +639,8 @@
642639 // given
643640 normal.setLevel(TRACE);
644641 queryLogger = QueryLogger.builder(cluster)
645- .withMaxLoggedParameters(1)
646- .build();
642+ .withMaxLoggedParameters(1)
643+ .build();
647644 cluster.register(queryLogger);
648645 // when
649646 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
@@ -655,21 +652,21 @@
655652 // then
656653 String line = normalAppender.waitAndGet(10000);
657654 assertThat(line)
658- .contains("Query completed normally")
659- .contains(ipOfNode(1))
660- .contains("c_int:123456")
661- .doesNotContain("pk:42")
662- .contains(FURTHER_PARAMS_OMITTED);
655+ .contains("Query completed normally")
656+ .contains(ipOfNode(1))
657+ .contains("c_int:123456")
658+ .doesNotContain("pk:42")
659+ .contains(FURTHER_PARAMS_OMITTED);
663660 }
664661
665662 @Test(groups = "short")
666- @CassandraVersion(major=2.0)
663+ @CassandraVersion(major = 2.0)
667664 public void should_not_log_exceeding_number_of_parameters_in_batch_statement() throws Exception {
668665 // given
669666 normal.setLevel(TRACE);
670667 queryLogger = QueryLogger.builder(cluster)
671- .withMaxLoggedParameters(1)
672- .build();
668+ .withMaxLoggedParameters(1)
669+ .build();
673670 cluster.register(queryLogger);
674671 // when
675672 String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
@@ -681,15 +678,15 @@
681678 // then
682679 String line = normalAppender.waitAndGet(10000);
683680 assertThat(line)
684- .contains("Query completed normally")
685- .contains(ipOfNode(1))
686- .contains(query1)
687- .contains(query2)
688- .contains("c_text:'foo'")
689- .doesNotContain("pk:42")
690- .doesNotContain("c_int:12345")
691- .doesNotContain("pk:43")
692- .contains(FURTHER_PARAMS_OMITTED);
681+ .contains("Query completed normally")
682+ .contains(ipOfNode(1))
683+ .contains(query1)
684+ .contains(query2)
685+ .contains("c_text:'foo'")
686+ .doesNotContain("pk:42")
687+ .doesNotContain("c_int:12345")
688+ .doesNotContain("pk:43")
689+ .contains(FURTHER_PARAMS_OMITTED);
693690 }
694691
695692 @Test(groups = "short")
@@ -697,8 +694,8 @@
697694 // given
698695 normal.setLevel(TRACE);
699696 queryLogger = QueryLogger.builder(cluster)
700- .withMaxLoggedParameters(-1)
701- .build();
697+ .withMaxLoggedParameters(-1)
698+ .build();
702699 cluster.register(queryLogger);
703700 // when
704701 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
@@ -710,10 +707,10 @@
710707 // then
711708 String line = normalAppender.waitAndGet(10000);
712709 assertThat(line)
713- .contains("Query completed normally")
714- .contains(ipOfNode(1))
715- .contains("c_int:123456")
716- .contains("pk:42");
710+ .contains("Query completed normally")
711+ .contains(ipOfNode(1))
712+ .contains("c_int:123456")
713+ .contains("pk:42");
717714 }
718715
719716 @Override
modified driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java +11 −10
@@ -15,13 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-import java.util.concurrent.TimeUnit;
20-
2118 import com.google.common.collect.Lists;
22-import org.scassandra.Scassandra;
2319 import org.scassandra.http.client.PreparedStatementPreparation;
24-import org.testng.annotations.*;
20+import org.testng.annotations.AfterMethod;
21+import org.testng.annotations.BeforeMethod;
22+import org.testng.annotations.Test;
23+
24+import java.util.List;
25+import java.util.concurrent.TimeUnit;
2526
2627 import static com.datastax.driver.core.Assertions.assertThat;
2728 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
@@ -46,11 +47,11 @@
4647 queryOptions = new QueryOptions();
4748 loadBalancingPolicy = new SortingLoadBalancingPolicy();
4849 cluster = Cluster.builder()
49- .addContactPoint(CCMBridge.ipOfNode(2))
50- .withLoadBalancingPolicy(loadBalancingPolicy)
51- .withQueryOptions(queryOptions)
52- .withNettyOptions(nonQuietClusterCloseOptions)
53- .build();
50+ .addContactPoint(CCMBridge.ipOfNode(2))
51+ .withLoadBalancingPolicy(loadBalancingPolicy)
52+ .withQueryOptions(queryOptions)
53+ .withNettyOptions(nonQuietClusterCloseOptions)
54+ .build();
5455
5556 session = cluster.connect();
5657
modified driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java +15 −15
@@ -15,23 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
18+import com.datastax.driver.core.Cluster.Builder;
19+import com.datastax.driver.core.Metrics.Errors;
20+import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
21+import com.datastax.driver.core.utils.CassandraVersion;
2022 import com.google.common.collect.Lists;
2123 import org.testng.annotations.BeforeMethod;
2224 import org.testng.annotations.Test;
25+
26+import java.util.Collection;
27+
2328 import static org.testng.Assert.assertEquals;
2429 import static org.testng.Assert.assertTrue;
2530
26-import com.datastax.driver.core.Cluster.Builder;
27-import com.datastax.driver.core.Metrics.Errors;
28-import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
29-import com.datastax.driver.core.utils.CassandraVersion;
30-
3131 /**
3232 * Tests the behavior of client-provided timestamps with protocol v3.
3333 */
34-@CassandraVersion(major=2.1)
34+@CassandraVersion(major = 2.1)
3535 public class QueryTimestampTest extends CCMBridge.PerClassSingleNodeCluster {
3636
3737 @Override
@@ -44,13 +44,13 @@
4444 @Override
4545 protected Builder configure(Builder builder) {
4646 return builder
47- .withTimestampGenerator(new TimestampGenerator() {
48- @Override
49- public long next() {
50- return timestampFromGenerator;
51- }
52- })
53- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
47+ .withTimestampGenerator(new TimestampGenerator() {
48+ @Override
49+ public long next() {
50+ return timestampFromGenerator;
51+ }
52+ })
53+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
5454 }
5555
5656 @BeforeMethod(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java +11 −11
@@ -15,17 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.util.concurrent.Futures;
19+import com.google.common.util.concurrent.ListenableFuture;
20+import com.google.common.util.concurrent.Uninterruptibles;
21+import org.assertj.core.util.Maps;
22+
1823 import java.net.InetAddress;
1924 import java.util.List;
2025 import java.util.Map;
2126 import java.util.concurrent.ExecutionException;
2227 import java.util.concurrent.TimeUnit;
2328
24-import com.google.common.util.concurrent.Futures;
25-import com.google.common.util.concurrent.ListenableFuture;
26-import com.google.common.util.concurrent.Uninterruptibles;
27-import org.assertj.core.util.Maps;
28-
2929 import static com.google.common.collect.Lists.newArrayList;
3030 import static org.assertj.core.api.Assertions.assertThat;
3131 import static org.testng.Assert.fail;
@@ -49,7 +49,7 @@
4949
5050 public void query(Session session, int times, ConsistencyLevel cl, Class<? extends Exception> expectedException) {
5151 Statement statement = new SimpleStatement(QUERY);
52- if(cl != null) {
52+ if (cl != null) {
5353 statement.setConsistencyLevel(cl);
5454 }
5555
@@ -63,20 +63,20 @@
6363 public void query(Session session, int times, Statement statement, Class<? extends Exception> expectedException) {
6464 List<ListenableFuture<ResultSet>> futures = newArrayList();
6565
66- for(int i = 0; i < times; i++) {
66+ for (int i = 0; i < times; i++) {
6767 futures.add(session.executeAsync(statement));
6868 }
6969
7070 try {
7171 List<ResultSet> results = Uninterruptibles.getUninterruptibly(Futures.allAsList(futures), 1, TimeUnit.MINUTES);
72- for(ResultSet result : results) {
72+ for (ResultSet result : results) {
7373 InetAddress coordinator = result.getExecutionInfo().getQueriedHost().getAddress();
7474 Integer n = coordinators.get(coordinator);
7575 coordinators.put(coordinator, n == null ? 1 : n + 1);
7676 }
7777 } catch (ExecutionException ex) {
7878 Throwable cause = ex.getCause();
79- if(expectedException == null) {
79+ if (expectedException == null) {
8080 fail("Queries failed", ex);
8181 } else {
8282 assertThat(cause).isInstanceOf(expectedException);
@@ -99,8 +99,8 @@
9999 public void assertQueried(ScassandraCluster sCluster, int dc, int node, int n) {
100100 int queryCount = queryCount(sCluster, dc, node);
101101 assertThat(queryCount)
102- .as("Expected node %d:%d to be queried %d times but was %d", dc, node, n, queryCount)
103- .isEqualTo(n);
102+ .as("Expected node %d:%d to be queried %d times but was %d", dc, node, n, queryCount)
103+ .isEqualTo(n);
104104 }
105105
106106 public void reset() {
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java +15 −16
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-
2018 import org.testng.annotations.Test;
2119
20+import java.util.List;
21+
2222 import static org.assertj.core.api.Assertions.assertThat;
23-import static org.testng.Assert.fail;
2423
2524 public class RPTokenFactoryTest {
2625 Token.Factory factory = Token.RPToken.FACTORY;
@@ -29,21 +28,21 @@
2928 public void should_split_range() {
3029 List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("127605887595351923798765477786913079296"), 3);
3130 assertThat(splits).containsExactly(
32- factory.fromString("42535295865117307932921825928971026432"),
33- factory.fromString("85070591730234615865843651857942052864")
31+ factory.fromString("42535295865117307932921825928971026432"),
32+ factory.fromString("85070591730234615865843651857942052864")
3433 );
3534 }
3635
3736 @Test(groups = "unit")
3837 public void should_split_range_that_wraps_around_the_ring() {
3938 List<Token> splits = factory.split(
40- factory.fromString("127605887595351923798765477786913079296"),
41- factory.fromString("85070591730234615865843651857942052864"),
42- 3);
39+ factory.fromString("127605887595351923798765477786913079296"),
40+ factory.fromString("85070591730234615865843651857942052864"),
41+ 3);
4342
4443 assertThat(splits).containsExactly(
45- factory.fromString("0"),
46- factory.fromString("42535295865117307932921825928971026432")
44+ factory.fromString("0"),
45+ factory.fromString("42535295865117307932921825928971026432")
4746 );
4847 }
4948
@@ -55,14 +54,14 @@
5554 // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring)
5655 List<Token> splits = factory.split(maxToken, minToken, 3);
5756 assertThat(splits).containsExactly(
58- maxToken,
59- maxToken
57+ maxToken,
58+ maxToken
6059 );
6160
6261 splits = factory.split(minToken, factory.fromString("0"), 3);
6362 assertThat(splits).containsExactly(
64- factory.fromString("0"),
65- factory.fromString("0")
63+ factory.fromString("0"),
64+ factory.fromString("0")
6665 );
6766 }
6867
@@ -70,8 +69,8 @@
7069 public void should_split_whole_ring() {
7170 List<Token> splits = factory.split(factory.fromString("-1"), factory.fromString("-1"), 3);
7271 assertThat(splits).containsExactly(
73- factory.fromString("56713727820156410577229101238628035242"),
74- factory.fromString("113427455640312821154458202477256070485")
72+ factory.fromString("56713727820156410577229101238628035242"),
73+ factory.fromString("113427455640312821154458202477256070485")
7574 );
7675 }
7776 }
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java +2 −1
@@ -22,7 +22,8 @@
2222 super("-p RandomPartitioner", DataType.varint());
2323 }
2424
25- @Override protected Token.Factory tokenFactory() {
25+ @Override
26+ protected Token.Factory tokenFactory() {
2627 return RPToken.FACTORY;
2728 }
2829 }
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java +2 −1
@@ -20,7 +20,8 @@
2020 super("-p RandomPartitioner", DataType.varint(), true);
2121 }
2222
23- @Override protected Token.Factory tokenFactory() {
23+ @Override
24+ protected Token.Factory tokenFactory() {
2425 return Token.RPToken.FACTORY;
2526 }
2627 }
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +17 −18
@@ -15,25 +15,24 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.TimeUnit;
19-
18+import com.datastax.driver.core.utils.CassandraVersion;
2019 import org.slf4j.Logger;
2120 import org.slf4j.LoggerFactory;
2221 import org.testng.annotations.AfterMethod;
2322 import org.testng.annotations.BeforeMethod;
2423 import org.testng.annotations.Test;
2524
25+import java.util.concurrent.TimeUnit;
2626
27-import com.datastax.driver.core.utils.CassandraVersion;
28-
29-import static com.datastax.driver.core.Assertions.*;
27+import static com.datastax.driver.core.Assertions.assertThat;
28+import static com.datastax.driver.core.Assertions.fail;
3029 import static com.datastax.driver.core.Host.State.DOWN;
3130 import static com.datastax.driver.core.Host.State.UP;
3231 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3332
3433 /**
3534 * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
36- *
35+ * <p/>
3736 * This class tests scenarios where these nodes have been recommissioned to another cluster and
3837 * come back up. The driver must detect that they are not part of the cluster anymore, and ignore them.
3938 */
@@ -52,7 +51,7 @@
5251
5352 // Now start the driver that will connect to node2 and node3, and consider node1 down
5453 mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
55- .withQueryOptions(nonDebouncingQueryOptions()).build();
54+ .withQueryOptions(nonDebouncingQueryOptions()).build();
5655 mainCluster.connect();
5756 waitForCountUpHosts(mainCluster, 2);
5857 // From that point, reconnections to node1 have been scheduled.
@@ -75,7 +74,7 @@
7574
7675 // Start the driver, the control connection will be on node2
7776 mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
78- .withQueryOptions(nonDebouncingQueryOptions()).build();
77+ .withQueryOptions(nonDebouncingQueryOptions()).build();
7978 mainCluster.connect();
8079 waitForCountUpHosts(mainCluster, 1);
8180
@@ -103,7 +102,7 @@
103102
104103 // Start the driver, it should only connect to node 2
105104 mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
106- .withQueryOptions(nonDebouncingQueryOptions()).build();
105+ .withQueryOptions(nonDebouncingQueryOptions()).build();
107106
108107 // When we first initialize the Cluster, all hosts are marked UP
109108 assertThat(mainCluster).host(2).hasState(UP);
@@ -114,13 +113,13 @@
114113
115114 // Node 1 should now be DOWN with no reconnection attempt
116115 assertThat(mainCluster).host(1)
117- .goesDownWithin(10, TimeUnit.SECONDS)
118- .hasState(DOWN)
119- .isNotReconnectingFromDown();
116+ .goesDownWithin(10, TimeUnit.SECONDS)
117+ .hasState(DOWN)
118+ .isNotReconnectingFromDown();
120119 }
121120
122121 @Test(groups = "long")
123- @CassandraVersion(major=2.0)
122+ @CassandraVersion(major = 2.0)
124123 public void should_ignore_node_that_does_not_support_protocol_version_on_session_init() throws Exception {
125124 // Simulate the bug before starting the cluster
126125 mainCcm = CCMBridge.builder("main").withNodes(2).build();
@@ -132,16 +131,16 @@
132131
133132 // Start the driver, it should only connect to node 2
134133 mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
135- .withQueryOptions(nonDebouncingQueryOptions()).build();
134+ .withQueryOptions(nonDebouncingQueryOptions()).build();
136135
137136 // Create a session. This will try to open a pool to node 1 and find that it doesn't support protocol version.
138137 mainCluster.connect();
139138
140139 // Node 1 should now be DOWN with no reconnection attempt
141140 assertThat(mainCluster).host(1)
142- .goesDownWithin(10, TimeUnit.SECONDS)
143- .hasState(DOWN)
144- .isNotReconnectingFromDown();
141+ .goesDownWithin(10, TimeUnit.SECONDS)
142+ .hasState(DOWN)
143+ .isNotReconnectingFromDown();
145144 }
146145
147146 @BeforeMethod(groups = "long")
@@ -183,7 +182,7 @@
183182
184183 if (i == maxRetries)
185184 fail(String.format("Up host count didn't reach %d after %d seconds",
186- expectedCount, i * interval));
185+ expectedCount, i * interval));
187186 else
188187 logger.debug("Counted {} up hosts after {} seconds", actualCount, i * interval);
189188
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionPolicyTest.java +18 −11
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import org.testng.annotations.Test;
19-import static org.testng.Assert.assertTrue;
20-import static org.testng.Assert.fail;
21-
2218 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2319 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
2420 import com.datastax.driver.core.policies.ExponentialReconnectionPolicy;
2521 import com.datastax.driver.core.policies.ReconnectionPolicy;
22+import org.testng.annotations.Test;
23+
24+import static org.testng.Assert.assertTrue;
25+import static org.testng.Assert.fail;
2626
2727 public class ReconnectionPolicyTest extends AbstractPoliciesTest {
2828
@@ -47,22 +47,26 @@
4747 try {
4848 new ExponentialReconnectionPolicy(-1, 1);
4949 fail();
50- } catch (IllegalArgumentException e) {}
50+ } catch (IllegalArgumentException e) {
51+ }
5152
5253 try {
5354 new ExponentialReconnectionPolicy(1, -1);
5455 fail();
55- } catch (IllegalArgumentException e) {}
56+ } catch (IllegalArgumentException e) {
57+ }
5658
5759 try {
5860 new ExponentialReconnectionPolicy(-1, -1);
5961 fail();
60- } catch (IllegalArgumentException e) {}
62+ } catch (IllegalArgumentException e) {
63+ }
6164
6265 try {
6366 new ExponentialReconnectionPolicy(2, 1);
6467 fail();
65- } catch (IllegalArgumentException e) {}
68+ } catch (IllegalArgumentException e) {
69+ }
6670
6771 // Test nextDelays()
6872 ReconnectionPolicy.ReconnectionSchedule schedule = new ExponentialReconnectionPolicy(2 * 1000, 5 * 60 * 1000).newSchedule();
@@ -104,7 +108,8 @@
104108 try {
105109 new ConstantReconnectionPolicy(-1);
106110 fail();
107- } catch (IllegalArgumentException e) {}
111+ } catch (IllegalArgumentException e) {
112+ }
108113
109114 // Test nextDelays()
110115 ReconnectionPolicy.ReconnectionSchedule schedule = new ConstantReconnectionPolicy(10 * 1000).newSchedule();
@@ -142,7 +147,8 @@
142147 startTime = System.nanoTime() / 1000000000;
143148 query(c, 12);
144149 fail("Test race condition where node has not shut off quickly enough.");
145- } catch (NoHostAvailableException e) {}
150+ } catch (NoHostAvailableException e) {
151+ }
146152
147153 long thisTime;
148154 boolean restarted = false;
@@ -184,7 +190,8 @@
184190 startTime = System.nanoTime() / 1000000000;
185191 query(c, 12);
186192 fail("Test race condition where node has not shut off quickly enough.");
187- } catch (NoHostAvailableException e) {}
193+ } catch (NoHostAvailableException e) {
194+ }
188195
189196 restarted = false;
190197 while (true) {
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +44 −45
@@ -15,6 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.Host.State;
19+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
20+import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy;
21+import com.datastax.driver.core.policies.LoadBalancingPolicy;
22+import com.datastax.driver.core.policies.RoundRobinPolicy;
23+import com.google.common.util.concurrent.ListenableFuture;
24+import org.testng.annotations.Test;
25+
1826 import java.io.IOException;
1927 import java.net.InetSocketAddress;
2028 import java.util.Collections;
@@ -24,21 +32,10 @@
2432 import java.util.concurrent.TimeUnit;
2533 import java.util.concurrent.atomic.AtomicInteger;
2634
35+import static com.datastax.driver.core.Assertions.assertThat;
2736 import static java.util.concurrent.TimeUnit.SECONDS;
28-
29-import com.google.common.util.concurrent.ListenableFuture;
30-import org.testng.annotations.Test;
31-
3237 import static org.assertj.core.api.Assertions.assertThat;
33-import static org.mockito.Mockito.reset;
34-import static org.mockito.Mockito.spy;
35-import static org.mockito.Mockito.times;
36-import static org.mockito.Mockito.verify;
37-
38-import com.datastax.driver.core.Host.State;
39-import com.datastax.driver.core.policies.*;
40-
41-import static com.datastax.driver.core.Assertions.assertThat;
38+import static org.mockito.Mockito.*;
4239
4340 /**
4441 * Scenarios where a Cluster loses connection to a host and reconnects.
@@ -53,9 +50,9 @@
5350 ccm = CCMBridge.builder("test").withNodes(2).build();
5451 int reconnectionDelay = 1000;
5552 cluster = Cluster.builder()
56- .addContactPoint(CCMBridge.ipOfNode(1))
57- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
58- .build();
53+ .addContactPoint(CCMBridge.ipOfNode(1))
54+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
55+ .build();
5956 cluster.connect();
6057
6158 assertThat(cluster).usesControlHost(1);
@@ -69,7 +66,7 @@
6966 ccm.start(2);
7067 ccm.waitForUp(2);
7168
72- assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
69+ assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
7370
7471 // Give the control connection a few moments to reconnect
7572 TimeUnit.MILLISECONDS.sleep(reconnectionDelay * 2);
@@ -88,9 +85,9 @@
8885 Cluster cluster = null;
8986 try {
9087 ccm = CCMBridge.builder("test")
91- .withCassandraConfiguration("authenticator", "PasswordAuthenticator") // default credentials: cassandra / cassandra
92- .notStarted()
93- .build();
88+ .withCassandraConfiguration("authenticator", "PasswordAuthenticator") // default credentials: cassandra / cassandra
89+ .notStarted()
90+ .build();
9491 ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
9592
9693 CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra");
@@ -98,11 +95,11 @@
9895 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs));
9996
10097 cluster = Cluster.builder()
101- .addContactPoint(CCMBridge.ipOfNode(1))
102- // Start with the correct auth so that we can initialize the server
103- .withAuthProvider(authProvider)
104- .withReconnectionPolicy(reconnectionPolicy)
105- .build();
98+ .addContactPoint(CCMBridge.ipOfNode(1))
99+ // Start with the correct auth so that we can initialize the server
100+ .withAuthProvider(authProvider)
101+ .withReconnectionPolicy(reconnectionPolicy)
102+ .build();
106103
107104 cluster.init();
108105 assertThat(cluster).usesControlHost(1);
@@ -128,7 +125,7 @@
128125 authProvider.setPassword("cassandra");
129126
130127 // The driver should eventually reconnect to the node
131- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
128+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
132129 } finally {
133130 if (cluster != null)
134131 cluster.close();
@@ -148,9 +145,9 @@
148145 try {
149146 ccm = CCMBridge.builder("test").withNodes(2).build();
150147 cluster = Cluster.builder()
151- .addContactPoint(CCMBridge.ipOfNode(1))
152- .withReconnectionPolicy(reconnectionPolicy)
153- .build();
148+ .addContactPoint(CCMBridge.ipOfNode(1))
149+ .withReconnectionPolicy(reconnectionPolicy)
150+ .build();
154151 cluster.connect();
155152
156153 // Stop a node and cancel the reconnection attempts to it
@@ -168,7 +165,7 @@
168165 ccm.waitForUp(2);
169166
170167 // The driver should now see the node as UP again
171- assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
168+ assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
172169
173170 } finally {
174171 if (cluster != null)
@@ -189,10 +186,10 @@
189186 try {
190187 ccm = CCMBridge.builder("test").withNodes(1).build();
191188 cluster = Cluster.builder()
192- .addContactPoint(CCMBridge.ipOfNode(1))
193- .withLoadBalancingPolicy(loadBalancingPolicy)
194- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
195- .build();
189+ .addContactPoint(CCMBridge.ipOfNode(1))
190+ .withLoadBalancingPolicy(loadBalancingPolicy)
191+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
192+ .build();
196193 cluster.connect();
197194
198195 // Tweak the LBP so that the control connection never reconnects, otherwise
@@ -229,7 +226,7 @@
229226 // Trigger another one-time reconnection attempt (this will succeed). The
230227 // host should be back up.
231228 host1.tryReconnectOnce();
232- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
229+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
233230 } finally {
234231 if (cluster != null)
235232 cluster.close();
@@ -255,12 +252,12 @@
255252 try {
256253 ccm = CCMBridge.builder("test").withNodes(1).build();
257254 cluster = Cluster.builder()
258- .addContactPoint(CCMBridge.ipOfNode(1))
259- .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
260- .withLoadBalancingPolicy(loadBalancingPolicy)
261- .withSocketOptions(socketOptions)
262- .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
263- .build();
255+ .addContactPoint(CCMBridge.ipOfNode(1))
256+ .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
257+ .withLoadBalancingPolicy(loadBalancingPolicy)
258+ .withSocketOptions(socketOptions)
259+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
260+ .build();
264261 // Create two sessions to have multiple pools
265262 cluster.connect();
266263 cluster.connect();
@@ -287,7 +284,7 @@
287284 // Reset the spy and count the number of connections attempts for 1 reconnect
288285 reset(socketOptions);
289286 host1.tryReconnectOnce();
290- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
287+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
291288 // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4
292289 // but the one from the reconnection attempt gets reused).
293290 verify(socketOptions, times(corePoolSize * 2)).getKeepAlive();
@@ -299,7 +296,9 @@
299296 }
300297 }
301298
302- /** Extends the plain text auth provider to track how many times the credentials have been requested */
299+ /**
300+ * Extends the plain text auth provider to track how many times the credentials have been requested
301+ */
303302 static class CountingAuthProvider extends PlainTextAuthProvider {
304303 final AtomicInteger count = new AtomicInteger();
305304
@@ -332,8 +331,8 @@
332331 public HostDistance distance(Host host) {
333332 HostDistance distance = distances.get(host);
334333 return (distance != null)
335- ? distance
336- : super.distance(host);
334+ ? distance
335+ : super.distance(host);
337336 }
338337
339338 public void setDistance(Host host, HostDistance distance) {
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +25 −27
@@ -15,17 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import static java.util.concurrent.TimeUnit.SECONDS;
19-
20-import org.mockito.Mockito;
21-import org.testng.annotations.Test;
22-
2318 import com.datastax.driver.core.Host.State;
2419 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
2520 import com.datastax.driver.core.policies.LimitingLoadBalancingPolicy;
2621 import com.datastax.driver.core.policies.RoundRobinPolicy;
22+import org.mockito.Mockito;
23+import org.testng.annotations.Test;
2724
2825 import static com.datastax.driver.core.Assertions.assertThat;
26+import static java.util.concurrent.TimeUnit.SECONDS;
2927
3028 public class RefreshConnectedHostTest {
3129
@@ -49,40 +47,40 @@
4947
5048 PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
5149 cluster = Cluster.builder()
52- .addContactPoint(CCMBridge.ipOfNode(1))
53- .withPoolingOptions(poolingOptions)
54- .withLoadBalancingPolicy(loadBalancingPolicy)
55- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
56- .withQueryOptions(TestUtils.nonDebouncingQueryOptions())
57- .build();
50+ .addContactPoint(CCMBridge.ipOfNode(1))
51+ .withPoolingOptions(poolingOptions)
52+ .withLoadBalancingPolicy(loadBalancingPolicy)
53+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
54+ .withQueryOptions(TestUtils.nonDebouncingQueryOptions())
55+ .build();
5856
5957 Session session = cluster.connect();
6058
6159 assertThat(cluster).usesControlHost(1);
6260 assertThat(cluster).host(1)
63- .hasState(State.UP)
64- .isAtDistance(HostDistance.LOCAL);
61+ .hasState(State.UP)
62+ .isAtDistance(HostDistance.LOCAL);
6563 // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
6664 // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
6765 assertThat(cluster).host(2)
68- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
69- .isAtDistance(HostDistance.LOCAL);
66+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS)
67+ .isAtDistance(HostDistance.LOCAL);
7068
7169 // Bring host 3 up, its presence should be acknowledged but it should be ignored
7270 ccm.start(3);
7371 ccm.waitForUp(3);
7472
7573 assertThat(cluster).host(1)
76- .hasState(State.UP)
77- .isAtDistance(HostDistance.LOCAL);
74+ .hasState(State.UP)
75+ .isAtDistance(HostDistance.LOCAL);
7876 assertThat(cluster).host(2)
79- .hasState(State.UP)
80- .isAtDistance(HostDistance.LOCAL);
77+ .hasState(State.UP)
78+ .isAtDistance(HostDistance.LOCAL);
8179
8280 // Ensure that the host is added to the Cluster.
8381 assertThat(cluster).host(3)
84- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
85- .isAtDistance(HostDistance.IGNORED);
82+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS)
83+ .isAtDistance(HostDistance.IGNORED);
8684 assertThat(session).hasNoPoolFor(3);
8785
8886 // Kill host 2, host 3 should take its place
@@ -90,19 +88,19 @@
9088 TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
9189
9290 assertThat(cluster).host(1)
93- .hasState(State.UP)
94- .isAtDistance(HostDistance.LOCAL);
91+ .hasState(State.UP)
92+ .isAtDistance(HostDistance.LOCAL);
9593 assertThat(cluster).host(2)
96- .hasState(State.DOWN);
94+ .hasState(State.DOWN);
9795 assertThat(cluster).host(3)
98- .hasState(State.UP)
99- .isAtDistance(HostDistance.LOCAL);
96+ .hasState(State.UP)
97+ .isAtDistance(HostDistance.LOCAL);
10098 assertThat(session).hasPoolFor(3);
10199
102100 // This is when refreshConnectedHost should have been invoked, it triggers pool creation when
103101 // we switch the node from IGNORED to UP:
104102 Mockito.verify(poolingOptions)
105- .refreshConnectedHost(TestUtils.findHost(cluster, 3));
103+ .refreshConnectedHost(TestUtils.findHost(cluster, 3));
106104
107105 } finally {
108106 if (cluster != null)
modified driver-core/src/test/java/com/datastax/driver/core/ReplicationStrategyTest.java +18 −17
@@ -17,6 +17,7 @@
1717
1818 import com.google.common.collect.ImmutableMap;
1919 import org.testng.annotations.Test;
20+
2021 import static org.testng.Assert.*;
2122
2223 public class ReplicationStrategyTest {
@@ -25,9 +26,9 @@
2526 public void createSimpleReplicationStrategyTest() throws Exception {
2627 ReplicationStrategy strategy = ReplicationStrategy.create(
2728 ImmutableMap.<String, String>builder()
28- .put("class", "SimpleStrategy")
29- .put("replication_factor", "3")
30- .build());
29+ .put("class", "SimpleStrategy")
30+ .put("replication_factor", "3")
31+ .build());
3132
3233 assertNotNull(strategy);
3334 assertTrue(strategy instanceof ReplicationStrategy.SimpleStrategy);
@@ -37,10 +38,10 @@
3738 public void createNetworkTopologyStrategyTest() throws Exception {
3839 ReplicationStrategy strategy = ReplicationStrategy.create(
3940 ImmutableMap.<String, String>builder()
40- .put("class", "NetworkTopologyStrategy")
41- .put("dc1", "2")
42- .put("dc2", "2")
43- .build());
41+ .put("class", "NetworkTopologyStrategy")
42+ .put("dc1", "2")
43+ .put("dc2", "2")
44+ .build());
4445
4546 assertNotNull(strategy);
4647 assertTrue(strategy instanceof ReplicationStrategy.NetworkTopologyStrategy);
@@ -50,9 +51,9 @@
5051 public void createSimpleReplicationStrategyWithoutFactorTest() throws Exception {
5152 ReplicationStrategy strategy = ReplicationStrategy.create(
5253 ImmutableMap.<String, String>builder()
53- .put("class", "SimpleStrategy")
54- //no replication_factor
55- .build());
54+ .put("class", "SimpleStrategy")
55+ //no replication_factor
56+ .build());
5657
5758 assertNull(strategy);
5859 }
@@ -61,10 +62,10 @@
6162 public void createUnknownStrategyTest() throws Exception {
6263 ReplicationStrategy strategy = ReplicationStrategy.create(
6364 ImmutableMap.<String, String>builder()
64- //no such strategy
65- .put("class", "FooStrategy")
66- .put("foo_factor", "3")
67- .build());
65+ //no such strategy
66+ .put("class", "FooStrategy")
67+ .put("foo_factor", "3")
68+ .build());
6869
6970 assertNull(strategy);
7071 }
@@ -73,9 +74,9 @@
7374 public void createUnspecifiedStrategyTest() throws Exception {
7475 ReplicationStrategy strategy = ReplicationStrategy.create(
7576 ImmutableMap.<String, String>builder()
76- //nothing useful is set
77- .put("foo", "bar")
78- .build());
77+ //nothing useful is set
78+ .put("foo", "bar")
79+ .build());
7980
8081 assertNull(strategy);
8182 }
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +14 −14
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.TimeUnit;
19-import java.util.concurrent.TimeoutException;
20-
2118 import com.google.common.collect.ImmutableMap;
2219 import org.scassandra.Scassandra;
2320 import org.scassandra.http.client.PrimingRequest;
2421 import org.testng.annotations.Test;
2522
23+import java.util.concurrent.TimeUnit;
24+import java.util.concurrent.TimeoutException;
25+
2626 import static org.assertj.core.api.Assertions.assertThat;
2727
2828 public class RequestHandlerTest {
@@ -36,19 +36,19 @@
3636 // Use a mock server that takes a constant time to reply
3737 scassandra.start();
3838 scassandra.primingClient().prime(
39- PrimingRequest.queryBuilder()
40- .withQuery("mock query")
41- .withRows(ImmutableMap.of("key", 1))
42- .withFixedDelay(10)
43- .build()
39+ PrimingRequest.queryBuilder()
40+ .withQuery("mock query")
41+ .withRows(ImmutableMap.of("key", 1))
42+ .withFixedDelay(10)
43+ .build()
4444 );
4545
4646 cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(scassandra.getBinaryPort())
47- .withPoolingOptions(new PoolingOptions()
48- .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
49- .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
50- .setHeartbeatIntervalSeconds(0))
51- .build();
47+ .withPoolingOptions(new PoolingOptions()
48+ .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
49+ .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
50+ .setHeartbeatIntervalSeconds(0))
51+ .build();
5252
5353 Session session = cluster.connect();
5454
@@ -82,7 +82,7 @@
8282 }
8383
8484 private Connection getSingleConnection(Session session) {
85- HostConnectionPool pool = ((SessionManager)session).pools.values().iterator().next();
85+ HostConnectionPool pool = ((SessionManager) session).pools.values().iterator().next();
8686 return pool.connections.get(0);
8787 }
8888 }
modified driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +4 −5
@@ -15,11 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.NoHostAvailableException;
1819 import com.google.common.base.Optional;
1920 import org.testng.annotations.Test;
2021
21-import com.datastax.driver.core.exceptions.NoHostAvailableException;
22-
2322 import static com.datastax.driver.core.CCMBridge.*;
2423
2524 public class SSLAuthenticatedEncryptionTest extends SSLTestBase {
@@ -38,7 +37,7 @@
3837 * @test_category connection:ssl, authentication
3938 * @expected_result Connection can be established to a cassandra node using SSL that requires client auth.
4039 */
41- @Test(groups="short")
40+ @Test(groups = "short")
4241 public void should_connect_with_ssl_with_client_auth_and_node_requires_auth() throws Exception {
4342 connectWithSSLOptions(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
4443 }
@@ -54,7 +53,7 @@
5453 * @test_category connection:ssl, authentication
5554 * @expected_result Connection is not established.
5655 */
57- @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
56+ @Test(groups = "short", expectedExceptions = {NoHostAvailableException.class})
5857 public void should_not_connect_without_client_auth_but_node_requires_auth() throws Exception {
5958 connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
6059 }
@@ -67,7 +66,7 @@
6766 * @test_category connection:ssl, authentication
6867 * @expected_result Connection can be established.
6968 */
70- @Test(groups="isolated")
69+ @Test(groups = "isolated")
7170 public void should_use_system_properties_with_default_ssl_options() throws Exception {
7271 System.setProperty("javax.net.ssl.keyStore", DEFAULT_CLIENT_KEYSTORE_FILE.getAbsolutePath());
7372 System.setProperty("javax.net.ssl.keyStorePassword", DEFAULT_CLIENT_KEYSTORE_PASSWORD);
modified driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +13 −14
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.TimeUnit;
19-
18+import com.datastax.driver.core.exceptions.NoHostAvailableException;
2019 import com.google.common.base.Optional;
2120 import org.testng.annotations.Test;
2221
23-import com.datastax.driver.core.exceptions.NoHostAvailableException;
22+import java.util.concurrent.TimeUnit;
2423
2524 import static com.datastax.driver.core.Assertions.assertThat;
2625 import static com.datastax.driver.core.CCMBridge.*;
@@ -40,7 +39,7 @@
4039 * @test_category connection:ssl
4140 * @expected_result Connection can be established to a cassandra node using SSL.
4241 */
43- @Test(groups="short")
42+ @Test(groups = "short")
4443 public void should_connect_with_ssl_without_client_auth_and_node_doesnt_require_auth() throws Exception {
4544 connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
4645 }
@@ -54,7 +53,7 @@
5453 * @test_category connection:ssl
5554 * @expected_result Connection can not be established to a cassandra node using SSL with an untrusted cert.
5655 */
57- @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
56+ @Test(groups = "short", expectedExceptions = {NoHostAvailableException.class})
5857 public void should_not_connect_with_ssl_without_trusting_server_cert() throws Exception {
5958 connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.<String>absent()));
6059 }
@@ -64,7 +63,7 @@
6463 * Validates that an SSL connection can not be established if the client is not specifying SSL, but
6564 * the cassandra node is using SSL.
6665 * </p>
67- *
66+ * <p/>
6867 * <p>
6968 * Note that future versions of cassandra may support both SSL-encrypted and non-SSL connections
7069 * simultaneously (CASSANDRA-8803)
@@ -73,13 +72,13 @@
7372 * @test_category connection:ssl
7473 * @expected_result Connection can not be established to a cassandra node using SSL and the client not using SSL.
7574 */
76- @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
75+ @Test(groups = "short", expectedExceptions = {NoHostAvailableException.class})
7776 public void should_not_connect_without_ssl_but_node_uses_ssl() throws Exception {
7877 Cluster cluster = null;
7978 try {
8079 cluster = Cluster.builder()
81- .addContactPoint(CCMBridge.IP_PREFIX + '1')
82- .build();
80+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
81+ .build();
8382
8483 cluster.connect();
8584 } finally {
@@ -97,14 +96,14 @@
9796 * @test_category connection:ssl
9897 * @expected_result Connection is re-established within a sufficient amount of time after a node comes back online.
9998 */
100- @Test(groups="long")
99+ @Test(groups = "long")
101100 public void should_reconnect_with_ssl_on_node_up() throws Exception {
102101 Cluster cluster = null;
103102 try {
104103 cluster = Cluster.builder()
105- .addContactPoint(CCMBridge.IP_PREFIX + '1')
106- .withSSL(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)))
107- .build();
104+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
105+ .withSSL(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)))
106+ .build();
108107
109108 cluster.connect();
110109
@@ -126,7 +125,7 @@
126125 * @test_category connection:ssl
127126 * @expected_result Connection can be established.
128127 */
129- @Test(groups="isolated")
128+ @Test(groups = "isolated")
130129 public void should_use_system_properties_with_default_ssl_options() throws Exception {
131130 System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath());
132131 System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD);
modified driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +21 −22
@@ -15,20 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.security.KeyStore;
19-import java.security.SecureRandom;
20-
2118 import com.google.common.base.Optional;
19+import org.testng.annotations.AfterClass;
20+import org.testng.annotations.BeforeClass;
21+
2222 import javax.net.ssl.KeyManagerFactory;
2323 import javax.net.ssl.SSLContext;
2424 import javax.net.ssl.TrustManagerFactory;
25-import org.testng.annotations.AfterClass;
26-import org.testng.annotations.BeforeClass;
25+import java.security.KeyStore;
26+import java.security.SecureRandom;
2727
28-import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_FILE;
2928 import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD;
30-import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_FILE;
3129 import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD;
30+
3231 public abstract class SSLTestBase {
3332
3433 private final boolean requireClientAuth;
@@ -39,14 +38,14 @@
3938 this.requireClientAuth = requireClientAuth;
4039 }
4140
42- @BeforeClass(groups={"isolated", "short", "long"})
41+ @BeforeClass(groups = {"isolated", "short", "long"})
4342 public void beforeClass() {
4443 ccm = CCMBridge.builder("test")
45- .withSSL(requireClientAuth)
46- .build();
44+ .withSSL(requireClientAuth)
45+ .build();
4746 }
4847
49- @AfterClass(groups={"isolated", "short", "long"})
48+ @AfterClass(groups = {"isolated", "short", "long"})
5049 public void afterClass() {
5150 ccm.remove();
5251 }
@@ -59,15 +58,15 @@
5958 *
6059 * @param sslOptions SSLOptions to use.
6160 * @throws Exception A {@link com.datastax.driver.core.exceptions.NoHostAvailableException} will be
62- * raised here if connection cannot be established.
61+ * raised here if connection cannot be established.
6362 */
6463 protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception {
6564 Cluster cluster = null;
6665 try {
6766 cluster = Cluster.builder()
68- .addContactPoint(CCMBridge.IP_PREFIX + '1')
69- .withSSL(sslOptions)
70- .build();
67+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
68+ .withSSL(sslOptions)
69+ .build();
7170
7271 cluster.connect();
7372 } finally {
@@ -83,15 +82,15 @@
8382 * </p>
8483 *
8584 * @throws Exception A {@link com.datastax.driver.core.exceptions.NoHostAvailableException} will be
86- * raised here if connection cannot be established.
85+ * raised here if connection cannot be established.
8786 */
8887 protected void connectWithSSL() throws Exception {
8988 Cluster cluster = null;
9089 try {
9190 cluster = Cluster.builder()
92- .addContactPoint(CCMBridge.IP_PREFIX + '1')
93- .withSSL()
94- .build();
91+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
92+ .withSSL()
93+ .build();
9594
9695 cluster.connect();
9796 } finally {
@@ -101,7 +100,7 @@
101100 }
102101
103102 /**
104- * @param keyStorePath Path to keystore, if absent is not used.
103+ * @param keyStorePath Path to keystore, if absent is not used.
105104 * @param trustStorePath Path to truststore, if absent is not used.
106105 * @return {@link com.datastax.driver.core.SSLOptions} with the given keystore and truststore path's for
107106 * server certificate validation and client certificate authentication.
@@ -109,7 +108,7 @@
109108 public SSLOptions getSSLOptions(Optional<String> keyStorePath, Optional<String> trustStorePath) throws Exception {
110109
111110 TrustManagerFactory tmf = null;
112- if(trustStorePath.isPresent()) {
111+ if (trustStorePath.isPresent()) {
113112 KeyStore ks = KeyStore.getInstance("JKS");
114113 ks.load(this.getClass().getResourceAsStream(trustStorePath.get()), DEFAULT_CLIENT_TRUSTSTORE_PASSWORD.toCharArray());
115114
@@ -118,7 +117,7 @@
118117 }
119118
120119 KeyManagerFactory kmf = null;
121- if(keyStorePath.isPresent()) {
120+ if (keyStorePath.isPresent()) {
122121 KeyStore ks = KeyStore.getInstance("JKS");
123122 ks.load(this.getClass().getResourceAsStream(keyStorePath.get()), DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
124123
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java +135 −136
@@ -15,11 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-import java.util.Map;
20-import java.util.TreeSet;
21-import java.util.concurrent.TimeUnit;
22-
2318 import com.beust.jcommander.internal.Lists;
2419 import com.beust.jcommander.internal.Maps;
2520 import com.google.common.collect.ImmutableList;
@@ -32,14 +27,18 @@
3227 import org.slf4j.Logger;
3328 import org.slf4j.LoggerFactory;
3429
30+import java.util.List;
31+import java.util.Map;
32+import java.util.TreeSet;
33+import java.util.concurrent.TimeUnit;
34+
35+import static com.datastax.driver.core.Assertions.assertThat;
3536 import static org.scassandra.cql.MapType.map;
3637 import static org.scassandra.cql.PrimitiveType.*;
3738 import static org.scassandra.cql.SetType.set;
3839 import static org.scassandra.http.client.PrimingRequest.then;
3940 import static org.scassandra.http.client.types.ColumnMetadata.column;
4041
41-import static com.datastax.driver.core.Assertions.assertThat;
42-
4342 public class ScassandraCluster {
4443
4544 private static final Logger logger = LoggerFactory.getLogger(ScassandraCluster.class);
@@ -152,12 +151,12 @@
152151 /**
153152 * First stops each node in {@code dc} and then asserts that each node's {@link Host}
154153 * is marked down for the given {@link Cluster} instance within 10 seconds.
155- *
154+ * <p/>
156155 * If any of the nodes are the control host, this node is stopped last, to reduce
157156 * likelihood of control connection choosing a host that will be shut down.
158157 *
159158 * @param cluster cluster to wait for down statuses on.
160- * @param dc DC to stop.
159+ * @param dc DC to stop.
161160 */
162161 public void stopDC(Cluster cluster, int dc) {
163162 logger.debug("Stopping all nodes in {}.", datacenter(dc));
@@ -184,7 +183,7 @@
184183 * for the given {@link Cluster} instance within 10 seconds.
185184 *
186185 * @param cluster cluster to wait for down status on.
187- * @param node Node to stop.
186+ * @param node Node to stop.
188187 */
189188 public void stop(Cluster cluster, int node) {
190189 logger.debug("Stopping node {}.", node);
@@ -198,8 +197,8 @@
198197 * for the given {@link Cluster} instance within 10 seconds.
199198 *
200199 * @param cluster cluster to wait for down status on.
201- * @param dc Data center node is in.
202- * @param node Node to stop.
200+ * @param dc Data center node is in.
201+ * @param node Node to stop.
203202 */
204203 public void stop(Cluster cluster, int dc, int node) {
205204 logger.debug("Stopping node {} in {}.", node, datacenter(dc));
@@ -211,7 +210,7 @@
211210 * is marked up for the given {@link Cluster} instance within 10 seconds.
212211 *
213212 * @param cluster cluster to wait for up statuses on.
214- * @param dc DC to start.
213+ * @param dc DC to start.
215214 */
216215 public void startDC(Cluster cluster, int dc) {
217216 logger.debug("Starting all nodes in {}.", datacenter(dc));
@@ -226,7 +225,7 @@
226225 * for the given {@link Cluster} instance within 10 seconds.
227226 *
228227 * @param cluster cluster to wait for up status on.
229- * @param node Node to start.
228+ * @param node Node to start.
230229 */
231230 public void start(Cluster cluster, int node) {
232231 logger.debug("Starting node {}.", node);
@@ -240,8 +239,8 @@
240239 * for the given {@link Cluster} instance within 10 seconds.
241240 *
242241 * @param cluster cluster to wait for up status on.
243- * @param dc Data center node is in.
244- * @param node Node to start.
242+ * @param dc Data center node is in.
243+ * @param node Node to start.
245244 */
246245 public void start(Cluster cluster, int dc, int node) {
247246 logger.debug("Starting node {} in {}.", node, datacenter(dc));
@@ -254,7 +253,7 @@
254253 int dcNodeCount = nodes(dc).size();
255254 List<Long> tokens = Lists.newArrayList(dcNodeCount);
256255 for (int i = 0; i < dcNodeCount; i++) {
257- tokens.add((i * ((long)Math.pow(2, 64) / dcNodeCount) + offset));
256+ tokens.add((i * ((long) Math.pow(2, 64) / dcNodeCount) + offset));
258257 }
259258 return tokens;
260259 }
@@ -277,69 +276,69 @@
277276 metadata = SELECT_LOCAL;
278277 query = "SELECT * FROM system.local WHERE key='local'";
279278 row = ImmutableMap.<String, Object>builder()
280- .put("key", "local")
281- .put("bootstrapped", "COMPLETED")
282- .put("broadcast_address", address)
283- .put("cluster_name", "scassandra")
284- .put("cql_version", "3.2.0")
285- .put("data_center", datacenter(dc))
286- .put("listen_address", address)
287- .put("partitioner", "org.apache.cassandra.dht.Murmur3Partitioner")
288- .put("rack", "rack1")
289- .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"))
290- .put("tokens", ImmutableSet.of(tokens.get(n)))
291- .build();
279+ .put("key", "local")
280+ .put("bootstrapped", "COMPLETED")
281+ .put("broadcast_address", address)
282+ .put("cluster_name", "scassandra")
283+ .put("cql_version", "3.2.0")
284+ .put("data_center", datacenter(dc))
285+ .put("listen_address", address)
286+ .put("partitioner", "org.apache.cassandra.dht.Murmur3Partitioner")
287+ .put("rack", "rack1")
288+ .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"))
289+ .put("tokens", ImmutableSet.of(tokens.get(n)))
290+ .build();
292291 } else { // prime system.peers.
293292 query = "SELECT * FROM system.peers WHERE peer='" + address + "'";
294293 metadata = SELECT_PEERS;
295294 row = ImmutableMap.<String, Object>builder()
296- .put("peer", address)
297- .put("rpc_address", address)
298- .put("data_center", datacenter(dc))
299- .put("rack", "rack1")
300- .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"))
301- .put("tokens", ImmutableSet.of(Long.toString(tokens.get(n))))
302- .build();
295+ .put("peer", address)
296+ .put("rpc_address", address)
297+ .put("data_center", datacenter(dc))
298+ .put("rack", "rack1")
299+ .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"))
300+ .put("tokens", ImmutableSet.of(Long.toString(tokens.get(n))))
301+ .build();
303302 rows.add(row);
304303 }
305304 client.prime(PrimingRequest.queryBuilder()
306- .withQuery(query)
307- .withThen(then()
308- .withColumnTypes(metadata)
309- .withRows(row)
310- .build())
311- .build());
305+ .withQuery(query)
306+ .withThen(then()
307+ .withColumnTypes(metadata)
308+ .withRows(row)
309+ .build())
310+ .build());
312311 }
313312 }
314313
315314 client.prime(PrimingRequest.queryBuilder()
316- .withQuery("SELECT * FROM system.peers")
317- .withThen(then()
318- .withColumnTypes(SELECT_PEERS)
319- .withRows(rows.build())
320- .build())
321- .build());
315+ .withQuery("SELECT * FROM system.peers")
316+ .withThen(then()
317+ .withColumnTypes(SELECT_PEERS)
318+ .withRows(rows.build())
319+ .build())
320+ .build());
322321
323322 // Needed to ensure cluster_name matches what we expect on connection.
324323 Map<String, Object> clusterNameRow = ImmutableMap.<String, Object>builder()
325- .put("cluster_name", "scassandra")
326- .build();
324+ .put("cluster_name", "scassandra")
325+ .build();
327326 client.prime(PrimingRequest.queryBuilder()
328- .withQuery("select cluster_name from system.local")
329- .withThen(then()
330- .withColumnTypes(SELECT_CLUSTER_NAME)
331- .withRows(clusterNameRow)
332- .build())
333- .build());
327+ .withQuery("select cluster_name from system.local")
328+ .withThen(then()
329+ .withColumnTypes(SELECT_CLUSTER_NAME)
330+ .withRows(clusterNameRow)
331+ .build())
332+ .build());
334333
335334 // Prime keyspaces
336335 client.prime(PrimingRequest.queryBuilder()
337- .withQuery("SELECT * FROM system.schema_keyspaces")
338- .withThen(then()
339- .withColumnTypes(SELECT_SCHEMA_KEYSPACES)
340- .withRows(keyspaceRows)
341- .build())
342- .build());
336+ .withQuery("SELECT * FROM system.schema_keyspaces")
337+ .withThen(then()
338+ .withColumnTypes(SELECT_SCHEMA_KEYSPACES)
339+ .withRows(keyspaceRows)
340+ .build())
341+ .build());
343342 }
344343
345344 private Object getPeerInfo(int dc, int node, String property, Object defaultValue) {
@@ -352,87 +351,87 @@
352351 return defaultValue;
353352
354353 return (forNode.containsKey(property))
355- ? forNode.get(property)
356- : defaultValue;
354+ ? forNode.get(property)
355+ : defaultValue;
357356 }
358357
359358 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_PEERS = {
360- column("peer", INET),
361- column("rpc_address", INET),
362- column("data_center", TEXT),
363- column("rack", TEXT),
364- column("release_version", TEXT),
365- column("tokens", set(TEXT))
359+ column("peer", INET),
360+ column("rpc_address", INET),
361+ column("data_center", TEXT),
362+ column("rack", TEXT),
363+ column("release_version", TEXT),
364+ column("tokens", set(TEXT))
366365 };
367366
368367 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_LOCAL = {
369- column("key", TEXT),
370- column("bootstrapped", TEXT),
371- column("broadcast_address", INET),
372- column("cluster_name", TEXT),
373- column("cql_version", TEXT),
374- column("data_center", TEXT),
375- column("listen_address", INET),
376- column("partitioner", TEXT),
377- column("rack", TEXT),
378- column("release_version", TEXT),
379- column("tokens", set(TEXT)),
368+ column("key", TEXT),
369+ column("bootstrapped", TEXT),
370+ column("broadcast_address", INET),
371+ column("cluster_name", TEXT),
372+ column("cql_version", TEXT),
373+ column("data_center", TEXT),
374+ column("listen_address", INET),
375+ column("partitioner", TEXT),
376+ column("rack", TEXT),
377+ column("release_version", TEXT),
378+ column("tokens", set(TEXT)),
380379 };
381380
382381 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_CLUSTER_NAME = {
383- column("cluster_name", TEXT)
382+ column("cluster_name", TEXT)
384383 };
385384
386385 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_KEYSPACES = {
387- column("durable_writes", BOOLEAN),
388- column("keyspace_name", TEXT),
389- column("strategy_class", TEXT),
390- column("strategy_options", TEXT)
386+ column("durable_writes", BOOLEAN),
387+ column("keyspace_name", TEXT),
388+ column("strategy_class", TEXT),
389+ column("strategy_options", TEXT)
391390 };
392391
393392 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_COLUMN_FAMILIES = {
394- column("bloom_filter_fp_chance", DOUBLE),
395- column("caching", TEXT),
396- column("cf_id", UUID),
397- column("column_aliases", TEXT),
398- column("columnfamily_name", TEXT),
399- column("comment", TEXT),
400- column("compaction_strategy_class", TEXT),
401- column("compaction_strategy_options", TEXT),
402- column("comparator", TEXT),
403- column("compression_parameters", TEXT),
404- column("default_time_to_live", INT),
405- column("default_validator", TEXT),
406- column("dropped_columns", map(TEXT, BIG_INT)),
407- column("gc_grace_seconds", INT),
408- column("index_interval", INT),
409- column("is_dense", BOOLEAN),
410- column("key_aliases", TEXT),
411- column("key_validator", TEXT),
412- column("keyspace_name", TEXT),
413- column("local_read_repair_chance", DOUBLE),
414- column("max_compaction_threshold", INT),
415- column("max_index_interval", INT),
416- column("memtable_flush_period_in_ms", INT),
417- column("min_compaction_threshold", INT),
418- column("min_index_interval", INT),
419- column("read_repair_chance", DOUBLE),
420- column("speculative_retry", TEXT),
421- column("subcomparator", TEXT),
422- column("type", TEXT),
423- column("value_alias", TEXT)
393+ column("bloom_filter_fp_chance", DOUBLE),
394+ column("caching", TEXT),
395+ column("cf_id", UUID),
396+ column("column_aliases", TEXT),
397+ column("columnfamily_name", TEXT),
398+ column("comment", TEXT),
399+ column("compaction_strategy_class", TEXT),
400+ column("compaction_strategy_options", TEXT),
401+ column("comparator", TEXT),
402+ column("compression_parameters", TEXT),
403+ column("default_time_to_live", INT),
404+ column("default_validator", TEXT),
405+ column("dropped_columns", map(TEXT, BIG_INT)),
406+ column("gc_grace_seconds", INT),
407+ column("index_interval", INT),
408+ column("is_dense", BOOLEAN),
409+ column("key_aliases", TEXT),
410+ column("key_validator", TEXT),
411+ column("keyspace_name", TEXT),
412+ column("local_read_repair_chance", DOUBLE),
413+ column("max_compaction_threshold", INT),
414+ column("max_index_interval", INT),
415+ column("memtable_flush_period_in_ms", INT),
416+ column("min_compaction_threshold", INT),
417+ column("min_index_interval", INT),
418+ column("read_repair_chance", DOUBLE),
419+ column("speculative_retry", TEXT),
420+ column("subcomparator", TEXT),
421+ column("type", TEXT),
422+ column("value_alias", TEXT)
424423 };
425424
426425 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_COLUMNS = {
427- column("column_name", TEXT),
428- column("columnfamily_name", TEXT),
429- column("component_index", INT),
430- column("index_name", TEXT),
431- column("index_options", TEXT),
432- column("index_type", TEXT),
433- column("keyspace_name", TEXT),
434- column("type", TEXT),
435- column("validator", TEXT),
426+ column("column_name", TEXT),
427+ column("columnfamily_name", TEXT),
428+ column("component_index", INT),
429+ column("index_name", TEXT),
430+ column("index_options", TEXT),
431+ column("index_type", TEXT),
432+ column("keyspace_name", TEXT),
433+ column("type", TEXT),
434+ column("validator", TEXT),
436435 };
437436
438437 public static ScassandraClusterBuilder builder() {
@@ -441,7 +440,7 @@
441440
442441 public static class ScassandraClusterBuilder {
443442
444- private Integer nodes[] = { 1 };
443+ private Integer nodes[] = {1};
445444 private String ipPrefix = CCMBridge.IP_PREFIX;
446445 private final List<Map<String, ? extends Object>> keyspaceRows = Lists.newArrayList();
447446 private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos = Maps.newHashMap();
@@ -458,11 +457,11 @@
458457
459458 public ScassandraClusterBuilder withSimpleKeyspace(String name, int replicationFactor) {
460459 Map<String, Object> simpleKeyspaceRow = ImmutableMap.<String, Object>builder()
461- .put("durable_writes", false)
462- .put("keyspace_name", name)
463- .put("strategy_class", "SimpleStrategy")
464- .put("strategy_options", "{\"replication_factor\":\"" + replicationFactor + "\"}")
465- .build();
460+ .put("durable_writes", false)
461+ .put("keyspace_name", name)
462+ .put("strategy_class", "SimpleStrategy")
463+ .put("strategy_options", "{\"replication_factor\":\"" + replicationFactor + "\"}")
464+ .build();
466465
467466 keyspaceRows.add(simpleKeyspaceRow);
468467 return this;
@@ -481,11 +480,11 @@
481480 String strategyOptions = strategyOptionsBuilder.substring(0, strategyOptionsBuilder.length() - 1) + "}";
482481
483482 Map<String, Object> ntsKeyspaceRow = ImmutableMap.<String, Object>builder()
484- .put("durable_writes", false)
485- .put("keyspace_name", name)
486- .put("strategy_class", "NetworkTopologyStrategy")
487- .put("strategy_options", strategyOptions)
488- .build();
483+ .put("durable_writes", false)
484+ .put("keyspace_name", name)
485+ .put("strategy_class", "NetworkTopologyStrategy")
486+ .put("strategy_options", strategyOptions)
487+ .build();
489488
490489 keyspaceRows.add(ntsKeyspaceRow);
491490 return this;
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +20 −19
@@ -15,9 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.util.Collections;
20-
2118 import org.scassandra.Scassandra;
2219 import org.scassandra.ScassandraFactory;
2320 import org.scassandra.http.client.ActivityClient;
@@ -30,6 +27,9 @@
3027 import org.testng.annotations.BeforeClass;
3128 import org.testng.annotations.BeforeMethod;
3229
30+import java.net.InetSocketAddress;
31+import java.util.Collections;
32+
3333 import static org.assertj.core.api.Assertions.fail;
3434
3535 /**
@@ -58,7 +58,7 @@
5858
5959 protected static String ip = CCMBridge.IP_PREFIX + "1";
6060
61- @BeforeClass(groups = { "short", "long" })
61+ @BeforeClass(groups = {"short", "long"})
6262 public void startScassandra() {
6363 scassandra = ScassandraFactory.createServer(ip, BINARY_PORT, ip, ADMIN_PORT);
6464 scassandra.start();
@@ -68,14 +68,14 @@
6868 hostAddress = new InetSocketAddress(ip, scassandra.getBinaryPort());
6969 }
7070
71- @AfterClass(groups = { "short", "long" })
71+ @AfterClass(groups = {"short", "long"})
7272 public void stopScassandra() {
73- if(scassandra != null)
73+ if (scassandra != null)
7474 scassandra.stop();
7575 }
7676
77- @BeforeMethod(groups = { "short", "long" })
78- @AfterMethod(groups = { "short", "long" })
77+ @BeforeMethod(groups = {"short", "long"})
78+ @AfterMethod(groups = {"short", "long"})
7979 public void resetClients() {
8080 activityClient.clearAllRecordedActivity();
8181 primingClient.clearAllPrimes();
@@ -84,28 +84,29 @@
8484
8585 protected Cluster.Builder createClusterBuilder() {
8686 Cluster.Builder builder = Cluster.builder()
87- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
88- .withPoolingOptions(new PoolingOptions()
89- .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
90- .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
91- .setHeartbeatIntervalSeconds(0))
92- .withPort(scassandra.getBinaryPort());
87+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
88+ .withPoolingOptions(new PoolingOptions()
89+ .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
90+ .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
91+ .setHeartbeatIntervalSeconds(0))
92+ .withPort(scassandra.getBinaryPort());
9393 return builder;
9494 }
9595
9696 /**
9797 * An overrideable method for building on to the Cluster.Builder used for this
9898 * class.
99+ *
99100 * @param builder
100101 * @return
101102 */
102103 protected Cluster.Builder configure(Cluster.Builder builder) {
103- return builder;
104+ return builder;
104105 }
105106
106107 protected Host retrieveSingleHost(Cluster cluster) {
107108 Host host = cluster.getMetadata().getHost(hostAddress);
108- if(host == null) {
109+ if (host == null) {
109110 fail("Unable to retrieve host");
110111 }
111112 return host;
@@ -123,7 +124,7 @@
123124
124125 protected Host host;
125126
126- @BeforeClass(groups = { "short", "long" }, dependsOnMethods = "startScassandra")
127+ @BeforeClass(groups = {"short", "long"}, dependsOnMethods = "startScassandra")
127128 public void initCluster() {
128129 Cluster.Builder builder = createClusterBuilder();
129130 cluster = builder.build();
@@ -131,13 +132,13 @@
131132 session = cluster.connect();
132133 }
133134
134- @AfterClass(groups = { "short", "long" })
135+ @AfterClass(groups = {"short", "long"})
135136 public void closeCluster() {
136137 if (cluster != null)
137138 cluster.close();
138139 }
139140
140- @AfterClass(groups = { "short", "long" }, dependsOnMethods = "closeCluster")
141+ @AfterClass(groups = {"short", "long"}, dependsOnMethods = "closeCluster")
141142 @Override
142143 public void stopScassandra() {
143144 super.stopScassandra();
modified driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java +6 −7
@@ -15,18 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.util.UUID;
20-
18+import com.datastax.driver.core.exceptions.DriverException;
19+import com.datastax.driver.core.utils.UUIDs;
2120 import org.testng.annotations.AfterClass;
2221 import org.testng.annotations.AfterMethod;
2322 import org.testng.annotations.BeforeClass;
2423 import org.testng.annotations.Test;
2524
26-import static org.assertj.core.api.Assertions.assertThat;
25+import java.net.InetAddress;
26+import java.util.UUID;
2727
28-import com.datastax.driver.core.exceptions.DriverException;
29-import com.datastax.driver.core.utils.UUIDs;
28+import static org.assertj.core.api.Assertions.assertThat;
3029
3130 public class SchemaAgreementTest {
3231
@@ -102,7 +101,7 @@
102101
103102 private static void forceSchemaVersion(Session session, InetAddress peerAddress, UUID schemaVersion) {
104103 session.execute(String.format("UPDATE system.peers SET schema_version = %s WHERE peer = %s",
105- DataType.uuid().format(schemaVersion), DataType.inet().format(peerAddress)));
104+ DataType.uuid().format(schemaVersion), DataType.inet().format(peerAddress)));
106105 }
107106
108107 @AfterMethod(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesCCTest.java +34 −40
@@ -15,27 +15,21 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collections;
19-import java.util.Iterator;
20-import java.util.concurrent.TimeUnit;
21-
18+import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy;
19+import com.datastax.driver.core.policies.LoadBalancingPolicy;
20+import com.datastax.driver.core.policies.Policies;
2221 import com.google.common.util.concurrent.Uninterruptibles;
2322 import org.mockito.ArgumentCaptor;
2423 import org.testng.annotations.Test;
2524
26-import static org.mockito.Matchers.any;
27-import static org.mockito.Mockito.mock;
28-import static org.mockito.Mockito.reset;
29-import static org.mockito.Mockito.timeout;
30-import static org.mockito.Mockito.verify;
31-import static org.testng.Assert.fail;
32-
33-import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy;
34-import com.datastax.driver.core.policies.LoadBalancingPolicy;
35-import com.datastax.driver.core.policies.Policies;
25+import java.util.Collections;
26+import java.util.Iterator;
27+import java.util.concurrent.TimeUnit;
3628
3729 import static com.datastax.driver.core.Assertions.assertThat;
3830 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
31+import static org.mockito.Matchers.any;
32+import static org.mockito.Mockito.*;
3933
4034 public class SchemaChangesCCTest {
4135
@@ -44,8 +38,8 @@
4438 /**
4539 * Validates that any schema change events made while the control connection is down are
4640 * propagated when the control connection is re-established.
47- * <p>
48- *
41+ * <p/>
42+ * <p/>
4943 * Note that on control connection recovery not all schema changes are propagated. For example,
5044 * if a table was altered and then dropped only a drop event would be received as that is all
5145 * that can be discerned.
@@ -55,13 +49,13 @@
5549 * @jira_ticket JAVA-151
5650 * @since 2.0.11, 2.1.8, 2.2.1
5751 */
58- @Test(groups="long")
52+ @Test(groups = "long")
5953 public void should_receive_changes_made_while_control_connection_is_down_on_reconnect() throws Exception {
6054 ToggleablePolicy lbPolicy = new ToggleablePolicy(Policies.defaultLoadBalancingPolicy());
6155
6256 CCMBridge ccm = CCMBridge.builder("SchemaChangesCCTest").withNodes(2).build();
6357 Cluster.Builder builder = Cluster.builder()
64- .withLoadBalancingPolicy(lbPolicy);
58+ .withLoadBalancingPolicy(lbPolicy);
6559 Cluster cluster = builder.addContactPoint(CCMBridge.ipOfNode(1)).build();
6660 // Put cluster2 control connection on node 2 so it doesn't go down (to prevent noise for debugging).
6761 Cluster cluster2 = builder.addContactPoint(CCMBridge.ipOfNode(2)).build();
@@ -116,29 +110,29 @@
116110 // Poll on the control connection and wait for it to be reestablished.
117111 long maxControlConnectionWait = 60000;
118112 long startTime = System.currentTimeMillis();
119- while(!cluster.manager.controlConnection.isOpen() && System.currentTimeMillis() - startTime < maxControlConnectionWait) {
113+ while (!cluster.manager.controlConnection.isOpen() && System.currentTimeMillis() - startTime < maxControlConnectionWait) {
120114 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
121115 }
122116
123117 assertThat(cluster.manager.controlConnection.isOpen())
124- .as("Control connection was not opened after %dms.", maxControlConnectionWait)
125- .isTrue();
118+ .as("Control connection was not opened after %dms.", maxControlConnectionWait)
119+ .isTrue();
126120
127121 // Ensure the drop keyspace event shows up.
128122 ArgumentCaptor<KeyspaceMetadata> removedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
129123 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(removedKeyspace.capture());
130124 assertThat(removedKeyspace.getValue())
131- .hasName("ks2")
132- .isEqualTo(predroppedKeyspace);
125+ .hasName("ks2")
126+ .isEqualTo(predroppedKeyspace);
133127
134128 // Ensure the drop table event shows up.
135129 ArgumentCaptor<TableMetadata> droppedTable = ArgumentCaptor.forClass(TableMetadata.class);
136130 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(droppedTable.capture());
137131
138132 assertThat(droppedTable.getValue())
139- .isInKeyspace("ks1")
140- .hasName("tbl2")
141- .isEqualTo(predroppedTable);
133+ .isInKeyspace("ks1")
134+ .hasName("tbl2")
135+ .isEqualTo(predroppedTable);
142136
143137 // Ensure that the alter keyspace event shows up.
144138 ArgumentCaptor<KeyspaceMetadata> alteredKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
@@ -147,14 +141,14 @@
147141
148142 // Previous metadata should match the metadata observed before disconnect.
149143 assertThat(originalKeyspace.getValue())
150- .hasName("ks1")
151- .isDurableWrites()
152- .isEqualTo(prealteredKeyspace);
144+ .hasName("ks1")
145+ .isDurableWrites()
146+ .isEqualTo(prealteredKeyspace);
153147
154148 // New metadata should reflect that the durable writes attribute changed.
155149 assertThat(alteredKeyspace.getValue())
156- .hasName("ks1")
157- .isNotDurableWrites();
150+ .hasName("ks1")
151+ .isNotDurableWrites();
158152
159153 // Ensure the alter table event shows up.
160154 ArgumentCaptor<TableMetadata> alteredTable = ArgumentCaptor.forClass(TableMetadata.class);
@@ -163,16 +157,16 @@
163157
164158 // Previous metadata should match the metadata observed before disconnect.
165159 assertThat(originalTable.getValue())
166- .isInKeyspace("ks1")
167- .hasName("tbl1")
168- .hasColumn("v", DataType.text())
169- .isEqualTo(prealteredTable);
160+ .isInKeyspace("ks1")
161+ .hasName("tbl1")
162+ .hasColumn("v", DataType.text())
163+ .isEqualTo(prealteredTable);
170164
171165 // New metadata should reflect that the column type changed.
172166 assertThat(alteredTable.getValue())
173- .isInKeyspace("ks1")
174- .hasName("tbl1")
175- .hasColumn("v", DataType.blob());
167+ .isInKeyspace("ks1")
168+ .hasName("tbl1")
169+ .hasColumn("v", DataType.blob());
176170
177171 // Ensure the add keyspace event shows up.
178172 ArgumentCaptor<KeyspaceMetadata> addedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
@@ -185,8 +179,8 @@
185179 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(addedTable.capture());
186180
187181 assertThat(addedTable.getValue())
188- .isInKeyspace("ks1")
189- .hasName("tbl3");
182+ .isInKeyspace("ks1")
183+ .hasName("tbl3");
190184 } finally {
191185 cluster.close();
192186 ccm.remove();
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +59 −59
@@ -15,25 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.Collections;
20-import java.util.List;
21-
18+import com.datastax.driver.core.utils.Bytes;
19+import com.datastax.driver.core.utils.CassandraVersion;
2220 import com.google.common.collect.Lists;
2321 import com.google.common.util.concurrent.Futures;
2422 import com.google.common.util.concurrent.ListenableFuture;
2523 import org.mockito.ArgumentCaptor;
2624 import org.testng.annotations.*;
2725
28-import static org.mockito.Matchers.any;
29-import static org.mockito.Mockito.*;
30-
31-import com.datastax.driver.core.utils.Bytes;
32-import com.datastax.driver.core.utils.CassandraVersion;
26+import java.util.Collection;
27+import java.util.Collections;
28+import java.util.List;
3329
3430 import static com.datastax.driver.core.Assertions.assertThat;
3531 import static com.datastax.driver.core.Metadata.handleId;
3632 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
33+import static org.mockito.Matchers.any;
34+import static org.mockito.Mockito.*;
3735
3836 public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster {
3937
@@ -45,7 +43,9 @@
4543 private static final String ALTER_TABLE = "ALTER TABLE %s.table1 ADD j int";
4644 private static final String DROP_TABLE = "DROP TABLE %s.table1";
4745
48- /** The maximum time that the test will wait to check that listeners have been notified */
46+ /**
47+ * The maximum time that the test will wait to check that listeners have been notified
48+ */
4949 private static final int NOTIF_TIMEOUT_MS = 5000;
5050
5151 Cluster cluster1;
@@ -75,16 +75,16 @@
7575 @BeforeClass(groups = "short")
7676 public void setup() throws InterruptedException {
7777 Cluster.Builder builder = configure(Cluster.builder())
78- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
79- .withQueryOptions(nonDebouncingQueryOptions());
78+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
79+ .withQueryOptions(nonDebouncingQueryOptions());
8080 cluster1 = builder.build();
8181 cluster2 = builder.build();
8282 schemaDisabledCluster = spy(configure(Cluster.builder())
83- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
84- .withClusterName("schema-disabled")
85- .withQueryOptions(nonDebouncingQueryOptions()
86- .setMetadataEnabled(false)
87- ).build());
83+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
84+ .withClusterName("schema-disabled")
85+ .withQueryOptions(nonDebouncingQueryOptions()
86+ .setMetadataEnabled(false)
87+ ).build());
8888
8989 schemaDisabledSession = schemaDisabledCluster.connect();
9090
@@ -119,12 +119,12 @@
119119
120120 @DataProvider(name = "existingKeyspaceName")
121121 public static Object[][] existingKeyspaceName() {
122- return new Object[][]{ { "lowercase" }, { "\"CaseSensitive\"" } };
122+ return new Object[][]{{"lowercase"}, {"\"CaseSensitive\""}};
123123 }
124124
125125 @DataProvider(name = "newKeyspaceName")
126126 public static Object[][] newKeyspaceName() {
127- return new Object[][]{ { "lowercase2" }, { "\"CaseSensitive2\"" } };
127+ return new Object[][]{{"lowercase2"}, {"\"CaseSensitive2\""}};
128128 }
129129
130130 @BeforeMethod(groups = "short")
@@ -154,8 +154,8 @@
154154 ArgumentCaptor<TableMetadata> added = ArgumentCaptor.forClass(TableMetadata.class);
155155 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
156156 assertThat(added.getValue())
157- .isInKeyspace(handleId(keyspace))
158- .hasName("table1");
157+ .isInKeyspace(handleId(keyspace))
158+ .hasName("table1");
159159 }
160160
161161 for (Metadata m : metadatas)
@@ -172,8 +172,8 @@
172172 added = ArgumentCaptor.forClass(TableMetadata.class);
173173 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
174174 assertThat(added.getValue())
175- .isInKeyspace(handleId(keyspace))
176- .hasName("table1");
175+ .isInKeyspace(handleId(keyspace))
176+ .hasName("table1");
177177 }
178178 execute(ALTER_TABLE, keyspace);
179179 for (SchemaChangeListener listener : listeners) {
@@ -181,12 +181,12 @@
181181 ArgumentCaptor<TableMetadata> previous = ArgumentCaptor.forClass(TableMetadata.class);
182182 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableChanged(current.capture(), previous.capture());
183183 assertThat(previous.getValue())
184- .isEqualTo(added.getValue())
185- .hasNoColumn("j");
184+ .isEqualTo(added.getValue())
185+ .hasNoColumn("j");
186186 assertThat(current.getValue())
187- .isInKeyspace(handleId(keyspace))
188- .hasName("table1")
189- .hasColumn("j");
187+ .isInKeyspace(handleId(keyspace))
188+ .hasName("table1")
189+ .hasColumn("j");
190190 }
191191 for (Metadata m : metadatas)
192192 assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j");
@@ -199,8 +199,8 @@
199199 ArgumentCaptor<TableMetadata> added = ArgumentCaptor.forClass(TableMetadata.class);
200200 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
201201 assertThat(added.getValue())
202- .hasName("table1")
203- .isInKeyspace(handleId(keyspace));
202+ .hasName("table1")
203+ .isInKeyspace(handleId(keyspace));
204204 }
205205 execute(DROP_TABLE, keyspace);
206206 for (Metadata m : metadatas)
@@ -211,7 +211,7 @@
211211 assertThat(removed.getValue()).hasName("table1");
212212 }
213213 }
214-
214+
215215 @Test(groups = "short", dataProvider = "existingKeyspaceName")
216216 @CassandraVersion(major = 2.1)
217217 public void should_notify_of_udt_creation(String keyspace) {
@@ -220,13 +220,13 @@
220220 for (SchemaChangeListener listener : listeners) {
221221 ArgumentCaptor<UserType> added = ArgumentCaptor.forClass(UserType.class);
222222 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeAdded(added.capture());
223- assertThat((DataType)added.getValue())
224- .isUserType(handleId(keyspace), "type1");
223+ assertThat((DataType) added.getValue())
224+ .isUserType(handleId(keyspace), "type1");
225225 }
226226
227227 for (Metadata m : metadatas)
228- assertThat((DataType)m.getKeyspace(keyspace).getUserType("type1"))
229- .isNotNull();
228+ assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1"))
229+ .isNotNull();
230230 }
231231
232232 @Test(groups = "short", dataProvider = "existingKeyspaceName")
@@ -245,7 +245,7 @@
245245
246246 for (Metadata m : metadatas)
247247 assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j"))
248- .isNotNull();
248+ .isNotNull();
249249 }
250250
251251 @Test(groups = "short", dataProvider = "existingKeyspaceName")
@@ -257,12 +257,12 @@
257257 for (SchemaChangeListener listener : listeners) {
258258 ArgumentCaptor<UserType> removed = ArgumentCaptor.forClass(UserType.class);
259259 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeRemoved(removed.capture());
260- assertThat((DataType)removed.getValue()).isUserType(handleId(keyspace), "type1");
260+ assertThat((DataType) removed.getValue()).isUserType(handleId(keyspace), "type1");
261261 }
262262
263263 for (Metadata m : metadatas)
264264 assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1"))
265- .isNull();
265+ .isNull();
266266 }
267267
268268 @Test(groups = "short", dataProvider = "newKeyspaceName")
@@ -294,11 +294,11 @@
294294 ArgumentCaptor<KeyspaceMetadata> previous = ArgumentCaptor.forClass(KeyspaceMetadata.class);
295295 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(current.capture(), previous.capture());
296296 assertThat(previous.getValue())
297- .isEqualTo(added.getValue())
298- .isDurableWrites();
297+ .isEqualTo(added.getValue())
298+ .isDurableWrites();
299299 assertThat(current.getValue())
300- .hasName(handleId(keyspace))
301- .isNotDurableWrites();
300+ .hasName(handleId(keyspace))
301+ .isNotDurableWrites();
302302 }
303303 for (Metadata m : metadatas)
304304 assertThat(m.getKeyspace(keyspace)).isNotDurableWrites();
@@ -315,13 +315,13 @@
315315 ArgumentCaptor<TableMetadata> table = ArgumentCaptor.forClass(TableMetadata.class);
316316 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(table.capture());
317317 assertThat(table.getValue())
318- .hasName("table1")
319- .isInKeyspace(handleId(keyspace));
318+ .hasName("table1")
319+ .isInKeyspace(handleId(keyspace));
320320
321321 ArgumentCaptor<KeyspaceMetadata> ks = ArgumentCaptor.forClass(KeyspaceMetadata.class);
322322 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(ks.capture());
323323 assertThat(ks.getValue())
324- .hasName(handleId(keyspace));
324+ .hasName(handleId(keyspace));
325325 }
326326 for (Metadata m : metadatas) {
327327 assertThat(m.getKeyspace(keyspace)).isNull();
@@ -340,10 +340,10 @@
340340 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
341341 public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() {
342342 Cluster cluster = configure(Cluster.builder())
343- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
344- .withQueryOptions(nonDebouncingQueryOptions()
345- .setMetadataEnabled(false)
346- ).build();
343+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
344+ .withQueryOptions(nonDebouncingQueryOptions()
345+ .setMetadataEnabled(false)
346+ ).build();
347347
348348 try {
349349 cluster.init();
@@ -364,10 +364,10 @@
364364 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
365365 public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() {
366366 Cluster cluster = configure(Cluster.builder())
367- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
368- .withQueryOptions(nonDebouncingQueryOptions()
369- .setMetadataEnabled(false)
370- ).build();
367+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
368+ .withQueryOptions(nonDebouncingQueryOptions()
369+ .setMetadataEnabled(false)
370+ ).build();
371371
372372 try {
373373 cluster.init();
@@ -438,12 +438,12 @@
438438 @AfterMethod(groups = "short")
439439 public void cleanup() throws InterruptedException {
440440 ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList(
441- session1.executeAsync("DROP TABLE lowercase.table1"),
442- session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
443- session1.executeAsync("DROP TYPE lowercase.type1"),
444- session1.executeAsync("DROP TYPE \"CaseSensitive\".type1"),
445- session1.executeAsync("DROP KEYSPACE lowercase2"),
446- session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
441+ session1.executeAsync("DROP TABLE lowercase.table1"),
442+ session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
443+ session1.executeAsync("DROP TYPE lowercase.type1"),
444+ session1.executeAsync("DROP TYPE \"CaseSensitive\".type1"),
445+ session1.executeAsync("DROP KEYSPACE lowercase2"),
446+ session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
447447 ));
448448 Futures.getUnchecked(f);
449449 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +26 −27
@@ -15,23 +15,22 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
2018 import org.mockito.ArgumentCaptor;
2119 import org.testng.annotations.AfterClass;
2220 import org.testng.annotations.AfterMethod;
2321 import org.testng.annotations.BeforeClass;
2422 import org.testng.annotations.Test;
2523
26-import static com.google.common.collect.Lists.newArrayList;
27-import static org.mockito.ArgumentCaptor.forClass;
28-import static org.mockito.Mockito.*;
24+import java.util.Collection;
2925
3026 import static com.datastax.driver.core.Assertions.assertThat;
3127 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
3228 import static com.datastax.driver.core.SchemaElement.TABLE;
3329 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
3430 import static com.datastax.driver.core.TestUtils.CREATE_TABLE_SIMPLE_FORMAT;
31+import static com.google.common.collect.Lists.newArrayList;
32+import static org.mockito.ArgumentCaptor.forClass;
33+import static org.mockito.Mockito.*;
3534
3635 public class SchemaRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
3736
@@ -63,9 +62,9 @@
6362 queryOptions.setMaxPendingRefreshSchemaRequests(5);
6463 // Create a separate cluster that will receive the schema events on its control connection.
6564 cluster2 = this.configure(Cluster.builder())
66- .addContactPointsWithPorts(newArrayList(hostAddress))
67- .withQueryOptions(queryOptions)
68- .build();
65+ .addContactPointsWithPorts(newArrayList(hostAddress))
66+ .withQueryOptions(queryOptions)
67+ .build();
6968 session2 = cluster2.connect();
7069
7170 // Create a spy of the Cluster's control connection and replace it with the spy.
@@ -90,7 +89,7 @@
9089 public void teardown() {
9190 cluster2.close();
9291 // drop all keyspaces
93- for(String keyspace : keyspaces) {
92+ for (String keyspace : keyspaces) {
9493 session.execute("DROP KEYSPACE " + keyspace);
9594 }
9695 }
@@ -182,7 +181,7 @@
182181 reset(listener);
183182
184183 int tableCount = 3;
185- for(int i =0 ; i < tableCount; i++) {
184+ for (int i = 0; i < tableCount; i++) {
186185 session.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + "tbl" + i));
187186 }
188187
@@ -195,7 +194,7 @@
195194 KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
196195 assertThat(ksm).isNotNull();
197196 // metadata is present for each table.
198- for(int i = 0; i < tableCount; i++) {
197+ for (int i = 0; i < tableCount; i++) {
199198 String table = "tbl" + i;
200199 // Should have never been a refreshSchema on the table.
201200 verify(controlConnection, never()).refreshSchema(TABLE, keyspace, table);
@@ -233,16 +232,16 @@
233232 ArgumentCaptor<TableMetadata> captor = forClass(TableMetadata.class);
234233 verify(listener, timeout(DEBOUNCE_TIME * 2).only()).onTableChanged(captor.capture(), original.capture());
235234 assertThat(captor.getValue())
236- .hasName(table)
237- .isInKeyspace(keyspace)
238- .hasColumn(columnName)
239- .hasComment(comment);
235+ .hasName(table)
236+ .isInKeyspace(keyspace)
237+ .hasColumn(columnName)
238+ .hasComment(comment);
240239
241240 assertThat(original.getValue())
242- .hasName(table)
243- .isInKeyspace(keyspace)
244- .hasNoColumn(columnName)
245- .doesNotHaveComment(comment);
241+ .hasName(table)
242+ .isInKeyspace(keyspace)
243+ .hasNoColumn(columnName)
244+ .doesNotHaveComment(comment);
246245
247246 // Verify a refresh of the table was executed, but only once.
248247 verify(controlConnection, times(1)).refreshSchema(TABLE, keyspace, table);
@@ -251,10 +250,10 @@
251250 assertThat(ksm).isNotNull();
252251 TableMetadata tm = ksm.getTable(table);
253252 assertThat(tm)
254- .hasName(table)
255- .isInKeyspace(keyspace)
256- .hasColumn(columnName)
257- .hasComment(comment);
253+ .hasName(table)
254+ .isInKeyspace(keyspace)
255+ .hasColumn(columnName)
256+ .hasComment(comment);
258257 }
259258
260259 /**
@@ -270,7 +269,7 @@
270269 @Test(groups = "short")
271270 public void should_debounce_and_coalesce_multiple_keyspace_creates_into_refresh_entire_schema() throws Exception {
272271 String prefix = "sdacmkc";
273- for(int i = 0; i < 3; i++) {
272+ for (int i = 0; i < 3; i++) {
274273 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
275274 keyspaces.add(prefix + i);
276275 }
@@ -279,7 +278,7 @@
279278 // Verify a complete schema refresh was executed, but only once.
280279 verify(controlConnection, times(1)).refreshSchema(null, null, null);
281280
282- for(int i = 0; i < 3; i++) {
281+ for (int i = 0; i < 3; i++) {
283282 KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i);
284283 assertThat(ksm).isNotNull().hasName(prefix + i);
285284 }
@@ -297,7 +296,7 @@
297296 @Test(groups = "short")
298297 public void should_refresh_when_max_pending_requests_reached() throws Exception {
299298 String prefix = "srwmprr";
300- for(int i = 0; i < 5; i++) {
299+ for (int i = 0; i < 5; i++) {
301300 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
302301 keyspaces.add(prefix + i);
303302 }
@@ -307,7 +306,7 @@
307306 // Verify a complete schema refresh was executed, but only once.
308307 verify(controlConnection, times(1)).refreshSchema(null, null, null);
309308
310- for(int i = 0; i < 5; i++) {
309+ for (int i = 0; i < 5; i++) {
311310 KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i);
312311 assertThat(ksm).isNotNull().hasName(prefix + i);
313312 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +62 −62
@@ -15,12 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.util.*;
20-
2118 import org.slf4j.Logger;
2219 import org.slf4j.LoggerFactory;
2320 import org.testng.annotations.Test;
21+
22+import java.util.*;
23+
2424 import static org.testng.Assert.assertEquals;
2525
2626 /**
@@ -37,9 +37,9 @@
3737 @Override
3838 protected Cluster.Builder configure(Cluster.Builder builder) {
3939 return builder.withQueryOptions(new QueryOptions()
40- .setRefreshNodeIntervalMillis(0)
41- .setRefreshNodeListIntervalMillis(0)
42- .setRefreshSchemaIntervalMillis(0)
40+ .setRefreshNodeIntervalMillis(0)
41+ .setRefreshNodeListIntervalMillis(0)
42+ .setRefreshSchemaIntervalMillis(0)
4343 );
4444 }
4545
@@ -47,51 +47,51 @@
4747 protected Collection<String> getTableDefinitions() {
4848
4949 String sparse = String.format("CREATE TABLE %s.sparse (\n"
50- + " k text,\n"
51- + " c1 int,\n"
52- + " c2 float,\n"
53- + " l list<text>,\n"
54- + " v int,\n"
55- + " PRIMARY KEY (k, c1, c2)\n"
56- + ");", keyspace);
50+ + " k text,\n"
51+ + " c1 int,\n"
52+ + " c2 float,\n"
53+ + " l list<text>,\n"
54+ + " v int,\n"
55+ + " PRIMARY KEY (k, c1, c2)\n"
56+ + ");", keyspace);
5757
5858 String st = String.format("CREATE TABLE %s.static (\n"
59- + " k text,\n"
60- + " i int,\n"
61- + " m map<text, timeuuid>,\n"
62- + " v int,\n"
63- + " PRIMARY KEY (k)\n"
64- + ");", keyspace);
59+ + " k text,\n"
60+ + " i int,\n"
61+ + " m map<text, timeuuid>,\n"
62+ + " v int,\n"
63+ + " PRIMARY KEY (k)\n"
64+ + ");", keyspace);
6565
6666 String counters = String.format("CREATE TABLE %s.counters (\n"
67- + " k text,\n"
68- + " c counter,\n"
69- + " PRIMARY KEY (k)\n"
70- + ");", keyspace);
67+ + " k text,\n"
68+ + " c counter,\n"
69+ + " PRIMARY KEY (k)\n"
70+ + ");", keyspace);
7171
7272 String compactStatic = String.format("CREATE TABLE %s.compact_static (\n"
73- + " k text,\n"
74- + " i int,\n"
75- + " t timeuuid,\n"
76- + " v int,\n"
77- + " PRIMARY KEY (k)\n"
78- + ") WITH COMPACT STORAGE;", keyspace);
73+ + " k text,\n"
74+ + " i int,\n"
75+ + " t timeuuid,\n"
76+ + " v int,\n"
77+ + " PRIMARY KEY (k)\n"
78+ + ") WITH COMPACT STORAGE;", keyspace);
7979
8080 String compactDynamic = String.format("CREATE TABLE %s.compact_dynamic (\n"
81- + " k text,\n"
82- + " c int,\n"
83- + " v timeuuid,\n"
84- + " PRIMARY KEY (k, c)\n"
85- + ") WITH COMPACT STORAGE;", keyspace);
81+ + " k text,\n"
82+ + " c int,\n"
83+ + " v timeuuid,\n"
84+ + " PRIMARY KEY (k, c)\n"
85+ + ") WITH COMPACT STORAGE;", keyspace);
8686
8787 String compactComposite = String.format("CREATE TABLE %s.compact_composite (\n"
88- + " k text,\n"
89- + " c1 int,\n"
90- + " c2 float,\n"
91- + " c3 double,\n"
92- + " v timeuuid,\n"
93- + " PRIMARY KEY (k, c1, c2, c3)\n"
94- + ") WITH COMPACT STORAGE;", keyspace);
88+ + " k text,\n"
89+ + " c1 int,\n"
90+ + " c2 float,\n"
91+ + " c3 double,\n"
92+ + " v timeuuid,\n"
93+ + " PRIMARY KEY (k, c1, c2, c3)\n"
94+ + ") WITH COMPACT STORAGE;", keyspace);
9595
9696 cql3.put("sparse", sparse);
9797 cql3.put("static", st);
@@ -103,7 +103,7 @@
103103 Properties properties = System.getProperties();
104104 String vmVersion = properties.getProperty("java.vm.specification.version");
105105 double javaVersion = 1.6;
106- if(vmVersion != null) {
106+ if (vmVersion != null) {
107107 try {
108108 javaVersion = Double.parseDouble(vmVersion);
109109 } catch (NumberFormatException e) {
@@ -113,27 +113,27 @@
113113
114114 // Ordering of compaction options will be dependent on JDK. See schemaOptionsTest comments for explanation of why this is needed.
115115 String compactionOptions;
116- if(javaVersion >= 1.8)
116+ if (javaVersion >= 1.8)
117117 compactionOptions = " AND compaction = { 'sstable_size_in_mb' : 15, 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy' }\n";
118118 else
119119 compactionOptions = " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n";
120120
121121 withOptions = String.format("CREATE TABLE %s.with_options (\n"
122- + " k text,\n"
123- + " v1 int,\n"
124- + " v2 int,\n"
125- + " i int,\n"
126- + " PRIMARY KEY (k, v1, v2)\n"
127- + ") WITH CLUSTERING ORDER BY (v1 DESC, v2 ASC)\n"
128- + " AND read_repair_chance = 0.5\n"
129- + " AND dclocal_read_repair_chance = 0.6\n"
130- + " AND replicate_on_write = true\n"
131- + " AND gc_grace_seconds = 42\n"
132- + " AND bloom_filter_fp_chance = 0.01\n"
133- + " AND caching = 'ALL'\n"
134- + " AND comment = 'My awesome table'\n"
135- + compactionOptions
136- + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 };", keyspace);
122+ + " k text,\n"
123+ + " v1 int,\n"
124+ + " v2 int,\n"
125+ + " i int,\n"
126+ + " PRIMARY KEY (k, v1, v2)\n"
127+ + ") WITH CLUSTERING ORDER BY (v1 DESC, v2 ASC)\n"
128+ + " AND read_repair_chance = 0.5\n"
129+ + " AND dclocal_read_repair_chance = 0.6\n"
130+ + " AND replicate_on_write = true\n"
131+ + " AND gc_grace_seconds = 42\n"
132+ + " AND bloom_filter_fp_chance = 0.01\n"
133+ + " AND caching = 'ALL'\n"
134+ + " AND comment = 'My awesome table'\n"
135+ + compactionOptions
136+ + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 };", keyspace);
137137
138138 List<String> allDefs = new ArrayList<String>();
139139 allDefs.addAll(cql3.values());
@@ -186,7 +186,7 @@
186186
187187 // With C* 2.x we'll have a few additional options
188188 withOpts += " AND default_time_to_live = 0\n"
189- + " AND speculative_retry = '99.0PERCENTILE'\n";
189+ + " AND speculative_retry = '99.0PERCENTILE'\n";
190190
191191 if (version.getMinor() == 0) {
192192 // With 2.0 we'll have one more options
@@ -194,11 +194,11 @@
194194 } else {
195195 // With 2.1 we have different options, the caching option changes and replicate_on_write disappears
196196 withOpts += " AND min_index_interval = 128\n"
197- + " AND max_index_interval = 2048;";
197+ + " AND max_index_interval = 2048;";
198198
199199 withOpts = withOpts.replace("caching = 'ALL'",
200- "caching = { 'keys' : 'ALL', 'rows_per_partition' : 'ALL' }")
201- .replace(" AND replicate_on_write = true\n", "");
200+ "caching = { 'keys' : 'ALL', 'rows_per_partition' : 'ALL' }")
201+ .replace(" AND replicate_on_write = true\n", "");
202202 }
203203 }
204204 assertEquals(metadata.exportAsString(), withOpts);
modified driver-core/src/test/java/com/datastax/driver/core/SessionAssert.java +1 −1
@@ -23,7 +23,7 @@
2323
2424 protected SessionAssert(Session actual) {
2525 // We are cheating a bit by casting, but this is the only implementation anyway
26- super((SessionManager)actual, SessionAssert.class);
26+ super((SessionManager) actual, SessionAssert.class);
2727 }
2828
2929 public SessionAssert hasPoolFor(int hostNumber) {
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +12 −15
@@ -15,30 +15,27 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidQueryException;
19+import com.datastax.driver.core.utils.SocketChannelMonitor;
20+import com.google.common.collect.Lists;
21+import org.testng.annotations.Test;
22+
1823 import java.net.InetSocketAddress;
1924 import java.util.Collections;
2025 import java.util.List;
2126 import java.util.concurrent.TimeUnit;
2227
23-import static java.util.concurrent.TimeUnit.MINUTES;
24-
25-import com.google.common.collect.Lists;
26-import org.testng.annotations.Test;
27-
28-import static org.assertj.core.api.Assertions.fail;
29-
30-import com.datastax.driver.core.exceptions.InvalidQueryException;
31-import com.datastax.driver.core.utils.SocketChannelMonitor;
32-
3328 import static com.datastax.driver.core.Assertions.assertThat;
3429 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
30+import static java.util.concurrent.TimeUnit.MINUTES;
31+import static org.assertj.core.api.Assertions.fail;
3532
3633 public class SessionLeakTest {
3734
3835 Cluster cluster;
3936 List<InetSocketAddress> nodes = Lists.newArrayList(
40- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
41- new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042));
37+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
38+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042));
4239 SocketChannelMonitor channelMonitor;
4340
4441 @Test(groups = "short")
@@ -115,9 +112,9 @@
115112 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
116113 try {
117114 cluster = Cluster.builder()
118- .addContactPointsWithPorts(Collections.singletonList(
119- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
120- .withNettyOptions(channelMonitor.nettyOptions()).build();
115+ .addContactPointsWithPorts(Collections.singletonList(
116+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
117+ .withNettyOptions(channelMonitor.nettyOptions()).build();
121118
122119 cluster.init();
123120
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +2 −2
@@ -212,10 +212,10 @@
212212
213213 // Immediately wait for CloseFutures, this should be very quick since all this work does is call closeAsync.
214214 List<ListenableFuture<Void>> futures = Lists.newArrayListWithCapacity(iterations);
215- for(ListenableFuture<CloseFuture> closeFuture : closeFutures) {
215+ for (ListenableFuture<CloseFuture> closeFuture : closeFutures) {
216216 try {
217217 futures.add(closeFuture.get());
218- } catch(Exception e) {
218+ } catch (Exception e) {
219219 logger.error("Got interrupted exception while waiting on closeFuture.", e);
220220 }
221221 }
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +13 −19
@@ -15,25 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.util.*;
20-import java.util.concurrent.CountDownLatch;
21-import java.util.concurrent.ExecutorService;
22-import java.util.concurrent.Executors;
23-import java.util.concurrent.TimeUnit;
24-
2518 import com.datastax.driver.core.utils.CassandraVersion;
26-import com.datastax.driver.core.utils.SocketChannelMonitor;
27-import io.netty.channel.socket.SocketChannel;
2819 import org.slf4j.Logger;
2920 import org.slf4j.LoggerFactory;
3021 import org.testng.annotations.Test;
3122
32-import static org.testng.Assert.assertEquals;
33-import static org.testng.Assert.assertTrue;
34-import static org.testng.Assert.fail;
23+import java.util.*;
24+import java.util.concurrent.CountDownLatch;
25+import java.util.concurrent.ExecutorService;
26+import java.util.concurrent.Executors;
27+import java.util.concurrent.TimeUnit;
3528
3629 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
30+import static org.testng.Assert.*;
3731
3832 /**
3933 * Simple test of the Sessions methods against a one node cluster.
@@ -50,9 +44,9 @@
5044 @Override
5145 protected Collection<String> getTableDefinitions() {
5246 return Arrays.asList(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1),
53- String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE2),
54- String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE3),
55- String.format("CREATE TABLE %s (k text PRIMARY KEY, c counter)", COUNTER_TABLE));
47+ String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE2),
48+ String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE3),
49+ String.format("CREATE TABLE %s (k text PRIMARY KEY, c counter)", COUNTER_TABLE));
5650 }
5751
5852 @Test(groups = "short")
@@ -134,7 +128,7 @@
134128 * @expected_result session established and queries made successfully using it.
135129 */
136130 @Test(groups = "short")
137- @CassandraVersion(major=2.0)
131+ @CassandraVersion(major = 2.0)
138132 public void session_should_function_with_lz4_compression() throws Exception {
139133 compressionTest(ProtocolOptions.Compression.LZ4);
140134 }
@@ -174,9 +168,9 @@
174168 // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster
175169 // (note the use of newSession below)
176170 final Cluster cluster = Cluster.builder()
177- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
178- .withNettyOptions(nonQuietClusterCloseOptions)
179- .build();
171+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
172+ .withNettyOptions(nonQuietClusterCloseOptions)
173+ .build();
180174 final Session session = cluster.newSession();
181175
182176 // Spawn two threads to simulate the race
modified driver-core/src/test/java/com/datastax/driver/core/SimpleJSONParserTest.java +2 −2
@@ -15,10 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.google.common.collect.ImmutableMap;
1918 import com.google.common.collect.ImmutableList;
20-
19+import com.google.common.collect.ImmutableMap;
2120 import org.testng.annotations.Test;
21+
2222 import static org.testng.Assert.assertEquals;
2323
2424 public class SimpleJSONParserTest {
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +8 −8
@@ -15,28 +15,28 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.Test;
19+
1820 import java.util.Collections;
1921 import java.util.List;
2022
21-import org.testng.annotations.Test;
22-
2323 import static org.assertj.core.api.Assertions.assertThat;
2424
2525 public class SimpleStatementTest {
2626
27- @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
27+ @Test(groups = "unit", expectedExceptions = {IllegalArgumentException.class})
2828 public void should_fail_if_too_many_variables() {
29- List<Object> args = Collections.nCopies(1 << 16, (Object)1);
29+ List<Object> args = Collections.nCopies(1 << 16, (Object) 1);
3030 new SimpleStatement("mock query", args.toArray());
3131 }
3232
33- @Test(groups = "unit", expectedExceptions = { IllegalStateException.class })
33+ @Test(groups = "unit", expectedExceptions = {IllegalStateException.class})
3434 public void should_throw_ISE_if_getObject_called_on_statement_without_values() {
3535 new SimpleStatement("doesn't matter").getObject(0);
3636 }
3737
3838
39- @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class })
39+ @Test(groups = "unit", expectedExceptions = {IndexOutOfBoundsException.class})
4040 public void should_throw_IOOBE_if_getObject_called_with_wrong_index() {
4141 new SimpleStatement("doesn't matter", new Object()).getObject(1);
4242 }
@@ -51,10 +51,10 @@
5151 @Test(groups = "unit")
5252 public void should_return_number_of_values() {
5353 assertThat(
54- new SimpleStatement("doesn't matter").valuesCount()
54+ new SimpleStatement("doesn't matter").valuesCount()
5555 ).isEqualTo(0);
5656 assertThat(
57- new SimpleStatement("doesn't matter", 1, 2).valuesCount()
57+ new SimpleStatement("doesn't matter", 1, 2).valuesCount()
5858 ).isEqualTo(2);
5959 }
6060
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStrategyTest.java +72 −72
@@ -15,15 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.collect.ImmutableList;
19+import com.google.common.collect.ImmutableMap;
20+import org.testng.annotations.Test;
21+
1822 import java.net.InetSocketAddress;
1923 import java.util.List;
2024 import java.util.Map;
2125 import java.util.Set;
2226
23-import com.google.common.collect.ImmutableList;
24-import com.google.common.collect.ImmutableMap;
25-import org.testng.annotations.Test;
26-
2727 public class SimpleStrategyTest extends AbstractReplicationStrategyTest {
2828
2929 private static ReplicationStrategy simpleStrategy(int replicationFactor) {
@@ -73,46 +73,46 @@
7373 private static final ReplicationStrategy exampleStrategyTooManyReplicas = simpleStrategy(8);
7474
7575 private static final List<Token> exampleRing = ImmutableList.<Token>builder()
76- .add(TOKEN01)
77- .add(TOKEN02)
78- .add(TOKEN03)
79- .add(TOKEN04)
80- .add(TOKEN05)
81- .add(TOKEN06)
82- .add(TOKEN07)
83- .add(TOKEN08)
84- .add(TOKEN09)
85- .add(TOKEN10)
86- .add(TOKEN11)
87- .add(TOKEN12)
88- .add(TOKEN13)
89- .add(TOKEN14)
90- .add(TOKEN15)
91- .add(TOKEN16)
92- .add(TOKEN17)
93- .add(TOKEN18)
94- .build();
76+ .add(TOKEN01)
77+ .add(TOKEN02)
78+ .add(TOKEN03)
79+ .add(TOKEN04)
80+ .add(TOKEN05)
81+ .add(TOKEN06)
82+ .add(TOKEN07)
83+ .add(TOKEN08)
84+ .add(TOKEN09)
85+ .add(TOKEN10)
86+ .add(TOKEN11)
87+ .add(TOKEN12)
88+ .add(TOKEN13)
89+ .add(TOKEN14)
90+ .add(TOKEN15)
91+ .add(TOKEN16)
92+ .add(TOKEN17)
93+ .add(TOKEN18)
94+ .build();
9595
9696 private static final Map<Token, Host> exampleTokenToPrimary = ImmutableMap.<Token, Host>builder()
97- .put(TOKEN01, host(IP1))
98- .put(TOKEN02, host(IP1))
99- .put(TOKEN03, host(IP5))
100- .put(TOKEN04, host(IP3))
101- .put(TOKEN05, host(IP1))
102- .put(TOKEN06, host(IP5))
103- .put(TOKEN07, host(IP2))
104- .put(TOKEN08, host(IP6))
105- .put(TOKEN09, host(IP3))
106- .put(TOKEN10, host(IP4))
107- .put(TOKEN11, host(IP5))
108- .put(TOKEN12, host(IP4))
109- .put(TOKEN13, host(IP4))
110- .put(TOKEN14, host(IP2))
111- .put(TOKEN15, host(IP6))
112- .put(TOKEN16, host(IP3))
113- .put(TOKEN17, host(IP2))
114- .put(TOKEN18, host(IP6))
115- .build();
97+ .put(TOKEN01, host(IP1))
98+ .put(TOKEN02, host(IP1))
99+ .put(TOKEN03, host(IP5))
100+ .put(TOKEN04, host(IP3))
101+ .put(TOKEN05, host(IP1))
102+ .put(TOKEN06, host(IP5))
103+ .put(TOKEN07, host(IP2))
104+ .put(TOKEN08, host(IP6))
105+ .put(TOKEN09, host(IP3))
106+ .put(TOKEN10, host(IP4))
107+ .put(TOKEN11, host(IP5))
108+ .put(TOKEN12, host(IP4))
109+ .put(TOKEN13, host(IP4))
110+ .put(TOKEN14, host(IP2))
111+ .put(TOKEN15, host(IP6))
112+ .put(TOKEN16, host(IP3))
113+ .put(TOKEN17, host(IP2))
114+ .put(TOKEN18, host(IP6))
115+ .build();
116116
117117 private static final String keyspace = "excalibur";
118118
@@ -125,18 +125,18 @@
125125 @Test(groups = "unit")
126126 public void simpleStrategySimpleTopologyTest() {
127127 List<Token> ring = ImmutableList.<Token>builder()
128- .add(TOKEN01)
129- .add(TOKEN06)
130- .add(TOKEN14)
131- .add(TOKEN19)
132- .build();
128+ .add(TOKEN01)
129+ .add(TOKEN06)
130+ .add(TOKEN14)
131+ .add(TOKEN19)
132+ .build();
133133
134134 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
135- .put(TOKEN01, host(IP1))
136- .put(TOKEN06, host(IP2))
137- .put(TOKEN14, host(IP1))
138- .put(TOKEN19, host(IP2))
139- .build();
135+ .put(TOKEN01, host(IP1))
136+ .put(TOKEN06, host(IP2))
137+ .put(TOKEN14, host(IP1))
138+ .put(TOKEN19, host(IP2))
139+ .build();
140140
141141 ReplicationStrategy strategy = simpleStrategy(2);
142142
@@ -151,18 +151,18 @@
151151 @Test(groups = "unit")
152152 public void simpleStrategyConsecutiveRingSectionsTest() {
153153 List<Token> ring = ImmutableList.<Token>builder()
154- .add(TOKEN01)
155- .add(TOKEN06)
156- .add(TOKEN14)
157- .add(TOKEN19)
158- .build();
154+ .add(TOKEN01)
155+ .add(TOKEN06)
156+ .add(TOKEN14)
157+ .add(TOKEN19)
158+ .build();
159159
160160 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
161- .put(TOKEN01, host(IP1))
162- .put(TOKEN06, host(IP1))
163- .put(TOKEN14, host(IP2))
164- .put(TOKEN19, host(IP2))
165- .build();
161+ .put(TOKEN01, host(IP1))
162+ .put(TOKEN06, host(IP1))
163+ .put(TOKEN14, host(IP2))
164+ .put(TOKEN19, host(IP2))
165+ .build();
166166
167167 ReplicationStrategy strategy = simpleStrategy(2);
168168
@@ -177,18 +177,18 @@
177177 @Test(groups = "unit")
178178 public void simpleStrategyUnbalancedRingTest() {
179179 List<Token> ring = ImmutableList.<Token>builder()
180- .add(TOKEN01)
181- .add(TOKEN06)
182- .add(TOKEN14)
183- .add(TOKEN19)
184- .build();
180+ .add(TOKEN01)
181+ .add(TOKEN06)
182+ .add(TOKEN14)
183+ .add(TOKEN19)
184+ .build();
185185
186186 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
187- .put(TOKEN01, host(IP1))
188- .put(TOKEN06, host(IP1))
189- .put(TOKEN14, host(IP2))
190- .put(TOKEN19, host(IP1))
191- .build();
187+ .put(TOKEN01, host(IP1))
188+ .put(TOKEN06, host(IP1))
189+ .put(TOKEN14, host(IP2))
190+ .put(TOKEN19, host(IP1))
191+ .build();
192192
193193 ReplicationStrategy strategy = simpleStrategy(2);
194194
modified driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java +6 −7
@@ -15,6 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.CassandraVersion;
19+import org.testng.annotations.Test;
20+import org.testng.collections.Lists;
21+
1822 import java.net.InetSocketAddress;
1923 import java.util.Collection;
2024 import java.util.concurrent.Executors;
@@ -22,14 +26,9 @@
2226 import java.util.concurrent.TimeUnit;
2327 import java.util.concurrent.atomic.AtomicBoolean;
2428
25-import org.testng.annotations.Test;
26-import org.testng.collections.Lists;
27-
2829 import static org.testng.Assert.fail;
2930
30-import com.datastax.driver.core.utils.CassandraVersion;
31-
32-@CassandraVersion(major=2.1)
31+@CassandraVersion(major = 2.1)
3332 public class SingleConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
3433 @Override
3534 protected Collection<String> getTableDefinitions() {
@@ -41,7 +40,7 @@
4140 // Throttle to a very low value. Even a single thread can generate a higher throughput.
4241 final int maxRequests = 10;
4342 cluster.getConfiguration().getPoolingOptions()
44- .setMaxRequestsPerConnection(HostDistance.LOCAL, maxRequests);
43+ .setMaxRequestsPerConnection(HostDistance.LOCAL, maxRequests);
4544
4645 // Track in flight requests in a dedicated thread every second
4746 final AtomicBoolean excessInflightQueriesSpotted = new AtomicBoolean(false);
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +17 −18
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Set;
20-
18+import com.datastax.driver.core.utils.Bytes;
2119 import org.testng.annotations.Test;
2220
23-import com.datastax.driver.core.utils.Bytes;
21+import java.nio.ByteBuffer;
22+import java.util.Set;
2423
2524 import static com.datastax.driver.core.Assertions.assertThat;
2625
@@ -35,18 +34,18 @@
3534
3635 try {
3736 ccm = CCMBridge.builder("test")
38- // force the initial token to a non-min value to validate that the single range will always be ]minToken, minToken]
39- .withCassandraConfiguration("initial_token", "1")
40- .build();
37+ // force the initial token to a non-min value to validate that the single range will always be ]minToken, minToken]
38+ .withCassandraConfiguration("initial_token", "1")
39+ .build();
4140
4241 cluster = Cluster.builder()
43- .addContactPoint(CCMBridge.ipOfNode(1))
44- .withQueryOptions(new QueryOptions()
45- .setRefreshNodeIntervalMillis(0)
46- .setRefreshNodeListIntervalMillis(0)
47- .setRefreshSchemaIntervalMillis(0)
48- )
49- .build();
42+ .addContactPoint(CCMBridge.ipOfNode(1))
43+ .withQueryOptions(new QueryOptions()
44+ .setRefreshNodeIntervalMillis(0)
45+ .setRefreshNodeListIntervalMillis(0)
46+ .setRefreshSchemaIntervalMillis(0)
47+ )
48+ .build();
5049
5150 Session session = cluster.connect();
5251 session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
@@ -57,10 +56,10 @@
5756 assertThat(tokenRanges).hasSize(1);
5857 TokenRange tokenRange = tokenRanges.iterator().next();
5958 assertThat(tokenRange)
60- .startsWith(Token.M3PToken.FACTORY.minToken())
61- .endsWith(Token.M3PToken.FACTORY.minToken())
62- .isNotEmpty()
63- .isNotWrappedAround();
59+ .startsWith(Token.M3PToken.FACTORY.minToken())
60+ .endsWith(Token.M3PToken.FACTORY.minToken())
61+ .isNotEmpty()
62+ .isNotWrappedAround();
6463
6564 Set<Host> hostsForRange = metadata.getReplicas("test", tokenRange);
6665 Host host1 = TestUtils.findHost(cluster, 1);
modified driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java +5 −6
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.policies.LoadBalancingPolicy;
19+import com.google.common.primitives.UnsignedBytes;
20+
1821 import java.util.Collection;
1922 import java.util.Comparator;
2023 import java.util.Iterator;
2124 import java.util.SortedSet;
2225 import java.util.concurrent.ConcurrentSkipListSet;
2326
24-import com.google.common.primitives.UnsignedBytes;
25-
26-import com.datastax.driver.core.policies.LoadBalancingPolicy;
27-
2827 /**
2928 * A load balancing policy that sorts hosts on the last byte of the address,
3029 * so that the query plan is always [host1, host2, host3].
@@ -37,8 +36,8 @@
3736 byte[] address1 = host1.getAddress().getAddress();
3837 byte[] address2 = host2.getAddress().getAddress();
3938 return UnsignedBytes.compare(
40- address1[address1.length - 1],
41- address2[address2.length - 1]);
39+ address1[address1.length - 1],
40+ address2[address2.length - 1]);
4241 }
4342 });
4443
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionIntegrationTest.java +8 −9
@@ -15,18 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
18+import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
19+import com.datastax.driver.core.utils.CassandraVersion;
2020 import com.google.common.collect.Lists;
2121 import org.mockito.Mockito;
2222 import org.testng.annotations.Test;
2323
24+import java.util.Collection;
25+
2426 import static org.assertj.core.api.Assertions.assertThat;
2527 import static org.mockito.Mockito.times;
2628
27-import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
28-import com.datastax.driver.core.utils.CassandraVersion;
29-
3029 /**
3130 * Test that needs a real CCM cluster (as opposed to SCassandra for other specex tests), because
3231 * it uses a protocol v3 feature.
@@ -44,10 +43,10 @@
4443 protected Cluster.Builder configure(Cluster.Builder builder) {
4544 timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE);
4645 return builder
47- .withTimestampGenerator(timestampGenerator)
48- .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
49- // Set an artificially low timeout to force speculative execution
50- .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, 2));
46+ .withTimestampGenerator(timestampGenerator)
47+ .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
48+ // Set an artificially low timeout to force speculative execution
49+ .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, 2));
5150 }
5251
5352 /**
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +54 −56
@@ -15,24 +15,22 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
19+import com.datastax.driver.core.policies.RetryPolicy;
2020 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2121 import com.google.common.collect.ImmutableList;
2222 import com.google.common.collect.ImmutableMap;
23-import org.scassandra.Scassandra;
2423 import org.scassandra.http.client.PrimingRequest;
25-import org.testng.annotations.*;
24+import org.testng.annotations.AfterMethod;
25+import org.testng.annotations.BeforeMethod;
26+import org.testng.annotations.Test;
2627
27-import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
28-import com.datastax.driver.core.policies.RetryPolicy;
28+import java.util.List;
29+import java.util.Map;
2930
3031 import static com.datastax.driver.core.Assertions.assertThat;
3132 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
32-
33-import static org.mockito.Mockito.mock;
34-import static org.mockito.Mockito.times;
35-import static org.mockito.Mockito.verify;
33+import static org.mockito.Mockito.*;
3634
3735 public class SpeculativeExecutionTest {
3836 ScassandraCluster scassandras;
@@ -52,13 +50,13 @@
5250
5351 loadBalancingPolicy = new SortingLoadBalancingPolicy();
5452 cluster = Cluster.builder()
55- .addContactPoint(scassandras.address(2))
56- .withLoadBalancingPolicy(loadBalancingPolicy)
57- .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1))
58- .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
59- .withRetryPolicy(new CustomRetryPolicy())
60- .withNettyOptions(nonQuietClusterCloseOptions)
61- .build();
53+ .addContactPoint(scassandras.address(2))
54+ .withLoadBalancingPolicy(loadBalancingPolicy)
55+ .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1))
56+ .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
57+ .withRetryPolicy(new CustomRetryPolicy())
58+ .withNettyOptions(nonQuietClusterCloseOptions)
59+ .build();
6260
6361 session = cluster.connect();
6462
@@ -80,9 +78,9 @@
8078 @Test(groups = "short")
8179 public void should_not_start_speculative_execution_if_first_execution_completes_successfully() {
8280 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
83- .withQuery("mock query")
84- .withRows(row("result", "result1"))
85- .build()
81+ .withQuery("mock query")
82+ .withRows(row("result", "result1"))
83+ .build()
8684 );
8785
8886 long execStartCount = errors.getSpeculativeExecutions().getCount();
@@ -99,17 +97,17 @@
9997 public void should_not_start_speculative_execution_if_first_execution_retries_but_is_still_fast_enough() {
10098 // will retry once on this node:
10199 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
102- .withQuery("mock query")
103- .withConsistency(PrimingRequest.Consistency.TWO)
104- .withResult(PrimingRequest.Result.read_request_timeout)
105- .build()
100+ .withQuery("mock query")
101+ .withConsistency(PrimingRequest.Consistency.TWO)
102+ .withResult(PrimingRequest.Result.read_request_timeout)
103+ .build()
106104 );
107105
108106 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
109- .withQuery("mock query")
110- .withConsistency(PrimingRequest.Consistency.ONE)
111- .withRows(row("result", "result1"))
112- .build()
107+ .withQuery("mock query")
108+ .withConsistency(PrimingRequest.Consistency.ONE)
109+ .withRows(row("result", "result1"))
110+ .build()
113111 );
114112
115113 long execStartCount = errors.getSpeculativeExecutions().getCount();
@@ -129,16 +127,16 @@
129127 @Test(groups = "short")
130128 public void should_start_speculative_execution_if_first_execution_takes_too_long() {
131129 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
132- .withQuery("mock query")
133- .withFixedDelay(400)
134- .withRows(row("result", "result1"))
135- .build()
130+ .withQuery("mock query")
131+ .withFixedDelay(400)
132+ .withRows(row("result", "result1"))
133+ .build()
136134 );
137135
138136 scassandras.node(2).primingClient().prime(PrimingRequest.queryBuilder()
139- .withQuery("mock query")
140- .withRows(row("result", "result2"))
141- .build()
137+ .withQuery("mock query")
138+ .withRows(row("result", "result2"))
139+ .build()
142140 );
143141 long execStartCount = errors.getSpeculativeExecutions().getCount();
144142
@@ -156,28 +154,28 @@
156154 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1000);
157155
158156 scassandras.node(1).primingClient()
159- // execution1 starts with host1, which will time out at t=1000
160- .prime(PrimingRequest.queryBuilder()
161- .withQuery("mock query")
162- .withFixedDelay(2000)
163- .withRows(row("result", "result1"))
164- .build());
165- // at t=1000, execution1 moves to host3, which eventually succeeds at t=1500
157+ // execution1 starts with host1, which will time out at t=1000
158+ .prime(PrimingRequest.queryBuilder()
159+ .withQuery("mock query")
160+ .withFixedDelay(2000)
161+ .withRows(row("result", "result1"))
162+ .build());
163+ // at t=1000, execution1 moves to host3, which eventually succeeds at t=1500
166164 scassandras.node(3).primingClient()
167- .prime(PrimingRequest.queryBuilder()
168- .withQuery("mock query")
169- .withFixedDelay(500)
170- .withRows(row("result", "result3"))
171- .build());
172- // meanwhile, execution2 starts at t=200, using host2 which times out at t=1200
173- // at that time, the query plan is empty so execution2 fails
174- // The goal of this test is to check that execution2 does not fail the query, since execution1 is still running
165+ .prime(PrimingRequest.queryBuilder()
166+ .withQuery("mock query")
167+ .withFixedDelay(500)
168+ .withRows(row("result", "result3"))
169+ .build());
170+ // meanwhile, execution2 starts at t=200, using host2 which times out at t=1200
171+ // at that time, the query plan is empty so execution2 fails
172+ // The goal of this test is to check that execution2 does not fail the query, since execution1 is still running
175173 scassandras.node(2).primingClient()
176- .prime(PrimingRequest.queryBuilder()
177- .withQuery("mock query")
178- .withFixedDelay(2000)
179- .withRows(row("result", "result2"))
180- .build());
174+ .prime(PrimingRequest.queryBuilder()
175+ .withQuery("mock query")
176+ .withFixedDelay(2000)
177+ .withRows(row("result", "result2"))
178+ .build());
181179 long execStartCount = errors.getSpeculativeExecutions().getCount();
182180
183181 ResultSet rs = session.execute("mock query");
@@ -197,7 +195,7 @@
197195 * @jira_ticket JAVA-796
198196 * @since 2.0.11, 2.1.7, 2.2.1
199197 */
200- @Test(groups="short")
198+ @Test(groups = "short")
201199 public void should_init_and_close_policy_on_cluster() {
202200 SpeculativeExecutionPolicy mockPolicy = mock(SpeculativeExecutionPolicy.class);
203201
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +7 −9
@@ -15,17 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.CountDownLatch;
19-
20-import static java.util.concurrent.TimeUnit.MINUTES;
21-
2218 import org.slf4j.Logger;
2319 import org.slf4j.LoggerFactory;
2420 import org.testng.annotations.Test;
2521
26-import static org.assertj.core.api.Assertions.assertThat;
22+import java.util.concurrent.CountDownLatch;
2723
2824 import static com.datastax.driver.core.StateListenerTest.TestListener.Event.*;
25+import static java.util.concurrent.TimeUnit.MINUTES;
26+import static org.assertj.core.api.Assertions.assertThat;
2927
3028 public class StateListenerTest {
3129 private static final Logger logger = LoggerFactory.getLogger(StateListenerTest.class);
@@ -37,8 +35,8 @@
3735 try {
3836 ccm = CCMBridge.builder("test").build();
3937 cluster = Cluster.builder()
40- .addContactPoint(CCMBridge.ipOfNode(1))
41- .build();
38+ .addContactPoint(CCMBridge.ipOfNode(1))
39+ .build();
4240 cluster.init();
4341 TestListener listener = new TestListener();
4442 cluster.register(listener);
@@ -82,8 +80,8 @@
8280
8381 void waitForEvent() throws InterruptedException {
8482 assertThat(latch.await(2, MINUTES))
85- .as("Timed out waiting for event " + expectedEvent)
86- .isTrue();
83+ .as("Timed out waiting for event " + expectedEvent)
84+ .isTrue();
8785 assertThat(actualEvent).isEqualTo(expectedEvent);
8886 }
8987
modified driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +52 −54
@@ -15,17 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.querybuilder.BuiltStatement;
1819 import com.google.common.collect.ImmutableList;
1920 import com.google.common.collect.ImmutableMap;
2021 import com.google.common.collect.Lists;
2122 import com.google.common.collect.Sets;
2223 import org.testng.annotations.Test;
2324
24-import static org.assertj.core.api.Assertions.assertThat;
25-
26-import com.datastax.driver.core.querybuilder.BuiltStatement;
27-
2825 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
26+import static org.assertj.core.api.Assertions.assertThat;
2927
3028 public class StatementIdempotenceTest {
3129 @Test(groups = "unit")
@@ -41,7 +39,7 @@
4139 QueryOptions queryOptions = new QueryOptions();
4240 SimpleStatement statement = new SimpleStatement("");
4341
44- for (boolean valueInOptions : new boolean[]{ true, false }) {
42+ for (boolean valueInOptions : new boolean[]{true, false}) {
4543 queryOptions.setDefaultIdempotence(valueInOptions);
4644 assertThat(statement.isIdempotentWithDefault(queryOptions)).isEqualTo(valueInOptions);
4745 }
@@ -52,8 +50,8 @@
5250 QueryOptions queryOptions = new QueryOptions();
5351 SimpleStatement statement = new SimpleStatement("");
5452
55- for (boolean valueInOptions : new boolean[]{ true, false })
56- for (boolean valueInStatement : new boolean[]{ true, false }) {
53+ for (boolean valueInOptions : new boolean[]{true, false})
54+ for (boolean valueInStatement : new boolean[]{true, false}) {
5755 queryOptions.setDefaultIdempotence(valueInOptions);
5856 statement.setIdempotent(valueInStatement);
5957 assertThat(statement.isIdempotentWithDefault(queryOptions)).isEqualTo(valueInStatement);
@@ -64,18 +62,18 @@
6462 public void should_infer_for_built_statement() {
6563 for (BuiltStatement statement : idempotentBuiltStatements())
6664 assertThat(statement.isIdempotent())
67- .as(statement.getQueryString())
68- .isTrue();
65+ .as(statement.getQueryString())
66+ .isTrue();
6967
7068 for (BuiltStatement statement : nonIdempotentBuiltStatements())
7169 assertThat(statement.isIdempotent())
72- .as(statement.getQueryString())
73- .isFalse();
70+ .as(statement.getQueryString())
71+ .isFalse();
7472 }
7573
7674 @Test(groups = "unit")
7775 public void should_override_inferred_value_when_manually_set_on_built_statement() {
78- for (boolean manualValue : new boolean[]{ true, false }) {
76+ for (boolean manualValue : new boolean[]{true, false}) {
7977 for (BuiltStatement statement : idempotentBuiltStatements()) {
8078 statement.setIdempotent(manualValue);
8179 assertThat(statement.isIdempotent()).isEqualTo(manualValue);
@@ -90,66 +88,66 @@
9088
9189 private static ImmutableList<BuiltStatement> idempotentBuiltStatements() {
9290 return ImmutableList.<BuiltStatement>of(
93- update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value
94- update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set
95- update("foo").with(put("m", "a", 1)).where(eq("k", 1)), // put in map
96-
97- // select statements should be idempotent even with function calls
98- select().countAll() .from("foo").where(eq("k", 1)),
99- select().ttl("v") .from("foo").where(eq("k", 1)),
100- select().writeTime("v") .from("foo").where(eq("k", 1)),
101- select().fcall("token", "k").from("foo").where(eq("k", 1))
91+ update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value
92+ update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set
93+ update("foo").with(put("m", "a", 1)).where(eq("k", 1)), // put in map
94+
95+ // select statements should be idempotent even with function calls
96+ select().countAll().from("foo").where(eq("k", 1)),
97+ select().ttl("v").from("foo").where(eq("k", 1)),
98+ select().writeTime("v").from("foo").where(eq("k", 1)),
99+ select().fcall("token", "k").from("foo").where(eq("k", 1))
102100
103101 );
104102 }
105103
106104 private static ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() {
107105 return ImmutableList.of(
108- update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list
109- update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list
110- update("foo").with(incr("c")).where(eq("k", 1)), // counter update
106+ update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list
107+ update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list
108+ update("foo").with(incr("c")).where(eq("k", 1)), // counter update
111109
112- // function calls
110+ // function calls
113111
114- insertInto("foo").value("k", 1).value("v", fcall("token", "k")),
115- insertInto("foo").value("k", 1).value("v", now()),
116- insertInto("foo").value("k", 1).value("v", uuid()),
112+ insertInto("foo").value("k", 1).value("v", fcall("token", "k")),
113+ insertInto("foo").value("k", 1).value("v", now()),
114+ insertInto("foo").value("k", 1).value("v", uuid()),
117115
118- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(fcall("token", "k"))),
119- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(now())),
120- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(uuid())),
116+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(fcall("token", "k"))),
117+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(now())),
118+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(uuid())),
121119
122- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, fcall("token", "k")}),
123- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, now()}),
124- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, uuid()}),
120+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, fcall("token", "k")}),
121+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, now()}),
122+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, uuid()}),
125123
126- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", fcall("token", "k"))}),
127- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", now())}),
128- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", uuid())}),
124+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", fcall("token", "k"))}),
125+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", now())}),
126+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", uuid())}),
129127
130- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(fcall("token", "k"), "foo")}),
131- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(now() , "foo")}),
132- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(uuid() , "foo")}),
128+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(fcall("token", "k"), "foo")}),
129+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(now(), "foo")}),
130+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(uuid(), "foo")}),
133131
134- update("foo").with(set("v", fcall("token", "k"))) .where(eq("k", 1)),
135- update("foo").with(set("v", now())) .where(eq("k", 1)),
136- update("foo").with(set("v", uuid())) .where(eq("k", 1)),
132+ update("foo").with(set("v", fcall("token", "k"))).where(eq("k", 1)),
133+ update("foo").with(set("v", now())).where(eq("k", 1)),
134+ update("foo").with(set("v", uuid())).where(eq("k", 1)),
137135
138- update("foo").with(set("v", Lists.newArrayList(fcall("token", "k")))).where(eq("k", 1)),
139- update("foo").with(set("v", Lists.newArrayList(now()))) .where(eq("k", 1)),
140- update("foo").with(set("v", Lists.newArrayList(uuid()))) .where(eq("k", 1)),
136+ update("foo").with(set("v", Lists.newArrayList(fcall("token", "k")))).where(eq("k", 1)),
137+ update("foo").with(set("v", Lists.newArrayList(now()))).where(eq("k", 1)),
138+ update("foo").with(set("v", Lists.newArrayList(uuid()))).where(eq("k", 1)),
141139
142- // raw() calls
140+ // raw() calls
143141
144- insertInto("foo").value("k", 1).value("v", raw("foo()")),
145- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(raw("foo()"))),
142+ insertInto("foo").value("k", 1).value("v", raw("foo()")),
143+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(raw("foo()"))),
146144
147- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, raw("foo()")}),
148- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", raw("foo()"))}),
149- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(raw("foo()"), "foo")}),
145+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, raw("foo()")}),
146+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", raw("foo()"))}),
147+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(raw("foo()"), "foo")}),
150148
151- update("foo").with(set("v", raw("foo()"))) .where(eq("k", 1)),
152- update("foo").with(set("v", Lists.newArrayList(raw("foo()")))).where(eq("k", 1))
149+ update("foo").with(set("v", raw("foo()"))).where(eq("k", 1)),
150+ update("foo").with(set("v", Lists.newArrayList(raw("foo()")))).where(eq("k", 1))
153151
154152 );
155153 }
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +20 −13
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.policies.*;
19+import com.google.common.collect.Lists;
20+import org.testng.annotations.Test;
21+
1822 import java.util.Collection;
1923 import java.util.Iterator;
2024 import java.util.concurrent.atomic.AtomicInteger;
2125
22-import com.google.common.collect.Lists;
23-import org.testng.annotations.Test;
24-
2526 import static org.assertj.core.api.Assertions.assertThat;
2627
27-import com.datastax.driver.core.policies.*;
28-
2928 public class StatementWrapperTest extends CCMBridge.PerClassSingleNodeCluster {
3029 @Override
3130 protected Collection<String> getTableDefinitions() {
@@ -39,9 +38,9 @@
3938 @Override
4039 protected Cluster.Builder configure(Cluster.Builder builder) {
4140 return builder
42- .withLoadBalancingPolicy(loadBalancingPolicy)
43- .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
44- .withRetryPolicy(retryPolicy);
41+ .withLoadBalancingPolicy(loadBalancingPolicy)
42+ .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
43+ .withRetryPolicy(retryPolicy);
4544 }
4645
4746 @Test(groups = "short")
@@ -75,7 +74,7 @@
7574 // Set CL TWO with only one node, so the statement will always cause UNAVAILABLE,
7675 // which our custom policy ignores.
7776 Statement s = new SimpleStatement("select * from system.local")
78- .setConsistencyLevel(ConsistencyLevel.TWO);
77+ .setConsistencyLevel(ConsistencyLevel.TWO);
7978
8079 session.execute(s);
8180 assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(0);
@@ -84,14 +83,18 @@
8483 assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(1);
8584 }
8685
87- /** A custom wrapper that's just used to mark statements. */
86+ /**
87+ * A custom wrapper that's just used to mark statements.
88+ */
8889 static class CustomStatement extends StatementWrapper {
8990 protected CustomStatement(Statement wrapped) {
9091 super(wrapped);
9192 }
9293 }
9394
94- /** A load balancing policy that counts how many times it has seen the custom wrapper */
95+ /**
96+ * A load balancing policy that counts how many times it has seen the custom wrapper
97+ */
9598 static class CustomLoadBalancingPolicy extends DelegatingLoadBalancingPolicy {
9699 final AtomicInteger customStatementsHandled = new AtomicInteger();
97100
@@ -107,7 +110,9 @@
107110 }
108111 }
109112
110- /** A speculative execution policy that counts how many times it has seen the custom wrapper */
113+ /**
114+ * A speculative execution policy that counts how many times it has seen the custom wrapper
115+ */
111116 static class CustomSpeculativeExecutionPolicy extends DelegatingSpeculativeExecutionPolicy {
112117 final AtomicInteger customStatementsHandled = new AtomicInteger();
113118
@@ -123,7 +128,9 @@
123128 }
124129 }
125130
126- /** A retry policy that counts how many times it has seen the custom wrapper for UNAVAILABLE errors. */
131+ /**
132+ * A retry policy that counts how many times it has seen the custom wrapper for UNAVAILABLE errors.
133+ */
127134 static class CustomRetryPolicy implements RetryPolicy {
128135 final AtomicInteger customStatementsHandled = new AtomicInteger();
129136
modified driver-core/src/test/java/com/datastax/driver/core/StreamIdGeneratorTest.java +1 −0
@@ -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 import static org.testng.Assert.fail;
2122
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +8 −8
@@ -15,29 +15,29 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
2018 import com.google.common.collect.Lists;
2119 import org.testng.annotations.Test;
2220
21+import java.util.Collection;
22+
2323 import static org.assertj.core.api.Assertions.assertThat;
2424
2525 public class TableMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
2626 @Override
2727 protected Collection<String> getTableDefinitions() {
2828 return Lists.newArrayList(
29- "CREATE TABLE single_quote (\n"
30- + " c1 int PRIMARY KEY\n"
31- + ") WITH comment = 'comment with single quote '' should work'"
29+ "CREATE TABLE single_quote (\n"
30+ + " c1 int PRIMARY KEY\n"
31+ + ") WITH comment = 'comment with single quote '' should work'"
3232 );
3333 }
3434
3535 @Override
3636 protected Cluster.Builder configure(Cluster.Builder builder) {
3737 return builder.withQueryOptions(new QueryOptions()
38- .setRefreshNodeIntervalMillis(0)
39- .setRefreshNodeListIntervalMillis(0)
40- .setRefreshSchemaIntervalMillis(0)
38+ .setRefreshNodeIntervalMillis(0)
39+ .setRefreshNodeListIntervalMillis(0)
40+ .setRefreshSchemaIntervalMillis(0)
4141 );
4242 }
4343
modified driver-core/src/test/java/com/datastax/driver/core/TestListener.java +12 −12
@@ -15,15 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.CassandraVersion;
1819 import org.testng.*;
1920 import org.testng.internal.ConstructorOrMethod;
2021
21-import java.lang.annotation.Annotation;
2222 import java.lang.reflect.Method;
2323 import java.util.concurrent.TimeUnit;
2424
25-import com.datastax.driver.core.utils.CassandraVersion;
26-
2725 public class TestListener extends TestListenerAdapter implements IInvokedMethodListener {
2826
2927 private long start_time = System.nanoTime();
@@ -74,16 +72,17 @@
7472
7573 static String formatIntoHHMMSS(long secondsTotal) {
7674 long hours = secondsTotal / 3600,
77- remainder = secondsTotal % 3600,
78- minutes = remainder / 60,
79- seconds = remainder % 60;
75+ remainder = secondsTotal % 3600,
76+ minutes = remainder / 60,
77+ seconds = remainder % 60;
8078
8179 return ((hours < 10 ? "0" : "") + hours
82- + ':' + (minutes < 10 ? "0" : "") + minutes
83- + ':' + (seconds< 10 ? "0" : "") + seconds);
80+ + ':' + (minutes < 10 ? "0" : "") + minutes
81+ + ':' + (seconds < 10 ? "0" : "") + seconds);
8482 }
8583
86- @Override public void beforeInvocation(IInvokedMethod testMethod, ITestResult testResult) {
84+ @Override
85+ public void beforeInvocation(IInvokedMethod testMethod, ITestResult testResult) {
8786 // Check to see if the class or method is annotated with 'CassandraVersion', if so ensure the
8887 // version we are testing with meets the requirement, if not a SkipException is thrown
8988 // and this test is skipped.
@@ -91,19 +90,20 @@
9190 ConstructorOrMethod constructorOrMethod = testNgMethod.getConstructorOrMethod();
9291
9392 Class<?> clazz = testNgMethod.getInstance().getClass();
94- if(clazz != null && clazz.isAnnotationPresent(CassandraVersion.class)) {
93+ if (clazz != null && clazz.isAnnotationPresent(CassandraVersion.class)) {
9594 CassandraVersion cassandraVersion = clazz.getAnnotation(CassandraVersion.class);
9695 TestUtils.versionCheck(cassandraVersion.major(), cassandraVersion.minor(), cassandraVersion.description());
9796 }
9897
9998 Method method = constructorOrMethod.getMethod();
100- if(method != null && method.isAnnotationPresent(CassandraVersion.class)) {
99+ if (method != null && method.isAnnotationPresent(CassandraVersion.class)) {
101100 CassandraVersion cassandraVersion = method.getAnnotation(CassandraVersion.class);
102101 TestUtils.versionCheck(cassandraVersion.major(), cassandraVersion.minor(), cassandraVersion.description());
103102 }
104103 }
105104
106- @Override public void afterInvocation(IInvokedMethod testMethod, ITestResult testResult) {
105+ @Override
106+ public void afterInvocation(IInvokedMethod testMethod, ITestResult testResult) {
107107 // Do nothing
108108 }
109109 }
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +73 −56
@@ -15,6 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.policies.RoundRobinPolicy;
19+import com.datastax.driver.core.policies.WhiteListPolicy;
20+import com.google.common.util.concurrent.Futures;
21+import com.google.common.util.concurrent.Uninterruptibles;
22+import io.netty.channel.EventLoopGroup;
23+import org.scassandra.Scassandra;
24+import org.scassandra.ScassandraFactory;
25+import org.slf4j.Logger;
26+import org.slf4j.LoggerFactory;
27+import org.testng.SkipException;
28+
1829 import java.io.IOException;
1930 import java.math.BigDecimal;
2031 import java.math.BigInteger;
@@ -26,18 +37,6 @@
2637 import java.util.concurrent.CountDownLatch;
2738 import java.util.concurrent.TimeUnit;
2839
29-import com.google.common.util.concurrent.Futures;
30-import com.google.common.util.concurrent.Uninterruptibles;
31-import io.netty.channel.EventLoopGroup;
32-import org.scassandra.Scassandra;
33-import org.scassandra.ScassandraFactory;
34-import org.slf4j.Logger;
35-import org.slf4j.LoggerFactory;
36-import org.testng.SkipException;
37-
38-import com.datastax.driver.core.policies.RoundRobinPolicy;
39-import com.datastax.driver.core.policies.WhiteListPolicy;
40-
4140 /**
4241 * A number of static fields/methods handy for tests.
4342 */
@@ -58,65 +57,65 @@
5857
5958 public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60);
6059
61- @SuppressWarnings({ "unchecked", "rawtypes" })
60+ @SuppressWarnings({"unchecked", "rawtypes"})
6261 public static BoundStatement setBoundValue(BoundStatement bs, String name, DataType type, Object value) {
6362 switch (type.getName()) {
6463 case ASCII:
65- bs.setString(name, (String)value);
64+ bs.setString(name, (String) value);
6665 break;
6766 case BIGINT:
68- bs.setLong(name, (Long)value);
67+ bs.setLong(name, (Long) value);
6968 break;
7069 case BLOB:
71- bs.setBytes(name, (ByteBuffer)value);
70+ bs.setBytes(name, (ByteBuffer) value);
7271 break;
7372 case BOOLEAN:
74- bs.setBool(name, (Boolean)value);
73+ bs.setBool(name, (Boolean) value);
7574 break;
7675 case COUNTER:
7776 // Just a no-op, we shouldn't handle counters the same way than other types
7877 break;
7978 case DECIMAL:
80- bs.setDecimal(name, (BigDecimal)value);
79+ bs.setDecimal(name, (BigDecimal) value);
8180 break;
8281 case DOUBLE:
83- bs.setDouble(name, (Double)value);
82+ bs.setDouble(name, (Double) value);
8483 break;
8584 case FLOAT:
86- bs.setFloat(name, (Float)value);
85+ bs.setFloat(name, (Float) value);
8786 break;
8887 case INET:
89- bs.setInet(name, (InetAddress)value);
88+ bs.setInet(name, (InetAddress) value);
9089 break;
9190 case INT:
92- bs.setInt(name, (Integer)value);
91+ bs.setInt(name, (Integer) value);
9392 break;
9493 case TEXT:
95- bs.setString(name, (String)value);
94+ bs.setString(name, (String) value);
9695 break;
9796 case TIMESTAMP:
98- bs.setDate(name, (Date)value);
97+ bs.setDate(name, (Date) value);
9998 break;
10099 case UUID:
101- bs.setUUID(name, (UUID)value);
100+ bs.setUUID(name, (UUID) value);
102101 break;
103102 case VARCHAR:
104- bs.setString(name, (String)value);
103+ bs.setString(name, (String) value);
105104 break;
106105 case VARINT:
107- bs.setVarint(name, (BigInteger)value);
106+ bs.setVarint(name, (BigInteger) value);
108107 break;
109108 case TIMEUUID:
110- bs.setUUID(name, (UUID)value);
109+ bs.setUUID(name, (UUID) value);
111110 break;
112111 case LIST:
113- bs.setList(name, (List)value);
112+ bs.setList(name, (List) value);
114113 break;
115114 case SET:
116- bs.setSet(name, (Set)value);
115+ bs.setSet(name, (Set) value);
117116 break;
118117 case MAP:
119- bs.setMap(name, (Map)value);
118+ bs.setMap(name, (Map) value);
120119 break;
121120 default:
122121 throw new RuntimeException("Missing handling of " + type);
@@ -178,7 +177,7 @@
178177 case BIGINT:
179178 return 42L;
180179 case BLOB:
181- return ByteBuffer.wrap(new byte[]{ (byte)4, (byte)12, (byte)1 });
180+ return ByteBuffer.wrap(new byte[]{(byte) 4, (byte) 12, (byte) 1});
182181 case BOOLEAN:
183182 return true;
184183 case COUNTER:
@@ -190,7 +189,7 @@
190189 case FLOAT:
191190 return 3.142519f;
192191 case INET:
193- return InetAddress.getByAddress(new byte[]{ (byte)127, (byte)0, (byte)0, (byte)1 });
192+ return InetAddress.getByAddress(new byte[]{(byte) 127, (byte) 0, (byte) 0, (byte) 1});
194193 case INT:
195194 return 24;
196195 case TEXT:
@@ -206,11 +205,17 @@
206205 case TIMEUUID:
207206 return UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66");
208207 case LIST:
209- return new ArrayList<Object>(){{ add(getFixedValue(type.getTypeArguments().get(0))); }};
208+ return new ArrayList<Object>() {{
209+ add(getFixedValue(type.getTypeArguments().get(0)));
210+ }};
210211 case SET:
211- return new HashSet<Object>(){{ add(getFixedValue(type.getTypeArguments().get(0))); }};
212+ return new HashSet<Object>() {{
213+ add(getFixedValue(type.getTypeArguments().get(0)));
214+ }};
212215 case MAP:
213- return new HashMap<Object, Object>(){{ put(getFixedValue(type.getTypeArguments().get(0)), getFixedValue(type.getTypeArguments().get(1))); }};
216+ return new HashMap<Object, Object>() {{
217+ put(getFixedValue(type.getTypeArguments().get(0)), getFixedValue(type.getTypeArguments().get(1)));
218+ }};
214219 }
215220 } catch (Exception e) {
216221 throw new RuntimeException(e);
@@ -260,11 +265,17 @@
260265 case TIMEUUID:
261266 return UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66");
262267 case LIST:
263- return new ArrayList<Object>(){{ add(getFixedValue2(type.getTypeArguments().get(0))); }};
268+ return new ArrayList<Object>() {{
269+ add(getFixedValue2(type.getTypeArguments().get(0)));
270+ }};
264271 case SET:
265- return new HashSet<Object>(){{ add(getFixedValue2(type.getTypeArguments().get(0))); }};
272+ return new HashSet<Object>() {{
273+ add(getFixedValue2(type.getTypeArguments().get(0)));
274+ }};
266275 case MAP:
267- return new HashMap<Object, Object>(){{ put(getFixedValue2(type.getTypeArguments().get(0)), getFixedValue2(type.getTypeArguments().get(1))); }};
276+ return new HashMap<Object, Object>() {{
277+ put(getFixedValue2(type.getTypeArguments().get(0)), getFixedValue2(type.getTypeArguments().get(1)));
278+ }};
268279 }
269280 } catch (Exception e) {
270281 throw new RuntimeException(e);
@@ -321,8 +332,8 @@
321332 logger.info("Waiting for stopped node: " + node);
322333 else if (waitForOut)
323334 logger.info("Waiting for decommissioned node: " + node);
324- else
325- logger.info("Waiting for upcoming node: " + node);
335+ else
336+ logger.info("Waiting for upcoming node: " + node);
326337
327338 // In the case where the we've killed the last node in the cluster, if we haven't
328339 // tried doing an actual query, the driver won't realize that last node is dead until
@@ -334,7 +345,7 @@
334345
335346 InetAddress address;
336347 try {
337- address = InetAddress.getByName(node);
348+ address = InetAddress.getByName(node);
338349 } catch (Exception e) {
339350 // That's a problem but that's not *our* problem
340351 return;
@@ -344,11 +355,17 @@
344355 for (int i = 0; i < maxTry; ++i) {
345356 for (Host host : metadata.getAllHosts()) {
346357 if (host.getAddress().equals(address) && testHost(host, waitForDead)) {
347- try { Thread.sleep(10000); } catch (Exception e) {}
358+ try {
359+ Thread.sleep(10000);
360+ } catch (Exception e) {
361+ }
348362 return;
349363 }
350364 }
351- try { Thread.sleep(1000); } catch (Exception e) {}
365+ try {
366+ Thread.sleep(1000);
367+ } catch (Exception e) {
368+ }
352369 }
353370
354371 for (Host host : metadata.getAllHosts()) {
@@ -363,7 +380,7 @@
363380 }
364381 }
365382
366- if (waitForOut){
383+ if (waitForOut) {
367384 return;
368385 } else {
369386 logger.info(node + " is not part of the cluster after " + maxTry + 's');
@@ -392,12 +409,12 @@
392409
393410 public static Host findOrWaitForHost(final Cluster cluster, final String address, long duration, TimeUnit unit) {
394411 Host host = findHost(cluster, address);
395- if(host == null) {
412+ if (host == null) {
396413 final CountDownLatch addSignal = new CountDownLatch(1);
397414 Host.StateListener addListener = new StateListenerBase() {
398415 @Override
399416 public void onAdd(Host host) {
400- if(host.getAddress().getHostAddress().equals(address)) {
417+ if (host.getAddress().getHostAddress().equals(address)) {
401418 // for a new node, because of this we also listen for add events.
402419 addSignal.countDown();
403420 }
@@ -437,8 +454,8 @@
437454 ControlConnection controlConnection = cluster.manager.controlConnection;
438455 long durationNs = TimeUnit.NANOSECONDS.convert(duration, unit);
439456 long start = System.nanoTime();
440- while(System.nanoTime() - start < durationNs) {
441- if(controlConnection.isOpen()) {
457+ while (System.nanoTime() - start < durationNs) {
458+ if (controlConnection.isOpen()) {
442459 return controlConnection.connectedHost();
443460 }
444461 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
@@ -447,7 +464,7 @@
447464 }
448465
449466 public static HostConnectionPool poolOf(Session session, int hostNumber) {
450- SessionManager sessionManager = (SessionManager)session;
467+ SessionManager sessionManager = (SessionManager) session;
451468 return sessionManager.pools.get(findHost(session.getCluster(), hostNumber));
452469 }
453470
@@ -493,7 +510,7 @@
493510 String version = System.getProperty("cassandra.version");
494511 String[] versionArray = version.split("\\.|-");
495512 double major = Double.parseDouble(versionArray[0] + "." + versionArray[1]);
496- if(major < 2.0) {
513+ if (major < 2.0) {
497514 return ProtocolVersion.V1;
498515 } else if (major < 2.1) {
499516 return ProtocolVersion.V2;
@@ -509,9 +526,9 @@
509526 Host controlHost = cluster.manager.controlConnection.connectedHost();
510527 List<InetSocketAddress> singleAddress = Collections.singletonList(controlHost.getSocketAddress());
511528 return Cluster.builder()
512- .addContactPointsWithPorts(singleAddress)
513- .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
514- .build();
529+ .addContactPointsWithPorts(singleAddress)
530+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
531+ .build();
515532 }
516533
517534 /**
@@ -519,8 +536,8 @@
519536 */
520537 public static QueryOptions nonDebouncingQueryOptions() {
521538 return new QueryOptions().setRefreshNodeIntervalMillis(0)
522- .setRefreshNodeListIntervalMillis(0)
523- .setRefreshSchemaIntervalMillis(0);
539+ .setRefreshNodeListIntervalMillis(0)
540+ .setRefreshSchemaIntervalMillis(0);
524541 }
525542
526543 /**
modified driver-core/src/test/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGeneratorTest.java +17 −18
@@ -15,20 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-import java.util.concurrent.ExecutionException;
20-import java.util.concurrent.Executors;
21-import java.util.concurrent.TimeUnit;
22-
2318 import com.google.common.collect.Lists;
2419 import com.google.common.util.concurrent.Futures;
2520 import com.google.common.util.concurrent.ListenableFuture;
2621 import com.google.common.util.concurrent.ListeningExecutorService;
2722 import com.google.common.util.concurrent.MoreExecutors;
2823 import org.testng.annotations.Test;
29-import static org.testng.Assert.assertEquals;
30-import static org.testng.Assert.assertTrue;
31-import static org.testng.Assert.fail;
24+
25+import java.util.List;
26+import java.util.concurrent.ExecutionException;
27+import java.util.concurrent.Executors;
28+import java.util.concurrent.TimeUnit;
29+
30+import static org.testng.Assert.*;
3231
3332 public class ThreadLocalMonotonicTimestampGeneratorTest {
3433
@@ -46,15 +45,15 @@
4645 List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(testThreadsCount);
4746 for (int i = 0; i < testThreadsCount; i++) {
4847 futures.add(executor.submit(
49- new Runnable() {
50- @Override
51- public void run() {
52- // Ensure that each thread gets the 1000 microseconds for the mocked millisecond value,
53- // in order
54- for (int i = 0; i < 1000; i++)
55- assertEquals(generator.next(), fixedTime * 1000 + i);
56- }
57- }));
48+ new Runnable() {
49+ @Override
50+ public void run() {
51+ // Ensure that each thread gets the 1000 microseconds for the mocked millisecond value,
52+ // in order
53+ for (int i = 0; i < 1000; i++)
54+ assertEquals(generator.next(), fixedTime * 1000 + i);
55+ }
56+ }));
5857 }
5958 executor.shutdown();
6059 executor.awaitTermination(1, TimeUnit.SECONDS);
@@ -64,7 +63,7 @@
6463 } catch (ExecutionException e) {
6564 Throwable cause = e.getCause();
6665 if (cause instanceof AssertionError)
67- throw (AssertionError)cause;
66+ throw (AssertionError) cause;
6867 else
6968 fail("Error in a test thread", cause);
7069 }
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +23 −23
@@ -74,9 +74,9 @@
7474 ccmBridge = CCMBridge.builder("test").withNodes(3).build();
7575 channelMonitor = new SocketChannelMonitor();
7676 nodes = Lists.newArrayList(
77- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
78- new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042),
79- new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
77+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
78+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042),
79+ new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
8080 );
8181
8282 PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, 8, 8);
@@ -91,33 +91,33 @@
9191
9292 @AfterClass(groups = "stress")
9393 public void afterClass() {
94- if(ccmBridge != null) {
94+ if (ccmBridge != null) {
9595 ccmBridge.stop();
9696 }
97- if(channelMonitor != null) {
97+ if (channelMonitor != null) {
9898 channelMonitor.stop();
9999 }
100- if(cluster != null) {
100+ if (cluster != null) {
101101 cluster.close();
102102 }
103103 }
104104
105105 /**
106- * <p>
106+ * <p/>
107107 * Validates that under extreme timeout conditions the driver is able to properly maintain connection pools in
108108 * addition to not leaking connections.
109- *
110- * <p>
109+ * <p/>
110+ * <p/>
111111 * Does the following:
112112 * <ol>
113- * <li>Creates a table and loads 30k rows in a single partition.</li>
114- * <li>Sets the connection and read timeout {@link SocketOptions} to very low values.</li>
115- * <li>Spawns workers that concurrently execute queries.</li>
116- * <li>For some duration, repeatedly measures number of open socket connections and warns if exceeded.</li>
117- * <li>After a duration, resets {@link SocketOptions} to defaults.</li>
118- * <li>Wait for 20 seconds for reaper to remove old connections and restore pools.</li>
119- * <li>Ensure pools are restored.</li>
120- * <li>Shutdown session and ensure that there remains only 1 open connection.</li>
113+ * <li>Creates a table and loads 30k rows in a single partition.</li>
114+ * <li>Sets the connection and read timeout {@link SocketOptions} to very low values.</li>
115+ * <li>Spawns workers that concurrently execute queries.</li>
116+ * <li>For some duration, repeatedly measures number of open socket connections and warns if exceeded.</li>
117+ * <li>After a duration, resets {@link SocketOptions} to defaults.</li>
118+ * <li>Wait for 20 seconds for reaper to remove old connections and restore pools.</li>
119+ * <li>Ensure pools are restored.</li>
120+ * <li>Shutdown session and ensure that there remains only 1 open connection.</li>
121121 * </ol>
122122 *
123123 * @test_category connection:connection_pool
@@ -163,7 +163,7 @@
163163
164164 // Ensure that we don't exceed maximum connections. Log as warning as there will be a bit of a timing
165165 // factor between retrieving open connections and checking the reaper.
166- if(openChannels.size() > maxConnections) {
166+ if (openChannels.size() > maxConnections) {
167167 logger.warn("{} of open channels: {} exceeds maximum expected: {}. " +
168168 "This could be because there are connections to be cleaned up in the reaper.",
169169 openChannels.size(), maxConnections, openChannels);
@@ -179,7 +179,7 @@
179179 .setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
180180
181181 logger.debug("Sleeping 20 seconds to allow connection reaper to clean up connections " +
182- "and for the pools to recover.");
182+ "and for the pools to recover.");
183183 Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
184184
185185 Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
@@ -249,7 +249,7 @@
249249 @Override
250250 public void run() {
251251
252- while(!stopped.get()) {
252+ while (!stopped.get()) {
253253 try {
254254 concurrentQueries.acquire();
255255 ResultSetFuture future = session.executeAsync(statement.bind("0"));
@@ -258,21 +258,21 @@
258258 @Override
259259 public void onSuccess(ResultSet result) {
260260 concurrentQueries.release();
261- if(executedQueries.incrementAndGet() % 1000 == 0)
261+ if (executedQueries.incrementAndGet() % 1000 == 0)
262262 logger.debug("Successfully executed {}. rows: {}", executedQueries.get(), result.getAvailableWithoutFetching());
263263 }
264264
265265 @Override
266266 public void onFailure(Throwable t) {
267267 concurrentQueries.release();
268- if(t instanceof NoHostAvailableException) {
268+ if (t instanceof NoHostAvailableException) {
269269 //logger.error("NHAE: {}", t.getMessage());
270270 } else {
271271 //logger.error("Exception", t);
272272 }
273273 }
274274 });
275- } catch(Exception e) {
275+ } catch (Exception e) {
276276 logger.error("Failure while submitting query.", e);
277277 }
278278 }
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 +20 −15
@@ -15,19 +15,18 @@
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.testng.Assert.assertEquals;
2627 import static org.testng.Assert.fail;
2728
28-import com.datastax.driver.core.utils.CassandraVersion;
29-
30-@CassandraVersion(major=2.1)
29+@CassandraVersion(major = 2.1)
3130 public class TupleTest extends CCMBridge.PerClassSingleNodeCluster {
3231
3332 @Override
@@ -89,13 +88,14 @@
8988 /**
9089 * Basic test of tuple functionality.
9190 * Original code found in python-driver:integration.standard.test_types.py:test_tuple_type
91+ *
9292 * @throws Exception
9393 */
9494 @Test(groups = "short")
9595 public void tupleTypeTest() throws Exception {
9696 try {
9797 session.execute("CREATE KEYSPACE test_tuple_type " +
98- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
98+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
9999 session.execute("USE test_tuple_type");
100100 session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)");
101101
@@ -111,7 +111,8 @@
111111 try {
112112 TupleValue partial = t.newValue("bar", 456);
113113 fail();
114- } catch (IllegalArgumentException e) {}
114+ } catch (IllegalArgumentException e) {
115+ }
115116
116117 // test incomplete tuples with new TupleType
117118 TupleType t1 = TupleType.of(DataType.ascii(), DataType.cint());
@@ -125,7 +126,8 @@
125126 try {
126127 TupleValue subpartial = t.newValue("zoo");
127128 fail();
128- } catch (IllegalArgumentException e) {}
129+ } catch (IllegalArgumentException e) {
130+ }
129131
130132 // test single value tuples with new TupleType
131133 TupleType t2 = TupleType.of(DataType.ascii());
@@ -163,7 +165,7 @@
163165 public void tupleTestTypeVaryingLengths() throws Exception {
164166 try {
165167 session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " +
166- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
168+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
167169 session.execute("USE test_tuple_type_varying_lengths");
168170
169171 // programmatically create the table with tuples of said sizes
@@ -218,7 +220,7 @@
218220
219221 try {
220222 session.execute("CREATE KEYSPACE test_tuple_subtypes " +
221- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
223+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
222224 session.execute("USE test_tuple_subtypes");
223225
224226 // programmatically create the table with a tuple of all datatypes
@@ -284,7 +286,7 @@
284286
285287 try {
286288 session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " +
287- "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
289+ "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}");
288290 session.execute("USE test_tuple_non_primitive_subtypes");
289291
290292 ArrayList<String> values = new ArrayList<String>();
@@ -388,6 +390,7 @@
388390
389391 /**
390392 * Helper method for creating nested tuple schema
393+ *
391394 * @param depth
392395 * @return
393396 */
@@ -400,6 +403,7 @@
400403
401404 /**
402405 * Helper method for creating nested tuples
406+ *
403407 * @param depth
404408 * @return
405409 */
@@ -435,9 +439,9 @@
435439 "v_2 %s, " +
436440 "v_3 %s, " +
437441 "v_128 %s)", nestedTuplesSchemaHelper(1),
438- nestedTuplesSchemaHelper(2),
439- nestedTuplesSchemaHelper(3),
440- nestedTuplesSchemaHelper(128)));
442+ nestedTuplesSchemaHelper(2),
443+ nestedTuplesSchemaHelper(3),
444+ nestedTuplesSchemaHelper(128)));
441445
442446 for (int i : Arrays.asList(1, 2, 3, 128)) {
443447 // create tuple
@@ -461,6 +465,7 @@
461465 /**
462466 * Test for inserting null Tuple values into UDT's
463467 * Original code found in python-driver:integration.standard.test_types.py:test_tuples_with_nulls
468+ *
464469 * @throws Exception
465470 */
466471 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java +8 −9
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Map;
20-import java.util.Collections;
21-import java.util.List;
22-
23-import com.google.common.collect.Lists;
2418 import com.google.common.base.Strings;
25-
19+import com.google.common.collect.Lists;
2620 import org.testng.Assert;
2721 import org.testng.annotations.Test;
2822
23+import java.nio.ByteBuffer;
24+import java.util.Collections;
25+import java.util.List;
26+import java.util.Map;
27+
2928 import static com.datastax.driver.core.DataType.text;
3029
3130 public class TypeCodecTest {
@@ -56,7 +55,7 @@
5655 Assert.assertNotNull(mapType);
5756 }
5857
59- @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
58+ @Test(groups = "unit", expectedExceptions = {IllegalArgumentException.class})
6059 public void collectionTooLargeTest() throws Exception {
6160 TypeCodec<List<Integer>> listType = TypeCodec.listOf(DataType.cint(), ProtocolVersion.V2);
6261 List<Integer> list = Collections.nCopies(65536, 1);
@@ -64,7 +63,7 @@
6463 listType.serialize(list);
6564 }
6665
67- @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
66+ @Test(groups = "unit", expectedExceptions = {IllegalArgumentException.class})
6867 public void collectionElementTooLargeTest() throws Exception {
6968 TypeCodec<List<String>> listType = TypeCodec.listOf(DataType.text(), ProtocolVersion.V2);
7069 List<String> list = Lists.newArrayList(Strings.repeat("a", 65536));
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +25 −22
@@ -15,28 +15,25 @@
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());
@@ -89,6 +86,7 @@
8986
9087 /**
9188 * Run simpleWriteReadTest with unprepared requests.
89+ *
9290 * @throws Exception
9391 */
9492 @Test(groups = "short")
@@ -119,6 +117,7 @@
119117
120118 /**
121119 * Test for ensuring udts are defined in a particular keyspace.
120+ *
122121 * @throws Exception
123122 */
124123 @Test(groups = "short")
@@ -163,6 +162,7 @@
163162 /**
164163 * Test for ensuring extra-lengthy udts are handled correctly.
165164 * Original code found in python-driver:integration.standard.test_udts.py:test_udt_sizes
165+ *
166166 * @throws Exception
167167 */
168168 @Test(groups = "short")
@@ -216,6 +216,7 @@
216216 /**
217217 * Test for inserting various types of DATA_TYPE_PRIMITIVES into UDT's.
218218 * Original code found in python-driver:integration.standard.test_udts.py:test_primitive_datatypes
219+ *
219220 * @throws Exception
220221 */
221222 @Test(groups = "short")
@@ -317,6 +318,7 @@
317318 /**
318319 * Test for inserting various types of DATA_TYPE_NON_PRIMITIVE into UDT's
319320 * Original code found in python-driver:integration.standard.test_udts.py:test_nonprimitive_datatypes
321+ *
320322 * @throws Exception
321323 */
322324 @Test(groups = "short")
@@ -336,17 +338,15 @@
336338 for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++)
337339 for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) {
338340 String typeString;
339- if(DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.MAP) {
341+ if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.MAP) {
340342 typeString = (String.format("%s_%s %s<%s, %s>", Character.toString((char) (startIndex + i)),
341343 Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
342344 DATA_TYPE_PRIMITIVES.get(j).getName(), DATA_TYPE_PRIMITIVES.get(j).getName()));
343- }
344- else if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.TUPLE) {
345+ } else if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.TUPLE) {
345346 typeString = (String.format("%s_%s frozen<%s<%s>>", Character.toString((char) (startIndex + i)),
346- Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
347- DATA_TYPE_PRIMITIVES.get(j).getName()));
348- }
349- else {
347+ Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
348+ DATA_TYPE_PRIMITIVES.get(j).getName()));
349+ } else {
350350 typeString = (String.format("%s_%s %s<%s>", Character.toString((char) (startIndex + i)),
351351 Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i),
352352 DATA_TYPE_PRIMITIVES.get(j).getName()));
@@ -368,7 +368,7 @@
368368
369369 String index = Character.toString((char) (startIndex + i)) + "_" + Character.toString((char) (startIndex + j));
370370 Object sampleElement = PrimitiveTypeSamples.ALL.get(dataType);
371- switch(name) {
371+ switch (name) {
372372 case LIST:
373373 alldatatypes.setList(index, Lists.newArrayList(sampleElement));
374374 break;
@@ -405,6 +405,7 @@
405405 /**
406406 * Test for ensuring nested UDT's are handled correctly.
407407 * Original code found in python-driver:integration.standard.test_udts.py:test_nested_registered_udts
408+ *
408409 * @throws Exception
409410 */
410411 @Test(groups = "short")
@@ -421,7 +422,7 @@
421422 session.execute("CREATE TYPE depth_0 (age int, name text)");
422423
423424 for (int i = 1; i <= MAX_NESTING_DEPTH; i++) {
424- session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i-1)));
425+ session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1)));
425426 }
426427
427428 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>," +
@@ -469,6 +470,7 @@
469470 /**
470471 * Test for inserting null values into UDT's
471472 * Original code found in python-driver:integration.standard.test_udts.py:test_udts_with_nulls
473+ *
472474 * @throws Exception
473475 */
474476 @Test(groups = "short")
@@ -522,6 +524,7 @@
522524
523525 /**
524526 * Test for inserting null values into collections of UDT's
527+ *
525528 * @throws Exception
526529 */
527530 @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/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.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(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table)
55+ String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1),
56+ "USE " + keyspace,
57+ String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, 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/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 +20 −26
@@ -15,35 +15,29 @@
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.*;
2119 import com.google.common.collect.ImmutableList;
2220 import com.google.common.collect.ImmutableMap;
2321 import org.mockito.Mockito;
2422 import org.scassandra.Scassandra;
2523 import org.scassandra.http.client.PrimingRequest;
26-import org.testng.annotations.AfterClass;
2724 import org.testng.annotations.AfterMethod;
28-import org.testng.annotations.BeforeClass;
2925 import org.testng.annotations.BeforeMethod;
3026
31-import static org.assertj.core.api.Assertions.assertThat;
32-import static org.mockito.Matchers.any;
33-import static org.mockito.Matchers.anyBoolean;
34-import static org.mockito.Matchers.anyInt;
35-import static org.mockito.Mockito.times;
36-
37-import com.datastax.driver.core.*;
27+import java.util.List;
28+import java.util.Map;
3829
3930 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
31+import static org.assertj.core.api.Assertions.assertThat;
32+import static org.mockito.Matchers.*;
33+import static org.mockito.Mockito.times;
4034
4135 /**
4236 * Base class for retry policy integration tests.
43- *
37+ * <p/>
4438 * We use SCassandra to easily simulate specific errors (unavailable, read timeout...) on nodes,
4539 * and SortingLoadBalancingPolicy to get a predictable order of the query plan (always host1, host2, host3).
46- *
40+ * <p/>
4741 * Note that SCassandra only allows a limited number of test cases, for instance it always returns errors
4842 * with receivedResponses = 0. If that becomes more finely tuneable in the future, we'll be able to add more
4943 * tests in child classes.
@@ -67,11 +61,11 @@
6761 scassandras.init();
6862
6963 cluster = Cluster.builder()
70- .addContactPoint(CCMBridge.ipOfNode(1))
71- .withRetryPolicy(retryPolicy)
72- .withLoadBalancingPolicy(new SortingLoadBalancingPolicy())
73- .withNettyOptions(nonQuietClusterCloseOptions)
74- .build();
64+ .addContactPoint(CCMBridge.ipOfNode(1))
65+ .withRetryPolicy(retryPolicy)
66+ .withLoadBalancingPolicy(new SortingLoadBalancingPolicy())
67+ .withNettyOptions(nonQuietClusterCloseOptions)
68+ .build();
7569
7670 session = cluster.connect();
7771
@@ -83,16 +77,16 @@
8377
8478 Mockito.reset(retryPolicy);
8579
86- for(Scassandra node : scassandras.nodes()) {
80+ for (Scassandra node : scassandras.nodes()) {
8781 node.activityClient().clearAllRecordedActivity();
8882 }
8983 }
9084
9185 protected void simulateError(int hostNumber, PrimingRequest.Result result) {
9286 scassandras.node(hostNumber).primingClient().prime(PrimingRequest.queryBuilder()
93- .withQuery("mock query")
94- .withResult(result)
95- .build());
87+ .withQuery("mock query")
88+ .withResult(result)
89+ .build());
9690 }
9791
9892 protected void simulateNormalResponse(int hostNumber) {
@@ -116,18 +110,18 @@
116110
117111 protected void assertOnReadTimeoutWasCalled(int times) {
118112 Mockito.verify(retryPolicy, times(times)).onReadTimeout(
119- any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyBoolean(), anyInt());
113+ any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyBoolean(), anyInt());
120114
121115 }
122116
123117 protected void assertOnWriteTimeoutWasCalled(int times) {
124118 Mockito.verify(retryPolicy, times(times)).onWriteTimeout(
125- any(Statement.class), any(ConsistencyLevel.class), any(WriteType.class), anyInt(), anyInt(), anyInt());
119+ any(Statement.class), any(ConsistencyLevel.class), any(WriteType.class), anyInt(), anyInt(), anyInt());
126120 }
127121
128122 protected void assertOnUnavailableWasCalled(int times) {
129123 Mockito.verify(retryPolicy, times(times)).onUnavailable(
130- any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
124+ any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
131125 }
132126
133127 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 +7 −8
@@ -15,6 +15,11 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.datastax.driver.core.ConsistencyLevel;
19+import com.datastax.driver.core.ResultSet;
20+import com.datastax.driver.core.Statement;
21+import com.datastax.driver.core.WriteType;
22+import com.datastax.driver.core.exceptions.UnavailableException;
1823 import org.testng.annotations.Test;
1924
2025 import static org.assertj.core.api.Assertions.assertThat;
@@ -22,12 +27,6 @@
2227 import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
2328 import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
2429
25-import com.datastax.driver.core.ConsistencyLevel;
26-import com.datastax.driver.core.ResultSet;
27-import com.datastax.driver.core.Statement;
28-import com.datastax.driver.core.WriteType;
29-import com.datastax.driver.core.exceptions.UnavailableException;
30-
3130 /**
3231 * Integration test with a custom implementation, to test retry and ignore decisions.
3332 */
@@ -84,8 +83,8 @@
8483 @Override
8584 public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
8685 return (nbRetry == 0)
87- ? RetryDecision.retry(cl)
88- : RetryDecision.rethrow();
86+ ? RetryDecision.retry(cl)
87+ : RetryDecision.rethrow();
8988 }
9089 }
9190 }
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 +8 −12
@@ -20,22 +20,18 @@
2020 import com.datastax.driver.core.Metrics;
2121 import com.datastax.driver.core.Session;
2222 import com.datastax.driver.core.exceptions.NoHostAvailableException;
23-
24-import org.scassandra.Scassandra;
25-import org.testng.annotations.Test;
26-
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-
3323 import com.datastax.driver.core.exceptions.ReadTimeoutException;
3424 import com.datastax.driver.core.exceptions.UnavailableException;
3525 import com.datastax.driver.core.exceptions.WriteTimeoutException;
26+import org.scassandra.Scassandra;
27+import org.testng.annotations.Test;
3628
3729 import java.util.Collections;
3830
31+import static org.assertj.core.api.Assertions.assertThat;
32+import static org.assertj.core.api.Assertions.fail;
33+import static org.scassandra.http.client.PrimingRequest.Result.*;
34+
3935 public class DefaultRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
4036 public DefaultRetryPolicyIntegrationTest() {
4137 super(DefaultRetryPolicy.INSTANCE);
@@ -119,7 +115,7 @@
119115 try {
120116 Session whiteListedSession = whiteListedCluster.connect();
121117 // Clear all activity as result of connect.
122- for(Scassandra node : scassandras.nodes()) {
118+ for (Scassandra node : scassandras.nodes()) {
123119 node.activityClient().clearAllRecordedActivity();
124120 }
125121
@@ -128,7 +124,7 @@
128124 try {
129125 query(whiteListedSession);
130126 fail("expected an NoHostAvailableException");
131- } catch(NoHostAvailableException e) {
127+ } catch (NoHostAvailableException e) {
132128 // ok
133129 Throwable error = e.getErrors().get(host1.getSocketAddress());
134130 assertThat(error).isNotNull();
modified driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingLoadBalancingPolicy.java +5 −5
@@ -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, CloseableLoadBalancingPolicy {
@@ -75,6 +75,6 @@
7575 @Override
7676 public void close() {
7777 if (delegate instanceof CloseableLoadBalancingPolicy)
78- ((CloseableLoadBalancingPolicy)delegate).close();
78+ ((CloseableLoadBalancingPolicy) delegate).close();
7979 }
8080 }
No newline at the end of the file
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/EC2MultiRegionAddressTranslaterTest.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 EC2MultiRegionAddressTranslater translater = new EC2MultiRegionAddressTranslater(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- EC2MultiRegionAddressTranslater.reverse(address)
82+ EC2MultiRegionAddressTranslater.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- EC2MultiRegionAddressTranslater.reverse(address)
92+ EC2MultiRegionAddressTranslater.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 +4 −7
@@ -15,17 +15,14 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.datastax.driver.core.exceptions.ReadTimeoutException;
19+import com.datastax.driver.core.exceptions.UnavailableException;
20+import com.datastax.driver.core.exceptions.WriteTimeoutException;
1821 import org.testng.annotations.Test;
1922
2023 import static org.assertj.core.api.Assertions.assertThat;
2124 import static org.assertj.core.api.Assertions.fail;
22-import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
23-import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
24-import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
25-
26-import com.datastax.driver.core.exceptions.ReadTimeoutException;
27-import com.datastax.driver.core.exceptions.UnavailableException;
28-import com.datastax.driver.core.exceptions.WriteTimeoutException;
25+import static org.scassandra.http.client.PrimingRequest.Result.*;
2926
3027 public class FallthroughRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
3128 public FallthroughRetryPolicyIntegrationTest() {
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/LatencyAwarePolicyTest.java +22 −24
@@ -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 /**
@@ -60,13 +58,13 @@
6058 // given
6159 String query = "SELECT foo FROM bar";
6260 primingClient.prime(
63- queryBuilder()
64- .withQuery(query)
65- .build()
61+ queryBuilder()
62+ .withQuery(query)
63+ .build()
6664 );
6765 LatencyAwarePolicy latencyAwarePolicy = LatencyAwarePolicy.builder(new RoundRobinPolicy())
68- .withMininumMeasurements(1)
69- .build();
66+ .withMininumMeasurements(1)
67+ .build();
7068 Cluster.Builder builder = super.createClusterBuilder();
7169 builder.withLoadBalancingPolicy(latencyAwarePolicy);
7270 Cluster cluster = builder.build();
@@ -98,14 +96,14 @@
9896 // given
9997 String query = "SELECT foo FROM bar";
10098 primingClient.prime(
101- queryBuilder()
102- .withQuery(query)
103- .withResult(unavailable)
104- .build()
99+ queryBuilder()
100+ .withQuery(query)
101+ .withResult(unavailable)
102+ .build()
105103 );
106104 LatencyAwarePolicy latencyAwarePolicy = LatencyAwarePolicy.builder(new RoundRobinPolicy())
107- .withMininumMeasurements(1)
108- .build();
105+ .withMininumMeasurements(1)
106+ .build();
109107 Cluster.Builder builder = super.createClusterBuilder();
110108 builder.withLoadBalancingPolicy(latencyAwarePolicy);
111109 Cluster cluster = builder.build();
@@ -138,14 +136,14 @@
138136 }
139137 }
140138
141- @Test(groups= "short")
139+ @Test(groups = "short")
142140 public void should_consider_latency_when_read_timeout() throws Exception {
143141 String query = "SELECT foo FROM bar";
144142 primingClient.prime(
145- queryBuilder()
146- .withQuery(query)
147- .withResult(read_request_timeout)
148- .build()
143+ queryBuilder()
144+ .withQuery(query)
145+ .withResult(read_request_timeout)
146+ .build()
149147 );
150148
151149 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/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 +62 −78
@@ -15,34 +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.BoundStatement;
28-import com.datastax.driver.core.CCMBridge;
29-import com.datastax.driver.core.Cluster;
30-import com.datastax.driver.core.DataType;
31-import com.datastax.driver.core.Host;
32-import com.datastax.driver.core.PreparedStatement;
33-import com.datastax.driver.core.QueryTracker;
34-import com.datastax.driver.core.ResultSet;
35-import com.datastax.driver.core.Row;
36-import com.datastax.driver.core.ScassandraCluster;
37-import com.datastax.driver.core.Session;
38-import com.datastax.driver.core.SimpleStatement;
39-import com.datastax.driver.core.TestUtils;
25+import java.nio.ByteBuffer;
26+import java.util.List;
4027
4128 import static com.datastax.driver.core.Assertions.assertThat;
42-import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
43-import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
44-import static com.datastax.driver.core.TestUtils.getDesiredProtocolVersion;
45-import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
29+import static com.datastax.driver.core.TestUtils.*;
4630
4731 public class TokenAwarePolicyTest {
4832
@@ -53,12 +37,12 @@
5337 queryTracker = new QueryTracker();
5438 }
5539
56- @DataProvider(name="shuffleProvider")
57- public Object[][] shuffleProvider () {
58- return new Object[][] {
59- { true },
60- { false },
61- { null }
40+ @DataProvider(name = "shuffleProvider")
41+ public Object[][] shuffleProvider() {
42+ return new Object[][]{
43+ {true},
44+ {false},
45+ {null}
6246 };
6347 }
6448
@@ -69,16 +53,16 @@
6953 *
7054 * @test_category load_balancing:token_aware
7155 */
72- @Test(groups="short", dataProvider="shuffleProvider")
56+ @Test(groups = "short", dataProvider = "shuffleProvider")
7357 public void should_shuffle_replicas_based_on_configuration(Boolean shuffleReplicas) {
7458 // given: an 8 node cluster using TokenAwarePolicy and some shuffle replica configuration with a keyspace with replication factor of 3.
7559 ScassandraCluster sCluster = ScassandraCluster.builder()
76- .withNodes(8)
77- .withSimpleKeyspace("keyspace", 3)
78- .build();
60+ .withNodes(8)
61+ .withSimpleKeyspace("keyspace", 3)
62+ .build();
7963
8064 LoadBalancingPolicy loadBalancingPolicy;
81- if(shuffleReplicas == null) {
65+ if (shuffleReplicas == null) {
8266 loadBalancingPolicy = new TokenAwarePolicy(new RoundRobinPolicy());
8367 shuffleReplicas = true;
8468 } else {
@@ -86,9 +70,9 @@
8670 }
8771
8872 Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
89- .withNettyOptions(nonQuietClusterCloseOptions)
90- .withLoadBalancingPolicy(loadBalancingPolicy)
91- .build();
73+ .withNettyOptions(nonQuietClusterCloseOptions)
74+ .withLoadBalancingPolicy(loadBalancingPolicy)
75+ .build();
9276
9377 try {
9478 sCluster.init();
@@ -101,9 +85,9 @@
10185 // then: The replicas resolved from the cluster metadata must match node 6 and its replicas.
10286 List<Host> replicas = Lists.newArrayList(cluster.getMetadata().getReplicas("keyspace", routingKey));
10387 assertThat(replicas).containsExactly(
104- sCluster.host(cluster, 1, 6),
105- sCluster.host(cluster, 1, 7),
106- sCluster.host(cluster, 1, 8));
88+ sCluster.host(cluster, 1, 6),
89+ sCluster.host(cluster, 1, 7),
90+ sCluster.host(cluster, 1, 8));
10791
10892 // then: generating a query plan on a statement using that routing key should properly prioritize node 6 and its replicas.
10993 SimpleStatement statement = new SimpleStatement("select * from table where k=5");
@@ -111,16 +95,16 @@
11195 statement.setKeyspace("keyspace");
11296
11397 boolean shuffledAtLeastOnce = false;
114- for(int i = 0; i < 1024; i++) {
98+ for (int i = 0; i < 1024; i++) {
11599 List<Host> queryPlan = Lists.newArrayList(loadBalancingPolicy.newQueryPlan(null, statement));
116100 assertThat(queryPlan).containsOnlyElementsOf(cluster.getMetadata().getAllHosts());
117101
118102 List<Host> firstThree = queryPlan.subList(0, 3);
119103 // then: if shuffle replicas was used or using default, the first three hosts returned should be 6,7,8 in any order.
120104 // if shuffle replicas was not used, the first three hosts returned should be 6,7,8 in that order.
121- if(shuffleReplicas) {
105+ if (shuffleReplicas) {
122106 assertThat(firstThree).containsOnlyElementsOf(replicas);
123- if(!firstThree.equals(replicas)) {
107+ if (!firstThree.equals(replicas)) {
124108 shuffledAtLeastOnce = true;
125109 }
126110 } else {
@@ -143,17 +127,17 @@
143127 *
144128 * @test_category load_balancing:token_aware
145129 */
146- @Test(groups="short")
130+ @Test(groups = "short")
147131 public void should_choose_proper_host_based_on_routing_key() {
148132 // given: A 3 node cluster using TokenAwarePolicy with a replication factor of 1.
149133 ScassandraCluster sCluster = ScassandraCluster.builder()
150- .withNodes(3)
151- .withSimpleKeyspace("keyspace", 1)
152- .build();
134+ .withNodes(3)
135+ .withSimpleKeyspace("keyspace", 1)
136+ .build();
153137 Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
154- .withNettyOptions(nonQuietClusterCloseOptions)
155- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
156- .build();
138+ .withNettyOptions(nonQuietClusterCloseOptions)
139+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
140+ .build();
157141
158142 // when: A query is made with a routing key
159143 try {
@@ -164,8 +148,8 @@
164148 // Encodes into murmur hash '4557949199137838892' which should belong be owned by node 3.
165149 ByteBuffer routingKey = DataType.text().serialize("should_choose_proper_host_based_on_routing_key", getDesiredProtocolVersion());
166150 SimpleStatement statement = new SimpleStatement("select * from table where k=5")
167- .setRoutingKey(routingKey)
168- .setKeyspace("keyspace");
151+ .setRoutingKey(routingKey)
152+ .setKeyspace("keyspace");
169153
170154 queryTracker.query(session, 10, statement);
171155
@@ -186,20 +170,20 @@
186170 *
187171 * @test_category load_balancing:token_aware
188172 */
189- @Test(groups="short")
173+ @Test(groups = "short")
190174 public void should_choose_host_in_local_dc_when_using_network_topology_strategy_and_dc_aware() {
191175 // given: A 6 node, 2 DC cluster with RF 1:1, using TokenAwarePolicy wrapping DCAwareRoundRobinPolicy with remote hosts.
192176 ScassandraCluster sCluster = ScassandraCluster.builder()
193- .withNodes(3, 3)
194- .withNetworkTopologyKeyspace("keyspace", ImmutableMap.of(1, 1, 2, 1))
195- .build();
196- Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2,1))
197- .withNettyOptions(nonQuietClusterCloseOptions)
198- .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder()
199- .withLocalDc(ScassandraCluster.datacenter(2))
200- .withUsedHostsPerRemoteDc(3)
201- .build()))
202- .build();
177+ .withNodes(3, 3)
178+ .withNetworkTopologyKeyspace("keyspace", ImmutableMap.of(1, 1, 2, 1))
179+ .build();
180+ Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2, 1))
181+ .withNettyOptions(nonQuietClusterCloseOptions)
182+ .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder()
183+ .withLocalDc(ScassandraCluster.datacenter(2))
184+ .withUsedHostsPerRemoteDc(3)
185+ .build()))
186+ .build();
203187
204188 // when: A query is made with a routing key
205189 try {
@@ -209,10 +193,10 @@
209193
210194 // Encodes into murmur hash '-8124212968526248339' which should belong to 1:1 in DC1 and 2:1 in DC2.
211195 ByteBuffer routingKey = DataType.text().serialize("should_choose_host_in_local_dc_when_using_network_topology_strategy_and_dc_aware",
212- getDesiredProtocolVersion());
196+ getDesiredProtocolVersion());
213197 SimpleStatement statement = new SimpleStatement("select * from table where k=5")
214- .setRoutingKey(routingKey)
215- .setKeyspace("keyspace");
198+ .setRoutingKey(routingKey)
199+ .setKeyspace("keyspace");
216200
217201 queryTracker.query(session, 10, statement);
218202
@@ -232,18 +216,18 @@
232216 *
233217 * @test_category load_balancing:token_aware
234218 */
235- @Test(groups="short")
219+ @Test(groups = "short")
236220 public void should_use_other_nodes_when_replicas_having_token_are_down() {
237221 // given: A 4 node cluster using TokenAwarePolicy with a replication factor of 2.
238222 ScassandraCluster sCluster = ScassandraCluster.builder()
239- .withNodes(4)
240- .withSimpleKeyspace("keyspace", 2)
241- .build();
223+ .withNodes(4)
224+ .withSimpleKeyspace("keyspace", 2)
225+ .build();
242226 Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2))
243- .withNettyOptions(nonQuietClusterCloseOptions)
244- // Don't shuffle replicas just to keep test deterministic.
245- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
246- .build();
227+ .withNettyOptions(nonQuietClusterCloseOptions)
228+ // Don't shuffle replicas just to keep test deterministic.
229+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
230+ .build();
247231
248232 try {
249233 sCluster.init();
@@ -254,8 +238,8 @@
254238 // Encodes into murmur hash '6444339665561646341' which should belong to node 4.
255239 ByteBuffer routingKey = DataType.text().serialize("should_use_other_nodes_when_replicas_having_token_are_down", getDesiredProtocolVersion());
256240 SimpleStatement statement = new SimpleStatement("select * from table where k=5")
257- .setRoutingKey(routingKey)
258- .setKeyspace("keyspace");
241+ .setRoutingKey(routingKey)
242+ .setKeyspace("keyspace");
259243
260244 queryTracker.query(session, 10, statement);
261245
@@ -328,9 +312,9 @@
328312 CCMBridge ccm = CCMBridge.builder("TokenAwarePolicyTest").withNodes(3).notStarted().build();
329313
330314 Cluster cluster = Cluster.builder()
331- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
332- .addContactPoint(CCMBridge.ipOfNode(1))
333- .build();
315+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
316+ .addContactPoint(CCMBridge.ipOfNode(1))
317+ .build();
334318
335319 try {
336320 ccm.start();
@@ -346,11 +330,11 @@
346330 BoundStatement insertBs = insertPs.bind(1, 2, 3);
347331
348332 PreparedStatement selectPs = session.prepare("SELECT * FROM " + table + " WHERE k1=? and k2=?");
349- BoundStatement selectBs = selectPs.bind(1,2);
333+ BoundStatement selectBs = selectPs.bind(1, 2);
350334
351335 // when: executing a prepared statement with a composite partition key.
352336 // then: should query the correct node (1) in for both insert and select queries.
353- for(int i = 0; i < 10; i++) {
337+ for (int i = 0; i < 10; i++) {
354338 ResultSet rs = session.execute(insertBs);
355339 assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
356340
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();

Next files