Elffuss BraidHub

kikocis/java-driver public

Format all Java sources with Intellij default settings.
Changeset6697eb958eb956e05d2bcb33188880f388991f4cdd6fe7ee460f9355bd9554b4
Authorolim7t <omichallat+github@gmail.com> · 2015-12-09 17:38 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-12-09 17:38 +01:00
Parents6ad0d047bddb

Browse the files at this changeset

283 files changed

modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java +11 −13
@@ -15,16 +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.google.common.collect.Lists;
25-
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
27-
2826 abstract class AbstractGettableData implements GettableData {
2927
3028 protected final ColumnDefinitions metadata;
@@ -153,16 +151,16 @@
153151
154152 public String getString(int i) {
155153 DataType.Name type = metadata.checkType(i, DataType.Name.VARCHAR,
156- DataType.Name.TEXT,
157- DataType.Name.ASCII);
154+ DataType.Name.TEXT,
155+ DataType.Name.ASCII);
158156
159157 ByteBuffer value = getValue(i);
160158 if (value == null)
161159 return null;
162160
163161 return type == DataType.Name.ASCII
164- ? TypeCodec.StringCodec.asciiInstance.deserialize(value)
165- : TypeCodec.StringCodec.utf8Instance.deserialize(value);
162+ ? TypeCodec.StringCodec.asciiInstance.deserialize(value)
163+ : TypeCodec.StringCodec.utf8Instance.deserialize(value);
166164 }
167165
168166 public String getString(String name) {
@@ -205,8 +203,8 @@
205203 return null;
206204
207205 return type == DataType.Name.UUID
208- ? TypeCodec.UUIDCodec.instance.deserialize(value)
209- : TypeCodec.TimeUUIDCodec.instance.deserialize(value);
206+ ? TypeCodec.UUIDCodec.instance.deserialize(value)
207+ : TypeCodec.TimeUUIDCodec.instance.deserialize(value);
210208 }
211209
212210 public UUID getUUID(String name) {
@@ -241,7 +239,7 @@
241239 if (value == null)
242240 return Collections.<T>emptyList();
243241
244- return Collections.unmodifiableList((List<T>)type.codec().deserialize(value));
242+ return Collections.unmodifiableList((List<T>) type.codec().deserialize(value));
245243 }
246244
247245 public <T> List<T> getList(String name, Class<T> elementsClass) {
@@ -262,7 +260,7 @@
262260 if (value == null)
263261 return Collections.<T>emptySet();
264262
265- return Collections.unmodifiableSet((Set<T>)type.codec().deserialize(value));
263+ return Collections.unmodifiableSet((Set<T>) type.codec().deserialize(value));
266264 }
267265
268266 public <T> Set<T> getSet(String name, Class<T> elementsClass) {
@@ -284,7 +282,7 @@
284282 if (value == null)
285283 return Collections.<K, V>emptyMap();
286284
287- return Collections.unmodifiableMap((Map<K, V>)type.codec().deserialize(value));
285+ return Collections.unmodifiableMap((Map<K, V>) type.codec().deserialize(value));
288286 }
289287
290288 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/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 +15 −16
@@ -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.
@@ -56,26 +55,26 @@
5655 case VOID:
5756 return empty(info);
5857 case ROWS:
59- Responses.Result.Rows r = (Responses.Result.Rows)msg;
58+ Responses.Result.Rows r = (Responses.Result.Rows) msg;
6059
6160 ColumnDefinitions columnDefs;
6261 if (r.metadata.columns == null) {
6362 assert statement instanceof BoundStatement;
64- columnDefs = ((BoundStatement)statement).statement.getPreparedId().resultSetMetadata;
63+ columnDefs = ((BoundStatement) statement).statement.getPreparedId().resultSetMetadata;
6564 assert columnDefs != null;
6665 } else {
6766 columnDefs = r.metadata.columns;
6867 }
6968
7069 Token.Factory tokenFactory = (session == null) ? null
71- : session.getCluster().manager.metadata.tokenFactory();
70+ : session.getCluster().manager.metadata.tokenFactory();
7271
7372 // info can be null only for internal calls, but we don't page those. We assert
7473 // this explicitly because MultiPage implementation don't support info == null.
7574 assert r.metadata.pagingState == null || info != null;
7675 return r.metadata.pagingState == null
77- ? new SinglePage(columnDefs, tokenFactory, r.data, info)
78- : new MultiPage(columnDefs, tokenFactory, r.data, info, r.metadata.pagingState, session, statement);
76+ ? new SinglePage(columnDefs, tokenFactory, r.data, info)
77+ : new MultiPage(columnDefs, tokenFactory, r.data, info, r.metadata.pagingState, session, statement);
7978
8079 case SET_KEYSPACE:
8180 case SCHEMA_CHANGE:
@@ -320,10 +319,10 @@
320319 try {
321320 switch (response.type) {
322321 case RESULT:
323- Responses.Result rm = (Responses.Result)response;
322+ Responses.Result rm = (Responses.Result) response;
324323 info = update(info, rm, MultiPage.this.session);
325324 if (rm.kind == Responses.Result.Kind.ROWS) {
326- Responses.Result.Rows rows = (Responses.Result.Rows)rm;
325+ Responses.Result.Rows rows = (Responses.Result.Rows) rm;
327326 if (rows.metadata.pagingState != null)
328327 info = info.withPagingState(rows.metadata.pagingState).withStatement(statement);
329328 MultiPage.this.nextPages.offer(rows.data);
@@ -343,7 +342,7 @@
343342 future.set(null);
344343 break;
345344 case ERROR:
346- future.setException(((Responses.Error)response).asException(connection.address));
345+ future.setException(((Responses.Error) response).asException(connection.address));
347346 break;
348347 default:
349348 // 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 +2 −2
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+
1820 import java.nio.ByteBuffer;
1921 import java.util.List;
2022
21-import com.datastax.driver.core.exceptions.DriverInternalError;
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/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 +16 −20
@@ -15,19 +15,15 @@
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-
2518 import com.google.common.collect.ImmutableList;
2619
20+import java.nio.ByteBuffer;
21+import java.util.*;
22+
2723 /**
2824 * A statement that group a number of {@link Statement} so they get executed as
2925 * a batch.
30- * <p>
26+ * <p/>
3127 * Note: BatchStatement is not supported with the native protocol version 1: you
3228 * will get an {@link UnsupportedProtocolVersionException} when submitting one if
3329 * version 1 of the protocol is in use (i.e. if you've force version 1 through
@@ -59,7 +55,9 @@
5955 * operations and it can only contain these.
6056 */
6157 COUNTER
62- };
58+ }
59+
60+ ;
6361
6462 final Type batchType;
6563 private final List<Statement> statements = new ArrayList<Statement>();
@@ -84,14 +82,14 @@
8482 IdAndValues idAndVals = new IdAndValues(statements.size());
8583 for (Statement statement : statements) {
8684 if (statement instanceof RegularStatement) {
87- RegularStatement st = (RegularStatement)statement;
85+ RegularStatement st = (RegularStatement) statement;
8886 ByteBuffer[] vals = st.getValues();
8987 idAndVals.ids.add(st.getQueryString());
9088 idAndVals.values.add(vals == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(vals));
9189 } else {
9290 // We handle BatchStatement in add() so ...
9391 assert statement instanceof BoundStatement;
94- BoundStatement st = (BoundStatement)statement;
92+ BoundStatement st = (BoundStatement) statement;
9593 idAndVals.ids.add(st.statement.getPreparedId().id);
9694 idAndVals.values.add(Arrays.asList(st.values));
9795 }
@@ -101,13 +99,13 @@
10199
102100 /**
103101 * Adds a new statement to this batch.
104- * <p>
102+ * <p/>
105103 * Note that {@code statement} can be any {@code Statement}. It is allowed to mix
106104 * {@code RegularStatement} and {@code BoundStatement} in the same
107105 * {@code BatchStatement} in particular. Adding another {@code BatchStatement}
108106 * is also allowed for convenient and is equivalent to adding all the {@code Statement}
109107 * contained in that other {@code BatchStatement}.
110- * <p>
108+ * <p/>
111109 * Please note that the options of the added Statement (all those defined directly by the
112110 * {@link Statement} class: consistency level, fetch size, tracing, ...) will be ignored
113111 * for the purpose of the execution of the Batch. Instead, the options used are the one
@@ -115,10 +113,9 @@
115113 *
116114 * @param statement the new statement to add.
117115 * @return this batch statement.
118- *
119116 * @throws IllegalStateException if adding the new statement means that this
120- * {@code BatchStatement} has more than 65536 statements (since this is the maximum number
121- * of statements for a BatchStatement allowed by the underlying protocol).
117+ * {@code BatchStatement} has more than 65536 statements (since this is the maximum number
118+ * of statements for a BatchStatement allowed by the underlying protocol).
122119 */
123120 public BatchStatement add(Statement statement) {
124121
@@ -126,7 +123,7 @@
126123 // easier to avoid endless loop if the use mistakenly pass a batch that depends on this
127124 // object (or this directly).
128125 if (statement instanceof BatchStatement) {
129- for (Statement subStatements : ((BatchStatement)statement).statements) {
126+ for (Statement subStatements : ((BatchStatement) statement).statements) {
130127 add(subStatements);
131128 }
132129 } else {
@@ -139,7 +136,7 @@
139136
140137 /**
141138 * Adds multiple statements to this batch.
142- * <p>
139+ * <p/>
143140 * This is a shortcut method that calls {@link #add} on all the statements
144141 * from {@code statements}.
145142 *
@@ -184,7 +181,7 @@
184181 /**
185182 * Throws an {@code UnsupportedOperationException} as setting the serial consistency is
186183 * currently not supported for protocol batches by Cassandra.
187- * <p>
184+ * <p/>
188185 * The current version of the protocol uses does not allow to provide a serial consistency level
189186 * for protocol batches (the batch created through this class). This is fixed by the protocol
190187 * version 3 that will be part of Cassandra 2.1 and will be supported by the driver version 2.1.
@@ -193,7 +190,6 @@
193190 *
194191 * @param serialConsistency the serial consistency level
195192 * @return nothing since this call currently always throws an {@code UnsupportedOperationException}.
196- *
197193 * @throws UnsupportedOperationException see above.
198194 */
199195 @Override
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +183 −224
@@ -15,31 +15,29 @@
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.google.common.collect.Lists;
25-
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
27-
2826 /**
2927 * A prepared statement with values bound to the bind variables.
30- * <p>
28+ * <p/>
3129 * Once values has been provided for the variables of the {@link PreparedStatement}
3230 * it has been created from, such BoundStatement can be executed (through
3331 * {@link Session#execute(Statement)}).
34- * <p>
32+ * <p/>
3533 * The values of a BoundStatement can be set by either index or name. When
3634 * setting them by name, names follow the case insensitivity rules explained in
3735 * {@link ColumnDefinitions} but with the difference that if multiple bind
3836 * variables have the same name, setting that name will set <b>all</b> the
3937 * variables for that name.
40- * <p>
38+ * <p/>
4139 * Any variable that hasn't been specifically set will be considered {@code null}.
42- * <p>
40+ * <p/>
4341 * Bound values may also be retrieved using {@code get*()} methods. Note that this
4442 * may have a non-negligible impact on performance: internally, values are stored
4543 * in serialized form, so they need to be deserialized again. These methods are
@@ -56,6 +54,7 @@
5654 /**
5755 * Creates a new {@code BoundStatement} from the provided prepared
5856 * statement.
57+ *
5958 * @param statement the prepared statement from which to create a {@code BoundStatement}.
6059 */
6160 public BoundStatement(PreparedStatement statement) {
@@ -90,7 +89,6 @@
9089 *
9190 * @param i the index of the variable to check.
9291 * @return whether the {@code i}th variable has been bound to a non null value.
93- *
9492 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
9593 */
9694 public boolean isSet(int i) {
@@ -105,9 +103,8 @@
105103 * @param name the name of the variable to check.
106104 * @return whether the first occurrence of variable {@code name} has been
107105 * bound to a non-null value.
108- *
109106 * @throws IllegalArgumentException if {@code name} is not a prepared
110- * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
107+ * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
111108 */
112109 public boolean isSet(String name) {
113110 return isSet(metadata().getFirstIdx(name));
@@ -115,33 +112,31 @@
115112
116113 /**
117114 * Bound values to the variables of this statement.
118- *
115+ * <p/>
119116 * This is a convenience method to bind all the variables of the
120117 * {@code BoundStatement} in one call.
121118 *
122119 * @param values the values to bind to the variables of the newly created
123- * BoundStatement. The first element of {@code values} will be bound to the
124- * first bind variable, etc. It is legal to provide fewer values than the
125- * statement has bound variables. In that case, the remaining variable need
126- * to be bound before execution. If more values than variables are provided
127- * however, an IllegalArgumentException wil be raised.
120+ * BoundStatement. The first element of {@code values} will be bound to the
121+ * first bind variable, etc. It is legal to provide fewer values than the
122+ * statement has bound variables. In that case, the remaining variable need
123+ * to be bound before execution. If more values than variables are provided
124+ * however, an IllegalArgumentException wil be raised.
128125 * @return this bound statement.
129- *
130126 * @throws IllegalArgumentException if more {@code values} are provided
131- * than there is of bound variables in this statement.
132- * @throws InvalidTypeException if any of the provided value is not of
133- * correct type to be bound to the corresponding bind variable.
134- * @throws NullPointerException if one of {@code values} is a collection
135- * (List, Set or Map) containing a null value. Nulls are not supported in
136- * collections by CQL.
127+ * than there is of bound variables in this statement.
128+ * @throws InvalidTypeException if any of the provided value is not of
129+ * correct type to be bound to the corresponding bind variable.
130+ * @throws NullPointerException if one of {@code values} is a collection
131+ * (List, Set or Map) containing a null value. Nulls are not supported in
132+ * collections by CQL.
137133 */
138134 public BoundStatement bind(Object... values) {
139135
140136 if (values.length > statement.getVariables().size())
141137 throw new IllegalArgumentException(String.format("Prepared statement has only %d variables, %d values provided", statement.getVariables().size(), values.length));
142138
143- for (int i = 0; i < values.length; i++)
144- {
139+ for (int i = 0; i < values.length; i++) {
145140 Object toSet = values[i];
146141
147142 if (toSet == null) {
@@ -155,7 +150,7 @@
155150 if (!(toSet instanceof List))
156151 throw new InvalidTypeException(String.format("Invalid type for value %d, column is a list but %s provided", i, toSet.getClass()));
157152
158- List<?> l = (List<?>)toSet;
153+ List<?> l = (List<?>) toSet;
159154 // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
160155 if (!l.isEmpty()) {
161156 // Ugly? Yes
@@ -169,7 +164,7 @@
169164 if (!(toSet instanceof Set))
170165 throw new InvalidTypeException(String.format("Invalid type for value %d, column is a set but %s provided", i, toSet.getClass()));
171166
172- Set<?> s = (Set<?>)toSet;
167+ Set<?> s = (Set<?>) toSet;
173168 // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
174169 if (!s.isEmpty()) {
175170 // Ugly? Yes
@@ -183,7 +178,7 @@
183178 if (!(toSet instanceof Map))
184179 throw new InvalidTypeException(String.format("Invalid type for value %d, column is a map but %s provided", i, toSet.getClass()));
185180
186- Map<?, ?> m = (Map<?, ?>)toSet;
181+ Map<?, ?> m = (Map<?, ?>) toSet;
187182 // If the list is empty, it will never fail validation, but otherwise we should check the list given if of the right type
188183 if (!m.isEmpty()) {
189184 // Ugly? Yes
@@ -199,7 +194,7 @@
199194 break;
200195 default:
201196 if (toSet instanceof Token)
202- toSet = ((Token)toSet).getValue();
197+ toSet = ((Token) toSet).getValue();
203198
204199 Class<?> providedClass = toSet.getClass();
205200 Class<?> expectedClass = columnType.getName().javaType;
@@ -214,14 +209,13 @@
214209
215210 /**
216211 * Sets the routing key for this bound statement.
217- * <p>
212+ * <p/>
218213 * This is useful when the routing key can neither be set on the {@code PreparedStatement} this bound statement
219214 * was built from, nor automatically computed from bound variables. In particular, this is the case if the
220215 * partition key is composite and only some of its components are bound.
221216 *
222217 * @param routingKey the raw (binary) value to use as routing key.
223218 * @return this {@code BoundStatement} object.
224- *
225219 * @see BoundStatement#getRoutingKey
226220 */
227221 public BoundStatement setRoutingKey(ByteBuffer routingKey) {
@@ -231,7 +225,7 @@
231225
232226 /**
233227 * The routing key for this bound query.
234- * <p>
228+ * <p/>
235229 * This method will return a non-{@code null} value if either of the following occur:
236230 * <ul>
237231 * <li>The routing key has been set directly through {@link BoundStatement#setRoutingKey}.</li>
@@ -241,8 +235,8 @@
241235 * key will then be built using the values provided for these partition key columns.</li>
242236 * </ul>
243237 * Otherwise, {@code null} is returned.
244- * <p>
245- *
238+ * <p/>
239+ * <p/>
246240 * Note that if the routing key has been set through {@link BoundStatement#setRoutingKey}, then that takes
247241 * precedence. If the routing key has been set through {@link PreparedStatement#setRoutingKey} then that is used
248242 * next. If neither of those are set then it is computed.
@@ -279,7 +273,7 @@
279273
280274 /**
281275 * Returns the keyspace this query operates on.
282- * <p>
276+ * <p/>
283277 * This method will always return a non-{@code null} value (unless the statement
284278 * has no variables, but you should avoid prepared statement in the first in that
285279 * case). The keyspace returned will be the one corresponding to the first
@@ -301,9 +295,8 @@
301295 * @param i the index of the variable to set.
302296 * @param v the value to set.
303297 * @return this BoundStatement.
304- *
305298 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
306- * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
299+ * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
307300 */
308301 public BoundStatement setBool(int i, boolean v) {
309302 metadata().checkType(i, DataType.Name.BOOLEAN);
@@ -315,13 +308,12 @@
315308 * provided boolean.
316309 *
317310 * @param name the name of the variable to set; if multiple variables
318- * {@code name} are prepared, all of them are set.
319- * @param v the value to set.
311+ * {@code name} are prepared, all of them are set.
312+ * @param v the value to set.
320313 * @return this BoundStatement.
321- *
322314 * @throws IllegalArgumentException if {@code name} is not a prepared
323- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
324- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type BOOLEAN.
315+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
316+ * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type BOOLEAN.
325317 */
326318 public BoundStatement setBool(String name, boolean v) {
327319 int[] indexes = metadata().getAllIdx(name);
@@ -339,9 +331,8 @@
339331 * @param i the index of the variable to set.
340332 * @param v the value to set.
341333 * @return this BoundStatement.
342- *
343334 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
344- * @throws InvalidTypeException if column {@code i} is not of type INT.
335+ * @throws InvalidTypeException if column {@code i} is not of type INT.
345336 */
346337 public BoundStatement setInt(int i, int v) {
347338 metadata().checkType(i, DataType.Name.INT);
@@ -353,13 +344,12 @@
353344 * provided integer.
354345 *
355346 * @param name the name of the variable to set; if multiple variables
356- * {@code name} are prepared, all of them are set.
357- * @param v the value to set.
347+ * {@code name} are prepared, all of them are set.
348+ * @param v the value to set.
358349 * @return this BoundStatement.
359- *
360350 * @throws IllegalArgumentException if {@code name} is not a prepared
361- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
362- * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type INT.
351+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
352+ * @throws InvalidTypeException if (any one occurrence of) {@code name} is not of type INT.
363353 */
364354 public BoundStatement setInt(String name, int v) {
365355 int[] indexes = metadata().getAllIdx(name);
@@ -377,9 +367,8 @@
377367 * @param i the index of the variable to set.
378368 * @param v the value to set.
379369 * @return this BoundStatement.
380- *
381370 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
382- * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
371+ * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
383372 */
384373 public BoundStatement setLong(int i, long v) {
385374 metadata().checkType(i, DataType.Name.BIGINT, DataType.Name.COUNTER);
@@ -391,14 +380,13 @@
391380 * provided long.
392381 *
393382 * @param name the name of the variable to set; if multiple variables
394- * {@code name} are prepared, all of them are set.
395- * @param v the value to set.
383+ * {@code name} are prepared, all of them are set.
384+ * @param v the value to set.
396385 * @return this BoundStatement.
397- *
398386 * @throws IllegalArgumentException if {@code name} is not a prepared
399- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
400- * @throws InvalidTypeException if (any occurrence of) {@code name} is
401- * not of type BIGINT or COUNTER.
387+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
388+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
389+ * not of type BIGINT or COUNTER.
402390 */
403391 public BoundStatement setLong(String name, long v) {
404392 int[] indexes = metadata().getAllIdx(name);
@@ -416,9 +404,8 @@
416404 * @param i the index of the variable to set.
417405 * @param v the value to set.
418406 * @return this BoundStatement.
419- *
420407 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
421- * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
408+ * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
422409 */
423410 public BoundStatement setDate(int i, Date v) {
424411 metadata().checkType(i, DataType.Name.TIMESTAMP);
@@ -430,14 +417,13 @@
430417 * provided date.
431418 *
432419 * @param name the name of the variable to set; if multiple variables
433- * {@code name} are prepared, all of them are set.
434- * @param v the value to set.
420+ * {@code name} are prepared, all of them are set.
421+ * @param v the value to set.
435422 * @return this BoundStatement.
436- *
437423 * @throws IllegalArgumentException if {@code name} is not a prepared
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 TIMESTAMP.
424+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
425+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
426+ * not of type TIMESTAMP.
441427 */
442428 public BoundStatement setDate(String name, Date v) {
443429 int[] indexes = metadata().getAllIdx(name);
@@ -455,9 +441,8 @@
455441 * @param i the index of the variable to set.
456442 * @param v the value to set.
457443 * @return this BoundStatement.
458- *
459444 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
460- * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
445+ * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
461446 */
462447 public BoundStatement setFloat(int i, float v) {
463448 metadata().checkType(i, DataType.Name.FLOAT);
@@ -469,14 +454,13 @@
469454 * provided float.
470455 *
471456 * @param name the name of the variable to set; if multiple variables
472- * {@code name} are prepared, all of them are set.
473- * @param v the value to set.
457+ * {@code name} are prepared, all of them are set.
458+ * @param v the value to set.
474459 * @return this BoundStatement.
475- *
476460 * @throws IllegalArgumentException if {@code name} is not a prepared
477- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
478- * @throws InvalidTypeException if (any occurrence of) {@code name} is
479- * not of type FLOAT.
461+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
462+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
463+ * not of type FLOAT.
480464 */
481465 public BoundStatement setFloat(String name, float v) {
482466 int[] indexes = metadata().getAllIdx(name);
@@ -494,9 +478,8 @@
494478 * @param i the index of the variable to set.
495479 * @param v the value to set.
496480 * @return this BoundStatement.
497- *
498481 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
499- * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
482+ * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
500483 */
501484 public BoundStatement setDouble(int i, double v) {
502485 metadata().checkType(i, DataType.Name.DOUBLE);
@@ -508,14 +491,13 @@
508491 * provided double.
509492 *
510493 * @param name the name of the variable to set; if multiple variables
511- * {@code name} are prepared, all of them are set.
512- * @param v the value to set.
494+ * {@code name} are prepared, all of them are set.
495+ * @param v the value to set.
513496 * @return this BoundStatement.
514- *
515497 * @throws IllegalArgumentException if {@code name} is not a prepared
516- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
517- * @throws InvalidTypeException if (any occurrence of) {@code name} is
518- * not of type DOUBLE.
498+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
499+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
500+ * not of type DOUBLE.
519501 */
520502 public BoundStatement setDouble(String name, double v) {
521503 int[] indexes = metadata().getAllIdx(name);
@@ -533,15 +515,14 @@
533515 * @param i the index of the variable to set.
534516 * @param v the value to set.
535517 * @return this BoundStatement.
536- *
537518 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
538- * @throws InvalidTypeException if column {@code i} is of neither of the
539- * following types: VARCHAR, TEXT or ASCII.
519+ * @throws InvalidTypeException if column {@code i} is of neither of the
520+ * following types: VARCHAR, TEXT or ASCII.
540521 */
541522 public BoundStatement setString(int i, String v) {
542523 DataType.Name type = metadata().checkType(i, DataType.Name.VARCHAR,
543- DataType.Name.TEXT,
544- DataType.Name.ASCII);
524+ DataType.Name.TEXT,
525+ DataType.Name.ASCII);
545526 switch (type) {
546527 case ASCII:
547528 return setValue(i, v == null ? null : TypeCodec.StringCodec.asciiInstance.serialize(v));
@@ -558,14 +539,13 @@
558539 * provided string.
559540 *
560541 * @param name the name of the variable to set; if multiple variables
561- * {@code name} are prepared, all of them are set.
562- * @param v the value to set.
542+ * {@code name} are prepared, all of them are set.
543+ * @param v the value to set.
563544 * @return this BoundStatement.
564- *
565545 * @throws IllegalArgumentException if {@code name} is not a prepared
566- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
567- * @throws InvalidTypeException if (any occurrence of) {@code name} is
568- * of neither of the following types: VARCHAR, TEXT or ASCII.
546+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
547+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
548+ * of neither of the following types: VARCHAR, TEXT or ASCII.
569549 */
570550 public BoundStatement setString(String name, String v) {
571551 int[] indexes = metadata().getAllIdx(name);
@@ -576,7 +556,7 @@
576556
577557 /**
578558 * Sets the {@code i}th value to the provided byte buffer.
579- *
559+ * <p/>
580560 * This method validate that the type of the column set is BLOB. If you
581561 * want to insert manually serialized data into columns of another type,
582562 * use {@link #setBytesUnsafe} instead.
@@ -584,9 +564,8 @@
584564 * @param i the index of the variable to set.
585565 * @param v the value to set.
586566 * @return this BoundStatement.
587- *
588567 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
589- * @throws InvalidTypeException if column {@code i} is not of type BLOB.
568+ * @throws InvalidTypeException if column {@code i} is not of type BLOB.
590569 */
591570 public BoundStatement setBytes(int i, ByteBuffer v) {
592571 metadata().checkType(i, DataType.Name.BLOB);
@@ -596,19 +575,18 @@
596575 /**
597576 * Sets the value for (all occurrences of) variable {@code name} to the
598577 * provided byte buffer.
599- *
578+ * <p/>
600579 * This method validate that the type of the column set is BLOB. If you
601580 * want to insert manually serialized data into columns of another type,
602581 * use {@link #setBytesUnsafe} instead.
603582 *
604583 * @param name the name of the variable to set; if multiple variables
605- * {@code name} are prepared, all of them are set.
606- * @param v the value to set.
584+ * {@code name} are prepared, all of them are set.
585+ * @param v the value to set.
607586 * @return this BoundStatement.
608- *
609587 * @throws IllegalArgumentException if {@code name} is not a prepared
610- * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
611- * @throws InvalidTypeException if (any occurrence of) {@code name} is not of type BLOB.
588+ * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
589+ * @throws InvalidTypeException if (any occurrence of) {@code name} is not of type BLOB.
612590 */
613591 public BoundStatement setBytes(String name, ByteBuffer v) {
614592 int[] indexes = metadata().getAllIdx(name);
@@ -622,7 +600,7 @@
622600
623601 /**
624602 * Sets the {@code i}th value to the provided byte buffer.
625- *
603+ * <p/>
626604 * Contrary to {@link #setBytes}, this method does not check the
627605 * type of the column set. If you insert data that is not compatible with
628606 * the type of the column, you will get an {@code InvalidQueryException} at
@@ -631,7 +609,6 @@
631609 * @param i the index of the variable to set.
632610 * @param v the value to set.
633611 * @return this BoundStatement.
634- *
635612 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
636613 */
637614 public BoundStatement setBytesUnsafe(int i, ByteBuffer v) {
@@ -641,19 +618,18 @@
641618 /**
642619 * Sets the value for (all occurrences of) variable {@code name} to the
643620 * provided byte buffer.
644- *
621+ * <p/>
645622 * Contrary to {@link #setBytes}, this method does not check the
646623 * type of the column set. If you insert data that is not compatible with
647624 * the type of the column, you will get an {@code InvalidQueryException} at
648625 * execute time.
649626 *
650627 * @param name the name of the variable to set; if multiple variables
651- * {@code name} are prepared, all of them are set.
652- * @param v the value to set.
628+ * {@code name} are prepared, all of them are set.
629+ * @param v the value to set.
653630 * @return this BoundStatement.
654- *
655631 * @throws IllegalArgumentException if {@code name} is not a prepared
656- * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
632+ * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
657633 */
658634 public BoundStatement setBytesUnsafe(String name, ByteBuffer v) {
659635 int[] indexes = metadata().getAllIdx(name);
@@ -669,9 +645,8 @@
669645 * @param i the index of the variable to set.
670646 * @param v the value to set.
671647 * @return this BoundStatement.
672- *
673648 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
674- * @throws InvalidTypeException if column {@code i} is not of type VARINT.
649+ * @throws InvalidTypeException if column {@code i} is not of type VARINT.
675650 */
676651 public BoundStatement setVarint(int i, BigInteger v) {
677652 metadata().checkType(i, DataType.Name.VARINT);
@@ -683,14 +658,13 @@
683658 * provided big integer.
684659 *
685660 * @param name the name of the variable to set; if multiple variables
686- * {@code name} are prepared, all of them are set.
687- * @param v the value to set.
661+ * {@code name} are prepared, all of them are set.
662+ * @param v the value to set.
688663 * @return this BoundStatement.
689- *
690664 * @throws IllegalArgumentException if {@code name} is not a prepared
691- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
692- * @throws InvalidTypeException if (any occurrence of) {@code name} is
693- * not of type VARINT.
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 VARINT.
694668 */
695669 public BoundStatement setVarint(String name, BigInteger v) {
696670 int[] indexes = metadata().getAllIdx(name);
@@ -708,9 +682,8 @@
708682 * @param i the index of the variable to set.
709683 * @param v the value to set.
710684 * @return this BoundStatement.
711- *
712685 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
713- * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
686+ * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
714687 */
715688 public BoundStatement setDecimal(int i, BigDecimal v) {
716689 metadata().checkType(i, DataType.Name.DECIMAL);
@@ -722,14 +695,13 @@
722695 * provided big decimal.
723696 *
724697 * @param name the name of the variable to set; if multiple variables
725- * {@code name} are prepared, all of them are set.
726- * @param v the value to set.
698+ * {@code name} are prepared, all of them are set.
699+ * @param v the value to set.
727700 * @return this BoundStatement.
728- *
729701 * @throws IllegalArgumentException if {@code name} is not a prepared
730- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
731- * @throws InvalidTypeException if (any occurrence of) {@code name} is
732- * not of type DECIMAL.
702+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
703+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
704+ * not of type DECIMAL.
733705 */
734706 public BoundStatement setDecimal(String name, BigDecimal v) {
735707 int[] indexes = metadata().getAllIdx(name);
@@ -747,15 +719,14 @@
747719 * @param i the index of the variable to set.
748720 * @param v the value to set.
749721 * @return this BoundStatement.
750- *
751722 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
752- * @throws InvalidTypeException if column {@code i} is not of type UUID or
753- * TIMEUUID, or if column {@code i} is of type TIMEUUID but {@code v} is
754- * not a type 1 UUID.
723+ * @throws InvalidTypeException if column {@code i} is not of type UUID or
724+ * TIMEUUID, or if column {@code i} is of type TIMEUUID but {@code v} is
725+ * not a type 1 UUID.
755726 */
756727 public BoundStatement setUUID(int i, UUID v) {
757728 DataType.Name type = metadata().checkType(i, DataType.Name.UUID,
758- DataType.Name.TIMEUUID);
729+ DataType.Name.TIMEUUID);
759730
760731 if (v == null)
761732 return setValue(i, null);
@@ -764,8 +735,8 @@
764735 throw new InvalidTypeException(String.format("%s is not a Type 1 (time-based) UUID", v));
765736
766737 return type == DataType.Name.UUID
767- ? setValue(i, TypeCodec.UUIDCodec.instance.serialize(v))
768- : setValue(i, TypeCodec.TimeUUIDCodec.instance.serialize(v));
738+ ? setValue(i, TypeCodec.UUIDCodec.instance.serialize(v))
739+ : setValue(i, TypeCodec.TimeUUIDCodec.instance.serialize(v));
769740 }
770741
771742 /**
@@ -773,15 +744,14 @@
773744 * provided UUID.
774745 *
775746 * @param name the name of the variable to set; if multiple variables
776- * {@code name} are prepared, all of them are set.
777- * @param v the value to set.
747+ * {@code name} are prepared, all of them are set.
748+ * @param v the value to set.
778749 * @return this BoundStatement.
779- *
780750 * @throws IllegalArgumentException if {@code name} is not a prepared
781- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
782- * @throws InvalidTypeException if (any occurrence of) {@code name} is
783- * not of type UUID or TIMEUUID, or if column {@code name} is of type
784- * TIMEUUID but {@code v} is not a type 1 UUID.
751+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
752+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
753+ * not of type UUID or TIMEUUID, or if column {@code name} is of type
754+ * TIMEUUID but {@code v} is not a type 1 UUID.
785755 */
786756 public BoundStatement setUUID(String name, UUID v) {
787757 int[] indexes = metadata().getAllIdx(name);
@@ -801,9 +771,8 @@
801771 * @param i the index of the variable to set.
802772 * @param v the value to set.
803773 * @return this BoundStatement.
804- *
805774 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
806- * @throws InvalidTypeException if column {@code i} is not of type INET.
775+ * @throws InvalidTypeException if column {@code i} is not of type INET.
807776 */
808777 public BoundStatement setInet(int i, InetAddress v) {
809778 metadata().checkType(i, DataType.Name.INET);
@@ -815,14 +784,13 @@
815784 * provided inet address.
816785 *
817786 * @param name the name of the variable to set; if multiple variables
818- * {@code name} are prepared, all of them are set.
819- * @param v the value to set.
787+ * {@code name} are prepared, all of them are set.
788+ * @param v the value to set.
820789 * @return this BoundStatement.
821- *
822790 * @throws IllegalArgumentException if {@code name} is not a prepared
823- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
824- * @throws InvalidTypeException if (any occurrence of) {@code name} is
825- * not of type INET.
791+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
792+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
793+ * not of type INET.
826794 */
827795 public BoundStatement setInet(String name, InetAddress v) {
828796 int[] indexes = metadata().getAllIdx(name);
@@ -836,16 +804,15 @@
836804
837805 /**
838806 * Sets the {@code i}th value to the provided {@link Token}.
839- * <p>
807+ * <p/>
840808 * {@link #setPartitionKeyToken(Token)} should generally be preferred if you
841809 * have a single token variable.
842810 *
843811 * @param i the index of the variable to set.
844812 * @param v the value to set.
845813 * @return this BoundStatement.
846- *
847814 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
848- * @throws InvalidTypeException if column {@code i} is not of the type of the token's value.
815+ * @throws InvalidTypeException if column {@code i} is not of the type of the token's value.
849816 */
850817 public BoundStatement setToken(int i, Token v) {
851818 metadata().checkType(i, v.getType().getName());
@@ -855,10 +822,10 @@
855822 /**
856823 * Sets the value for (all occurrences of) variable {@code name} to the
857824 * provided token.
858- * <p>
825+ * <p/>
859826 * {@link #setPartitionKeyToken(Token)} should generally be preferred if you
860827 * have a single token variable.
861- * <p>
828+ * <p/>
862829 * If you have multiple token variables, use positional binding ({@link #setToken(int, Token)},
863830 * or named bind markers:
864831 * <pre>
@@ -869,14 +836,13 @@
869836 * </pre>
870837 *
871838 * @param name the name of the variable to set; if multiple variables
872- * {@code name} are prepared, all of them are set.
873- * @param v the value to set.
839+ * {@code name} are prepared, all of them are set.
840+ * @param v the value to set.
874841 * @return this BoundStatement.
875- *
876842 * @throws IllegalArgumentException if {@code name} is not a prepared
877- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
878- * @throws InvalidTypeException if (any occurrence of) {@code name} is
879- * not of the type of the token's value.
843+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
844+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
845+ * not of the type of the token's value.
880846 */
881847 public BoundStatement setToken(String name, Token v) {
882848 int[] indexes = metadata().getAllIdx(name);
@@ -889,7 +855,7 @@
889855 * Sets the value for (all occurrences of) variable "{@code partition key token}"
890856 * to the provided token (this is the name generated by Cassandra for markers
891857 * corresponding to a {@code token(...)} call).
892- * <p>
858+ * <p/>
893859 * This method is a shorthand for statements with a single token variable:
894860 * <pre>
895861 * {@code
@@ -909,11 +875,10 @@
909875 *
910876 * @param v the value to set.
911877 * @return this BoundStatement.
912- *
913878 * @throws IllegalArgumentException if {@code name} is not a prepared
914- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
915- * @throws InvalidTypeException if (any occurrence of) {@code name} is
916- * not of the type of the token's value.
879+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
880+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
881+ * not of the type of the token's value.
917882 */
918883 public BoundStatement setPartitionKeyToken(Token v) {
919884 return setToken("partition key token", v);
@@ -921,20 +886,19 @@
921886
922887 /**
923888 * Sets the {@code i}th value to the provided list.
924- * <p>
889+ * <p/>
925890 * Please note that {@code null} values are not supported inside collection by CQL.
926891 *
927892 * @param <T> the type of the elements of the list to set.
928- * @param i the index of the variable to set.
929- * @param v the value to set.
893+ * @param i the index of the variable to set.
894+ * @param v the value to set.
930895 * @return this BoundStatement.
931- *
932896 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
933- * @throws InvalidTypeException if column {@code i} is not a list type or
934- * if the elements of {@code v} are not of the type of the elements of
935- * column {@code i}.
936- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
937- * by CQL.
897+ * @throws InvalidTypeException if column {@code i} is not a list type or
898+ * if the elements of {@code v} are not of the type of the elements of
899+ * column {@code i}.
900+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
901+ * by CQL.
938902 */
939903 public <T> BoundStatement setList(int i, List<T> v) {
940904 DataType type = metadata().getType(i);
@@ -960,22 +924,21 @@
960924 /**
961925 * Sets the value for (all occurrences of) variable {@code name} to the
962926 * provided list.
963- * <p>
927+ * <p/>
964928 * Please note that {@code null} values are not supported inside collection by CQL.
965929 *
966- * @param <T> the type of the elements of the list to set.
930+ * @param <T> the type of the elements of the list to set.
967931 * @param name the name of the variable to set; if multiple variables
968- * {@code name} are prepared, all of them are set.
969- * @param v the value to set.
932+ * {@code name} are prepared, all of them are set.
933+ * @param v the value to set.
970934 * @return this BoundStatement.
971- *
972935 * @throws IllegalArgumentException if {@code name} is not a prepared
973- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
974- * @throws InvalidTypeException if (any occurrence of) {@code name} is
975- * not a list type or if the elements of {@code v} are not of the type of
976- * the elements of column {@code name}.
977- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
978- * by CQL.
936+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
937+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
938+ * not a list type or if the elements of {@code v} are not of the type of
939+ * the elements of column {@code name}.
940+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
941+ * by CQL.
979942 */
980943 public <T> BoundStatement setList(String name, List<T> v) {
981944 int[] indexes = metadata().getAllIdx(name);
@@ -986,21 +949,20 @@
986949
987950 /**
988951 * Sets the {@code i}th value to the provided map.
989- * <p>
952+ * <p/>
990953 * Please note that {@code null} values are not supported inside collection by CQL.
991954 *
992955 * @param <K> the type of the keys for the map to set.
993956 * @param <V> the type of the values for the map to set.
994- * @param i the index of the variable to set.
995- * @param v the value to set.
957+ * @param i the index of the variable to set.
958+ * @param v the value to set.
996959 * @return this BoundStatement.
997- *
998960 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
999- * @throws InvalidTypeException if column {@code i} is not a map type or
1000- * if the elements (keys or values) of {@code v} are not of the type of the
1001- * elements of column {@code i}.
1002- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1003- * by CQL.
961+ * @throws InvalidTypeException if column {@code i} is not a map type or
962+ * if the elements (keys or values) of {@code v} are not of the type of the
963+ * elements of column {@code i}.
964+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
965+ * by CQL.
1004966 */
1005967 public <K, V> BoundStatement setMap(int i, Map<K, V> v) {
1006968 DataType type = metadata().getType(i);
@@ -1028,23 +990,22 @@
1028990 /**
1029991 * Sets the value for (all occurrences of) variable {@code name} to the
1030992 * provided map.
1031- * <p>
993+ * <p/>
1032994 * Please note that {@code null} values are not supported inside collection by CQL.
1033995 *
1034- * @param <K> the type of the keys for the map to set.
1035- * @param <V> the type of the values for the map to set.
996+ * @param <K> the type of the keys for the map to set.
997+ * @param <V> the type of the values for the map to set.
1036998 * @param name the name of the variable to set; if multiple variables
1037- * {@code name} are prepared, all of them are set.
1038- * @param v the value to set.
999+ * {@code name} are prepared, all of them are set.
1000+ * @param v the value to set.
10391001 * @return this BoundStatement.
1040- *
10411002 * @throws IllegalArgumentException if {@code name} is not a prepared
1042- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
1043- * @throws InvalidTypeException if (any occurrence of) {@code name} is
1044- * not a map type or if the elements (keys or values) of {@code v} are not of
1045- * the type of the elements of column {@code name}.
1046- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1047- * by CQL.
1003+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
1004+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
1005+ * not a map type or if the elements (keys or values) of {@code v} are not of
1006+ * the type of the elements of column {@code name}.
1007+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1008+ * by CQL.
10481009 */
10491010 public <K, V> BoundStatement setMap(String name, Map<K, V> v) {
10501011 int[] indexes = metadata().getAllIdx(name);
@@ -1055,20 +1016,19 @@
10551016
10561017 /**
10571018 * Sets the {@code i}th value to the provided set.
1058- * <p>
1019+ * <p/>
10591020 * Please note that {@code null} values are not supported inside collection by CQL.
10601021 *
10611022 * @param <T> the type of the elements of the set to set.
1062- * @param i the index of the variable to set.
1063- * @param v the value to set.
1023+ * @param i the index of the variable to set.
1024+ * @param v the value to set.
10641025 * @return this BoundStatement.
1065- *
10661026 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
1067- * @throws InvalidTypeException if column {@code i} is not a set type or
1068- * if the elements of {@code v} are not of the type of the elements of
1069- * column {@code i}.
1070- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1071- * by CQL.
1027+ * @throws InvalidTypeException if column {@code i} is not a set type or
1028+ * if the elements of {@code v} are not of the type of the elements of
1029+ * column {@code i}.
1030+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1031+ * by CQL.
10721032 */
10731033 public <T> BoundStatement setSet(int i, Set<T> v) {
10741034 DataType type = metadata().getType(i);
@@ -1093,22 +1053,21 @@
10931053 /**
10941054 * Sets the value for (all occurrences of) variable {@code name} to the
10951055 * provided set.
1096- * <p>
1056+ * <p/>
10971057 * Please note that {@code null} values are not supported inside collection by CQL.
10981058 *
1099- * @param <T> the type of the elements of the set to set.
1059+ * @param <T> the type of the elements of the set to set.
11001060 * @param name the name of the variable to set; if multiple variables
1101- * {@code name} are prepared, all of them are set.
1102- * @param v the value to set.
1061+ * {@code name} are prepared, all of them are set.
1062+ * @param v the value to set.
11031063 * @return this BoundStatement.
1104- *
11051064 * @throws IllegalArgumentException if {@code name} is not a prepared
1106- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
1107- * @throws InvalidTypeException if (any occurrence of) {@code name} is
1108- * not a map type or if the elements of {@code v} are not of the type of
1109- * the elements of column {@code name}.
1110- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1111- * by CQL.
1065+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
1066+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
1067+ * not a map type or if the elements of {@code v} are not of the type of
1068+ * the elements of column {@code name}.
1069+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
1070+ * by CQL.
11121071 */
11131072 public <T> BoundStatement setSet(String name, Set<T> v) {
11141073 int[] indexes = metadata().getAllIdx(name);
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,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
20-import com.google.common.collect.ImmutableMap;
21-
2218 import com.datastax.driver.core.exceptions.DriverInternalError;
2319 import com.datastax.driver.core.utils.Bytes;
20+import com.google.common.collect.ImmutableMap;
21+
22+import java.util.*;
2423
2524 /*
2625 * Helps transforming Cassandra types (as read in the schema tables) to
@@ -44,24 +43,24 @@
4443 private static final String MAP_TYPE = "org.apache.cassandra.db.marshal.MapType";
4544
4645 private static ImmutableMap<String, DataType> cassTypeToDataType =
47- new ImmutableMap.Builder<String, DataType>()
48- .put("org.apache.cassandra.db.marshal.AsciiType", DataType.ascii())
49- .put("org.apache.cassandra.db.marshal.LongType", DataType.bigint())
50- .put("org.apache.cassandra.db.marshal.BytesType", DataType.blob())
51- .put("org.apache.cassandra.db.marshal.BooleanType", DataType.cboolean())
52- .put("org.apache.cassandra.db.marshal.CounterColumnType", DataType.counter())
53- .put("org.apache.cassandra.db.marshal.DecimalType", DataType.decimal())
54- .put("org.apache.cassandra.db.marshal.DoubleType", DataType.cdouble())
55- .put("org.apache.cassandra.db.marshal.FloatType", DataType.cfloat())
56- .put("org.apache.cassandra.db.marshal.InetAddressType", DataType.inet())
57- .put("org.apache.cassandra.db.marshal.Int32Type", DataType.cint())
58- .put("org.apache.cassandra.db.marshal.UTF8Type", DataType.text())
59- .put("org.apache.cassandra.db.marshal.TimestampType", DataType.timestamp())
60- .put("org.apache.cassandra.db.marshal.DateType", DataType.timestamp())
61- .put("org.apache.cassandra.db.marshal.UUIDType", DataType.uuid())
62- .put("org.apache.cassandra.db.marshal.IntegerType", DataType.varint())
63- .put("org.apache.cassandra.db.marshal.TimeUUIDType", DataType.timeuuid())
64- .build();
46+ new ImmutableMap.Builder<String, DataType>()
47+ .put("org.apache.cassandra.db.marshal.AsciiType", DataType.ascii())
48+ .put("org.apache.cassandra.db.marshal.LongType", DataType.bigint())
49+ .put("org.apache.cassandra.db.marshal.BytesType", DataType.blob())
50+ .put("org.apache.cassandra.db.marshal.BooleanType", DataType.cboolean())
51+ .put("org.apache.cassandra.db.marshal.CounterColumnType", DataType.counter())
52+ .put("org.apache.cassandra.db.marshal.DecimalType", DataType.decimal())
53+ .put("org.apache.cassandra.db.marshal.DoubleType", DataType.cdouble())
54+ .put("org.apache.cassandra.db.marshal.FloatType", DataType.cfloat())
55+ .put("org.apache.cassandra.db.marshal.InetAddressType", DataType.inet())
56+ .put("org.apache.cassandra.db.marshal.Int32Type", DataType.cint())
57+ .put("org.apache.cassandra.db.marshal.UTF8Type", DataType.text())
58+ .put("org.apache.cassandra.db.marshal.TimestampType", DataType.timestamp())
59+ .put("org.apache.cassandra.db.marshal.DateType", DataType.timestamp())
60+ .put("org.apache.cassandra.db.marshal.UUIDType", DataType.uuid())
61+ .put("org.apache.cassandra.db.marshal.IntegerType", DataType.varint())
62+ .put("org.apache.cassandra.db.marshal.TimeUUIDType", DataType.timeuuid())
63+ .build();
6564
6665 static DataType parseOne(String className) {
6766 if (isReversed(className)) {
@@ -142,9 +141,9 @@
142141
143142 private ParseResult(DataType type, boolean reversed) {
144143 this(false,
145- Collections.<DataType>singletonList(type),
146- Collections.<Boolean>singletonList(reversed),
147- Collections.<String, DataType>emptyMap());
144+ Collections.<DataType>singletonList(type),
145+ Collections.<Boolean>singletonList(reversed),
146+ Collections.<String, DataType>emptyMap());
148147 }
149148
150149 private ParseResult(boolean isComposite, List<DataType> types, List<Boolean> reversed, Map<String, DataType> collections) {
@@ -328,8 +327,8 @@
328327 */
329328 private static boolean isIdentifierChar(int c) {
330329 return (c >= '0' && c <= '9')
331- || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
332- || c == '-' || c == '+' || c == '.' || c == '_' || c == '&';
330+ || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
331+ || c == '-' || c == '+' || c == '.' || c == '_' || c == '&';
333332 }
334333
335334 // left idx positioned on the character stopping the read
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 +220 −242
@@ -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.Objects;
@@ -34,16 +30,19 @@
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 /**
4544 * Information and known state of a Cassandra cluster.
46- * <p>
45+ * <p/>
4746 * This is the main entry point of the driver. A simple example of access to a
4847 * Cassandra cluster would be:
4948 * <pre>
@@ -53,7 +52,7 @@
5352 * for (Row row : session.execute("SELECT * FROM table1"))
5453 * // do something ...
5554 * </pre>
56- * <p>
55+ * <p/>
5756 * A cluster object maintains a permanent connection to one of the cluster nodes
5857 * which it uses solely to maintain information on the state and current
5958 * topology of the cluster. Using the connection, the driver will discover all
@@ -67,7 +66,7 @@
6766 @VisibleForTesting
6867 static final int NEW_NODE_DELAY_SECONDS = SystemProperties.getInt("com.datastax.driver.NEW_NODE_DELAY_SECONDS", 1);
6968 private static final int NON_BLOCKING_EXECUTOR_SIZE = SystemProperties.getInt("com.datastax.driver.NON_BLOCKING_EXECUTOR_SIZE",
70- Runtime.getRuntime().availableProcessors());
69+ Runtime.getRuntime().availableProcessors());
7170
7271 private static final ResourceBundle driverProperties = ResourceBundle.getBundle("com.datastax.driver.core.Driver");
7372
@@ -83,13 +82,13 @@
8382
8483 /**
8584 * Constructs a new Cluster instance.
86- * <p>
85+ * <p/>
8786 * This constructor is mainly exposed so Cluster can be sub-classed as a means to make testing/mocking
8887 * easier or to "intercept" its method call. Most users shouldn't extend this class however and
8988 * should prefer either using the {@link #builder} or calling {@link #buildFrom} with a custom
9089 * Initializer.
9190 *
92- * @param name the name to use for the cluster (this is not the Cassandra cluster name, see {@link #getClusterName}).
91+ * @param name the name to use for the cluster (this is not the Cassandra cluster name, see {@link #getClusterName}).
9392 * @param contactPoints the list of contact points to use for the new cluster.
9493 * @param configuration the configuration for the new cluster.
9594 */
@@ -99,7 +98,7 @@
9998
10099 /**
101100 * Constructs a new Cluster instance.
102- * <p>
101+ * <p/>
103102 * This constructor is mainly exposed so Cluster can be sub-classed as a means to make testing/mocking
104103 * easier or to "intercept" its method call. Most users shouldn't extend this class however and
105104 * should prefer using the {@link #builder}.
@@ -109,9 +108,9 @@
109108 */
110109 protected Cluster(Initializer initializer) {
111110 this(initializer.getClusterName(),
112- checkNotEmpty(initializer.getContactPoints()),
113- initializer.getConfiguration(),
114- initializer.getInitialListeners());
111+ checkNotEmpty(initializer.getContactPoints()),
112+ initializer.getConfiguration(),
113+ initializer.getInitialListeners());
115114 }
116115
117116 private static List<InetSocketAddress> checkNotEmpty(List<InetSocketAddress> contactPoints) {
@@ -126,35 +125,34 @@
126125
127126 /**
128127 * Initialize this Cluster instance.
129- *
128+ * <p/>
130129 * This method creates an initial connection to one of the contact points
131130 * used to construct the {@code Cluster} instance. That connection is then
132131 * used to populate the cluster {@link Metadata}.
133- * <p>
132+ * <p/>
134133 * Calling this method is optional in the sense that any call to one of the
135134 * {@code connect} methods of this object will automatically trigger a call
136135 * to this method beforehand. It is thus only useful to call this method if
137136 * for some reason you want to populate the metadata (or test that at least
138137 * one contact point can be reached) without creating a first {@code
139138 * Session}.
140- * <p>
139+ * <p/>
141140 * Please note that this method only creates one control connection for
142141 * gathering cluster metadata. In particular, it doesn't create any connection pools.
143142 * Those are created when a new {@code Session} is created through
144143 * {@code connect}.
145- * <p>
144+ * <p/>
146145 * This method has no effect if the cluster is already initialized.
147146 *
148147 * @return this {@code Cluster} object.
149- *
150148 * @throws NoHostAvailableException if no host amongst the contact points
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.
149+ * can be reached.
150+ * @throws AuthenticationException if an authentication error occurs
151+ * while contacting the initial contact points.
152+ * @throws IllegalStateException if the Cluster was closed prior to calling
153+ * this method. This can occur either directly (through {@link #close()} or
154+ * {@link #closeAsync()}), or as a result of an error while initializing the
155+ * Cluster.
158156 */
159157 public Cluster init() {
160158 this.manager.init();
@@ -163,18 +161,17 @@
163161
164162 /**
165163 * Build a new cluster based on the provided initializer.
166- * <p>
164+ * <p/>
167165 * Note that for building a cluster pragmatically, Cluster.Builder
168166 * provides a slightly less verbose shortcut with {@link Builder#build}.
169- * <p>
167+ * <p/>
170168 * Also note that that all the contact points provided by {@code
171169 * initializer} must share the same port.
172170 *
173171 * @param initializer the Cluster.Initializer to use
174172 * @return the newly created Cluster instance
175- *
176173 * @throws IllegalArgumentException if the list of contact points provided
177- * by {@code initializer} is empty or if not all those contact points have the same port.
174+ * by {@code initializer} is empty or if not all those contact points have the same port.
178175 */
179176 public static Cluster buildFrom(Initializer initializer) {
180177 return new Cluster(initializer);
@@ -182,7 +179,7 @@
182179
183180 /**
184181 * Creates a new {@link Cluster.Builder} instance.
185- * <p>
182+ * <p/>
186183 * This is a convenience method for {@code new Cluster.Builder()}.
187184 *
188185 * @return the new cluster builder.
@@ -193,7 +190,7 @@
193190
194191 /**
195192 * Returns the current version of the driver.
196- * <p>
193+ * <p/>
197194 * This is intended for products that wrap or extend the driver, as a way to check
198195 * compatibility if end-users override the driver version in their application.
199196 *
@@ -205,16 +202,16 @@
205202
206203 /**
207204 * Creates a new session on this cluster but does not initialize it.
208- * <p>
205+ * <p/>
209206 * Because this method does not perform any initialization, it cannot fail.
210207 * The initialization of the session (the connection of the Session to the
211208 * Cassandra nodes) will occur if either the {@link Session#init} method is
212209 * called explicitly, or whenever the returned session object is used.
213- * <p>
210+ * <p/>
214211 * Once a session returned by this method gets initialized (see above), it
215212 * will be set to no keyspace. If you want to set such session to a
216213 * keyspace, you will have to explicitly execute a 'USE mykeyspace' query.
217- * <p>
214+ * <p/>
218215 * Note that if you do not particularly need to defer initialization, it is
219216 * simpler to use one of the {@code connect()} method of this class.
220217 *
@@ -227,23 +224,22 @@
227224
228225 /**
229226 * Creates a new session on this cluster and initialize it.
230- * <p>
227+ * <p/>
231228 * Note that this method will initialize the newly created session, trying
232229 * to connect to the Cassandra nodes before returning. If you only want to
233230 * create a Session object without initializing it right away, see
234231 * {@link #newSession}.
235232 *
236233 * @return a new session on this cluster sets to no keyspace.
237- *
238234 * @throws NoHostAvailableException if the Cluster has not been initialized
239- * yet ({@link #init} has not be called and this is the first connect call)
240- * and no host amongst the contact points can be reached.
241- * @throws AuthenticationException if an authentication error occurs while
242- * contacting the initial contact points.
243- * @throws IllegalStateException if the Cluster was closed prior to calling
244- * this method. This can occur either directly (through {@link #close()} or
245- * {@link #closeAsync()}), or as a result of an error while initializing the
246- * Cluster.
235+ * yet ({@link #init} has not be called and this is the first connect call)
236+ * and no host amongst the contact points can be reached.
237+ * @throws AuthenticationException if an authentication error occurs while
238+ * contacting the initial contact points.
239+ * @throws IllegalStateException if the Cluster was closed prior to calling
240+ * this method. This can occur either directly (through {@link #close()} or
241+ * {@link #closeAsync()}), or as a result of an error while initializing the
242+ * Cluster.
247243 */
248244 public Session connect() {
249245 try {
@@ -256,28 +252,27 @@
256252 /**
257253 * Creates a new session on this cluster, initialize it and sets the
258254 * keyspace to the provided one.
259- * <p>
255+ * <p/>
260256 * Note that this method will initialize the newly created session, trying
261257 * to connect to the Cassandra nodes before returning. If you only want to
262258 * create a Session object without initializing it right away, see
263259 * {@link #newSession}.
264260 *
265261 * @param keyspace The name of the keyspace to use for the created
266- * {@code Session}.
262+ * {@code Session}.
267263 * @return a new session on this cluster sets to keyspace
268264 * {@code keyspaceName}.
269- *
270265 * @throws NoHostAvailableException if the Cluster has not been initialized
271- * yet ({@link #init} has not be called and this is the first connect call)
272- * and no host amongst the contact points can be reached, or if no host can
273- * be contacted to set the {@code keyspace}.
274- * @throws AuthenticationException if an authentication error occurs while
275- * contacting the initial contact points.
276- * @throws InvalidQueryException if the keyspace does not exists.
277- * @throws IllegalStateException if the Cluster was closed prior to calling
278- * this method. This can occur either directly (through {@link #close()} or
279- * {@link #closeAsync()}), or as a result of an error while initializing the
280- * Cluster.
266+ * yet ({@link #init} has not be called and this is the first connect call)
267+ * and no host amongst the contact points can be reached, or if no host can
268+ * be contacted to set the {@code keyspace}.
269+ * @throws AuthenticationException if an authentication error occurs while
270+ * contacting the initial contact points.
271+ * @throws InvalidQueryException if the keyspace does not exists.
272+ * @throws IllegalStateException if the Cluster was closed prior to calling
273+ * this method. This can occur either directly (through {@link #close()} or
274+ * {@link #closeAsync()}), or as a result of an error while initializing the
275+ * Cluster.
281276 */
282277 public Session connect(String keyspace) {
283278 try {
@@ -289,23 +284,20 @@
289284
290285 /**
291286 * Creates a new session on this cluster and initializes it asynchronously.
292- *
287+ * <p/>
293288 * This will also initialize the {@code Cluster} if needed; note that cluster
294289 * initialization happens synchronously on the thread that called this method.
295290 * Therefore it is recommended to initialize the cluster at application
296291 * startup, and not rely on this method to do it.
297292 *
298293 * @return a future that will complete when the session is fully initialized.
299- *
300294 * @throws NoHostAvailableException if the Cluster has not been initialized
301- * yet ({@link #init} has not been called and this is the first connect call)
302- * and no host amongst the contact points can be reached.
303- *
304- * @throws IllegalStateException if the Cluster was closed prior to calling
305- * this method. This can occur either directly (through {@link #close()} or
306- * {@link #closeAsync()}), or as a result of an error while initializing the
307- * Cluster.
308- *
295+ * yet ({@link #init} has not been called and this is the first connect call)
296+ * and no host amongst the contact points can be reached.
297+ * @throws IllegalStateException if the Cluster was closed prior to calling
298+ * this method. This can occur either directly (through {@link #close()} or
299+ * {@link #closeAsync()}), or as a result of an error while initializing the
300+ * Cluster.
309301 * @see #connect()
310302 */
311303 public ListenableFuture<Session> connectAsync() {
@@ -315,24 +307,22 @@
315307 /**
316308 * Creates a new session on this cluster, and initializes it to the given
317309 * keyspace asynchronously.
318- *
310+ * <p/>
319311 * This will also initialize the {@code Cluster} if needed; note that cluster
320312 * initialization happens synchronously on the thread that called this method.
321313 * Therefore it is recommended to initialize the cluster at application
322314 * startup, and not rely on this method to do it.
323315 *
324316 * @param keyspace The name of the keyspace to use for the created
325- * {@code Session}.
317+ * {@code Session}.
326318 * @return a future that will complete when the session is fully initialized.
327- *
328319 * @throws NoHostAvailableException if the Cluster has not been initialized
329- * yet ({@link #init} has not been called and this is the first connect call)
330- * and no host amongst the contact points can be reached.
331- *
332- * @throws IllegalStateException if the Cluster was closed prior to calling
333- * this method. This can occur either directly (through {@link #close()} or
334- * {@link #closeAsync()}), or as a result of an error while initializing the
335- * Cluster.
320+ * yet ({@link #init} has not been called and this is the first connect call)
321+ * and no host amongst the contact points can be reached.
322+ * @throws IllegalStateException if the Cluster was closed prior to calling
323+ * this method. This can occur either directly (through {@link #close()} or
324+ * {@link #closeAsync()}), or as a result of an error while initializing the
325+ * Cluster.
336326 */
337327 public ListenableFuture<Session> connectAsync(final String keyspace) {
338328 checkNotClosed(manager);
@@ -360,7 +350,7 @@
360350
361351 /**
362352 * The name of this cluster object.
363- * <p>
353+ * <p/>
364354 * Note that this is not the Cassandra cluster name, but rather a name
365355 * assigned to this Cluster object. Currently, that name is only used
366356 * for one purpose: to distinguish exposed JMX metrics when multiple
@@ -378,7 +368,7 @@
378368
379369 /**
380370 * Returns read-only metadata on the connected cluster.
381- * <p>
371+ * <p/>
382372 * This includes the known nodes with their status as seen by the driver,
383373 * as well as the schema definitions. Since this return metadata on the
384374 * connected cluster, this method may trigger the creation of a connection
@@ -386,15 +376,14 @@
386376 * has been called yet).
387377 *
388378 * @return the cluster metadata.
389- *
390379 * @throws NoHostAvailableException if the Cluster has not been initialized yet
391- * and no host amongst the contact points can be reached.
392- * @throws AuthenticationException if an authentication error occurs
393- * while contacting the initial contact points.
394- * @throws IllegalStateException if the Cluster was closed prior to calling
395- * this method. This can occur either directly (through {@link #close()} or
396- * {@link #closeAsync()}), or as a result of an error while initializing the
397- * Cluster.
380+ * and no host amongst the contact points can be reached.
381+ * @throws AuthenticationException if an authentication error occurs
382+ * while contacting the initial contact points.
383+ * @throws IllegalStateException if the Cluster was closed prior to calling
384+ * this method. This can occur either directly (through {@link #close()} or
385+ * {@link #closeAsync()}), or as a result of an error while initializing the
386+ * Cluster.
398387 */
399388 public Metadata getMetadata() {
400389 manager.init();
@@ -425,9 +414,9 @@
425414 /**
426415 * Registers the provided listener to be notified on hosts
427416 * up/down/added/removed events.
428- * <p>
417+ * <p/>
429418 * Registering the same listener multiple times is a no-op.
430- * <p>
419+ * <p/>
431420 * Note that while {@link LoadBalancingPolicy} implements
432421 * {@code Host.StateListener}, the configured load balancing does not
433422 * need to (and should not) be registered through this method to
@@ -444,7 +433,7 @@
444433
445434 /**
446435 * Unregisters the provided listener from being notified on hosts events.
447- * <p>
436+ * <p/>
448437 * This method is a no-op if {@code listener} hadn't previously be
449438 * registered against this Cluster.
450439 *
@@ -460,13 +449,13 @@
460449 /**
461450 * Registers the provided tracker to be updated with hosts read
462451 * latencies.
463- * <p>
452+ * <p/>
464453 * Registering the same listener multiple times is a no-op.
465- * <p>
454+ * <p/>
466455 * Be wary that the registered tracker {@code update} method will be call
467456 * very frequently (at the end of every query to a Cassandra host) and
468457 * should thus not be costly.
469- * <p>
458+ * <p/>
470459 * The main use case for a {@code LatencyTracker} is so
471460 * {@link LoadBalancingPolicy} can implement latency awareness
472461 * Typically, {@link LatencyAwarePolicy} registers it's own internal
@@ -485,7 +474,7 @@
485474 /**
486475 * Unregisters the provided latency tracking from being updated
487476 * with host read latencies.
488- * <p>
477+ * <p/>
489478 * This method is a no-op if {@code tracker} hadn't previously be
490479 * registered against this Cluster.
491480 *
@@ -500,7 +489,7 @@
500489
501490 /**
502491 * Registers the provided listener to be updated with schema change events.
503- * <p>
492+ * <p/>
504493 * Registering the same listener multiple times is a no-op.
505494 *
506495 * @param listener the new {@link SchemaChangeListener} to register.
@@ -516,7 +505,7 @@
516505 /**
517506 * Unregisters the provided schema change listener from being updated
518507 * with schema change events.
519- * <p>
508+ * <p/>
520509 * This method is a no-op if {@code listener} hadn't previously be
521510 * registered against this Cluster.
522511 *
@@ -532,17 +521,17 @@
532521
533522 /**
534523 * Initiates a shutdown of this cluster instance.
535- * <p>
524+ * <p/>
536525 * This method is asynchronous and return a future on the completion
537526 * of the shutdown process. As soon a the cluster is shutdown, no
538527 * new request will be accepted, but already submitted queries are
539528 * allowed to complete. This method closes all connections from all
540529 * sessions and reclaims all resources used by this Cluster
541530 * instance.
542- * <p>
531+ * <p/>
543532 * If for some reason you wish to expedite this process, the
544533 * {@link CloseFuture#force} can be called on the result future.
545- * <p>
534+ * <p/>
546535 * This method has no particular effect if the cluster was already closed
547536 * (in which case the returned future will return immediately).
548537 *
@@ -555,7 +544,7 @@
555544 /**
556545 * Initiates a shutdown of this cluster instance and blocks until
557546 * that shutdown completes.
558- * <p>
547+ * <p/>
559548 * This method is a shortcut for {@code closeAsync().get()}.
560549 */
561550 public void close() {
@@ -570,7 +559,7 @@
570559
571560 /**
572561 * Whether this Cluster instance has been closed.
573- * <p>
562+ * <p/>
574563 * Note that this method returns true as soon as one of the close methods
575564 * ({@link #closeAsync} or {@link #close}) has been called, it does not guarantee
576565 * that the closing is done. If you want to guarantee that the closing is done,
@@ -591,11 +580,11 @@
591580
592581 /**
593582 * Initializer for {@link Cluster} instances.
594- * <p>
583+ * <p/>
595584 * If you want to create a new {@code Cluster} instance programmatically,
596585 * then it is advised to use {@link Cluster.Builder} which can be obtained from the
597586 * {@link Cluster#builder} method.
598- * <p>
587+ * <p/>
599588 * But it is also possible to implement a custom {@code Initializer} that
600589 * retrieves initialization from a web-service or from a configuration file.
601590 */
@@ -603,7 +592,7 @@
603592
604593 /**
605594 * An optional name for the created cluster.
606- * <p>
595+ * <p/>
607596 * Such name is optional (a default name will be created otherwise) and is currently
608597 * only use for JMX reporting of metrics. See {@link Cluster#getClusterName} for more
609598 * information.
@@ -623,15 +612,15 @@
623612
624613 /**
625614 * The configuration to use for the new cluster.
626- * <p>
615+ * <p/>
627616 * Note that some configuration can be modified after the cluster
628617 * initialization but some others cannot. In particular, the ones that
629618 * cannot be changed afterwards includes:
630619 * <ul>
631- * <li>the port use to connect to Cassandra nodes (see {@link ProtocolOptions}).</li>
632- * <li>the policies used (see {@link Policies}).</li>
633- * <li>the authentication info provided (see {@link Configuration}).</li>
634- * <li>whether metrics are enabled (see {@link Configuration}).</li>
620+ * <li>the port use to connect to Cassandra nodes (see {@link ProtocolOptions}).</li>
621+ * <li>the policies used (see {@link Policies}).</li>
622+ * <li>the authentication info provided (see {@link Configuration}).</li>
623+ * <li>whether metrics are enabled (see {@link Configuration}).</li>
635624 * </ul>
636625 *
637626 * @return the configuration to use for the new cluster.
@@ -640,7 +629,7 @@
640629
641630 /**
642631 * Optional listeners to register against the newly created cluster.
643- * <p>
632+ * <p/>
644633 * Note that contrary to listeners registered post Cluster creation,
645634 * the listeners returned by this method will see {@link Host.StateListener#onAdd}
646635 * events for the initial contact points.
@@ -702,11 +691,11 @@
702691
703692 /**
704693 * An optional name for the create cluster.
705- * <p>
694+ * <p/>
706695 * Note: this is not related to the Cassandra cluster name (though you
707696 * are free to provide the same name). See {@link Cluster#getClusterName} for
708697 * details.
709- * <p>
698+ * <p/>
710699 * If you use this method and create more than one Cluster instance in the
711700 * same JVM (which should be avoided unless you need to connect to multiple
712701 * Cassandra clusters), you should make sure each Cluster instance get a
@@ -722,7 +711,7 @@
722711
723712 /**
724713 * The port to use to connect to the Cassandra host.
725- * <p>
714+ * <p/>
726715 * If not set through this method, the default port (9042) will be used
727716 * instead.
728717 *
@@ -736,12 +725,11 @@
736725
737726 /**
738727 * Sets the maximum time to wait for schema agreement before returning from a DDL query.
739- * <p>
728+ * <p/>
740729 * If not set through this method, the default value (10 seconds) will be used.
741730 *
742731 * @param maxSchemaAgreementWaitSeconds the new value to set.
743732 * @return this Builder.
744- *
745733 * @throws IllegalStateException if the provided value is zero or less.
746734 */
747735 public Builder withMaxSchemaAgreementWaitSeconds(int maxSchemaAgreementWaitSeconds) {
@@ -754,12 +742,12 @@
754742
755743 /**
756744 * The native protocol version to use.
757- * <p>
745+ * <p/>
758746 * The driver supports both version 1 and 2 of the native protocol. Version 2
759747 * of the protocol has more features and should be preferred, but it is only
760748 * supported by Cassandra 2.0 and above, so you will have to use version 1 with
761749 * Cassandra 1.2 nodes.
762- * <p>
750+ * <p/>
763751 * By default, the driver will "auto-detect" which protocol version it can use
764752 * when connecting to the first node. More precisely, it will try the version
765753 * 2 first and will fallback to version 1 if it is not supported by that first
@@ -767,7 +755,7 @@
767755 * it won't change: if the first node the driver connects to is a Cassandra 1.2
768756 * node and auto-detection is used (the default), then the native protocol
769757 * version 1 will be use for the lifetime of the Cluster instance.
770- * <p>
758+ * <p/>
771759 * This method allows to force the use of a particular protocol version. Forcing
772760 * version 1 is always fine since all Cassandra version (at least all those
773761 * supporting the native protocol in the first place) so far supports it. However,
@@ -778,22 +766,21 @@
778766 * an UnsupportedFeatureException). Using the protocol version 1 should thus
779767 * only be considered when using Cassandra 1.2, until nodes have been upgraded
780768 * to Cassandra 2.0.
781- * <p>
769+ * <p/>
782770 * If version 2 of the protocol is used, then Cassandra 1.2 nodes will be ignored
783771 * (the driver won't connect to them).
784- * <p>
772+ * <p/>
785773 * The default behavior (auto-detection) is fine in almost all case, but you may
786774 * want to force a particular version if you have a Cassandra cluster with mixed
787775 * 1.2/2.0 nodes (i.e. during a Cassandra upgrade).
788776 *
789777 * @param version the native protocol version to use. The versions supported by
790- * this driver are version 1 and 2. Negative values are also supported to trigger
791- * auto-detection (see above) but this is the default (so you don't have to call
792- * this method for that behavior).
778+ * this driver are version 1 and 2. Negative values are also supported to trigger
779+ * auto-detection (see above) but this is the default (so you don't have to call
780+ * this method for that behavior).
793781 * @return this Builder.
794- *
795782 * @throws IllegalArgumentException if {@code version} is neither 1, 2 or a
796- * negative value.
783+ * negative value.
797784 */
798785 public Builder withProtocolVersion(int version) {
799786 if (version >= 0 && version != 1 && version != 2)
@@ -804,14 +791,14 @@
804791
805792 /**
806793 * Adds a contact point.
807- * <p>
794+ * <p/>
808795 * Contact points are addresses of Cassandra nodes that the driver uses
809796 * to discover the cluster topology. Only one contact point is required
810797 * (the driver will retrieve the address of the other nodes
811798 * automatically), but it is usually a good idea to provide more than
812799 * one contact point, because if that single contact point is unavailable,
813800 * the driver cannot initialize itself correctly.
814- * <p>
801+ * <p/>
815802 * Note that by default (that is, unless you use the {@link #withLoadBalancingPolicy})
816803 * method of this builder), the first succesfully contacted host will be use
817804 * to define the local data-center for the client. If follows that if you are
@@ -821,11 +808,10 @@
821808 *
822809 * @param address the address of the node to connect to
823810 * @return this Builder.
824- *
825811 * @throws IllegalArgumentException if no IP address for {@code address}
826- * could be found
827- * @throws SecurityException if a security manager is present and
828- * permission to resolve the host name is denied.
812+ * could be found
813+ * @throws SecurityException if a security manager is present and
814+ * permission to resolve the host name is denied.
829815 */
830816 public Builder addContactPoint(String address) {
831817 // We explicitely check for nulls because InetAdress.getByName() will happily
@@ -844,18 +830,16 @@
844830
845831 /**
846832 * Adds contact points.
847- * <p>
833+ * <p/>
848834 * See {@link Builder#addContactPoint} for more details on contact
849835 * points.
850836 *
851837 * @param addresses addresses of the nodes to add as contact point.
852838 * @return this Builder.
853- *
854839 * @throws IllegalArgumentException if no IP address for at least one
855- * of {@code addresses} could be found
856- * @throws SecurityException if a security manager is present and
857- * permission to resolve the host name is denied.
858- *
840+ * of {@code addresses} could be found
841+ * @throws SecurityException if a security manager is present and
842+ * permission to resolve the host name is denied.
859843 * @see Builder#addContactPoint
860844 */
861845 public Builder addContactPoints(String... addresses) {
@@ -866,19 +850,17 @@
866850
867851 /**
868852 * Adds a contact point - or many if it host resolves to multiple <code>InetAddress</code>s (A records).
869- * <p>
870- *
853+ * <p/>
854+ * <p/>
871855 * If the host name points to a dns records with multiple a-records, all InetAddresses
872856 * returned will be used. Make sure that all resulting <code>InetAddress</code>s returned
873857 * points to the same cluster and datacenter.
874- * <p>
858+ * <p/>
875859 * See {@link Builder#addContactPoint} for more details on contact
876860 * points and thrown exceptions
877861 *
878862 * @param address address of the nodes to look up InetAddresses from to add as contact points.
879863 * @return this Builder.
880- *
881- *
882864 * @see Builder#addContactPoint
883865 */
884866 public Builder addContactPoints(String address) {
@@ -898,13 +880,12 @@
898880
899881 /**
900882 * Adds contact points.
901- * <p>
883+ * <p/>
902884 * See {@link Builder#addContactPoint} for more details on contact
903885 * points.
904886 *
905887 * @param addresses addresses of the nodes to add as contact point.
906888 * @return this Builder.
907- *
908889 * @see Builder#addContactPoint
909890 */
910891 public Builder addContactPoints(InetAddress... addresses) {
@@ -914,13 +895,12 @@
914895
915896 /**
916897 * Adds contact points.
917- *
898+ * <p/>
918899 * See {@link Builder#addContactPoint} for more details on contact
919900 * points.
920901 *
921902 * @param addresses addresses of the nodes to add as contact point
922903 * @return this Builder
923- *
924904 * @see Builder#addContactPoint
925905 */
926906 public Builder addContactPoints(Collection<InetAddress> addresses) {
@@ -930,7 +910,7 @@
930910
931911 /**
932912 * Adds contact points.
933- * <p>
913+ * <p/>
934914 * See {@link Builder#addContactPoint} for more details on contact
935915 * points. Contrarily to other {@code addContactPoints} methods, this method
936916 * allow to provide a different port for each contact points. Since Cassandra
@@ -947,7 +927,6 @@
947927 *
948928 * @param addresses addresses of the nodes to add as contact point
949929 * @return this Builder
950- *
951930 * @see Builder#addContactPoint
952931 */
953932 public Builder addContactPointsWithPorts(Collection<InetSocketAddress> addresses) {
@@ -957,7 +936,7 @@
957936
958937 /**
959938 * Configures the load balancing policy to use for the new cluster.
960- * <p>
939+ * <p/>
961940 * If no load balancing policy is set through this method,
962941 * {@link Policies#defaultLoadBalancingPolicy} will be used instead.
963942 *
@@ -971,7 +950,7 @@
971950
972951 /**
973952 * Configures the reconnection policy to use for the new cluster.
974- * <p>
953+ * <p/>
975954 * If no reconnection policy is set through this method,
976955 * {@link Policies#DEFAULT_RECONNECTION_POLICY} will be used instead.
977956 *
@@ -985,7 +964,7 @@
985964
986965 /**
987966 * Configures the retry policy to use for the new cluster.
988- * <p>
967+ * <p/>
989968 * If no retry policy is set through this method,
990969 * {@link Policies#DEFAULT_RETRY_POLICY} will be used instead.
991970 *
@@ -999,7 +978,7 @@
999978
1000979 /**
1001980 * Configures the address translater to use for the new cluster.
1002- * <p>
981+ * <p/>
1003982 * See {@link AddressTranslater} for more detail on address translation,
1004983 * but the default translater, {@link IdentityTranslater}, should be
1005984 * correct in most cases. If unsure, stick to the default.
@@ -1014,7 +993,7 @@
1014993
1015994 /**
1016995 * Configures the speculative execution policy to use for the new cluster.
1017- * <p>
996+ * <p/>
1018997 * If no policy is set through this method, {@link Policies#defaultSpeculativeExecutionPolicy()}
1019998 * will be used instead.
1020999 *
@@ -1028,7 +1007,7 @@
10281007
10291008 /**
10301009 * Uses the provided credentials when connecting to Cassandra hosts.
1031- * <p>
1010+ * <p/>
10321011 * This should be used if the Cassandra cluster has been configured to
10331012 * use the {@code PasswordAuthenticator}. If the the default {@code
10341013 * AllowAllAuthenticator} is used instead, using this method has no
@@ -1046,14 +1025,14 @@
10461025 /**
10471026 * Use the specified AuthProvider when connecting to Cassandra
10481027 * hosts.
1049- * <p>
1028+ * <p/>
10501029 * Use this method when a custom authentication scheme is in place.
10511030 * You shouldn't call both this method and {@code withCredentials}
10521031 * on the same {@code Builder} instance as one will supersede the
10531032 * other
10541033 *
10551034 * @param authProvider the {@link AuthProvider} to use to login to
1056- * Cassandra hosts.
1035+ * Cassandra hosts.
10571036 * @return this Builder
10581037 */
10591038 public Builder withAuthProvider(AuthProvider authProvider) {
@@ -1066,7 +1045,6 @@
10661045 *
10671046 * @param compression the compression to set.
10681047 * @return this Builder.
1069- *
10701048 * @see ProtocolOptions.Compression
10711049 */
10721050 public Builder withCompression(ProtocolOptions.Compression compression) {
@@ -1087,10 +1065,10 @@
10871065
10881066 /**
10891067 * Enables the use of SSL for the created {@code Cluster}.
1090- * <p>
1068+ * <p/>
10911069 * Calling this method will use default SSL options (see {@link SSLOptions#SSLOptions()}).
10921070 * This is thus a shortcut for {@code withSSL(new SSLOptions())}.
1093- * <p>
1071+ * <p/>
10941072 * Note that if SSL is enabled, the driver will not connect to any
10951073 * Cassandra nodes that doesn't have SSL enabled and it is strongly
10961074 * advised to enable SSL on every Cassandra node if you plan on using
@@ -1107,7 +1085,6 @@
11071085 * Enable the use of SSL for the created {@code Cluster} using the provided options.
11081086 *
11091087 * @param sslOptions the SSL options to use.
1110- *
11111088 * @return this builder.
11121089 */
11131090 public Builder withSSL(SSLOptions sslOptions) {
@@ -1117,7 +1094,7 @@
11171094
11181095 /**
11191096 * Register the provided listeners in the newly created cluster.
1120- * <p>
1097+ * <p/>
11211098 * Note: repeated calls to this method will override the previous ones.
11221099 *
11231100 * @param listeners the listeners to register.
@@ -1130,7 +1107,7 @@
11301107
11311108 /**
11321109 * Disables JMX reporting of the metrics.
1133- * <p>
1110+ * <p/>
11341111 * JMX reporting is enabled by default (see {@link Metrics}) but can be
11351112 * disabled using this option. If metrics are disabled, this is a
11361113 * no-op.
@@ -1144,7 +1121,7 @@
11441121
11451122 /**
11461123 * Sets the PoolingOptions to use for the newly created Cluster.
1147- * <p>
1124+ * <p/>
11481125 * If no pooling options are set through this method, default pooling
11491126 * options will be used.
11501127 *
@@ -1158,7 +1135,7 @@
11581135
11591136 /**
11601137 * Sets the SocketOptions to use for the newly created Cluster.
1161- * <p>
1138+ * <p/>
11621139 * If no socket options are set through this method, default socket
11631140 * options will be used.
11641141 *
@@ -1172,7 +1149,7 @@
11721149
11731150 /**
11741151 * Sets the QueryOptions to use for the newly created Cluster.
1175- * <p>
1152+ * <p/>
11761153 * If no query options are set through this method, default query
11771154 * options will be used.
11781155 *
@@ -1186,7 +1163,7 @@
11861163
11871164 /**
11881165 * Set the {@link NettyOptions} to use for the newly created Cluster.
1189- * <p>
1166+ * <p/>
11901167 * If no Netty options are set through this method, {@link NettyOptions#DEFAULT_INSTANCE}
11911168 * will be used as a default value, which means that no customization will be applied.
11921169 *
@@ -1200,7 +1177,7 @@
12001177
12011178 /**
12021179 * The configuration that will be used for the new cluster.
1203- * <p>
1180+ * <p/>
12041181 * You <b>should not</b> modify this object directly because changes made
12051182 * to the returned object may not be used by the cluster build.
12061183 * Instead, you should use the other methods of this {@code Builder}.
@@ -1210,19 +1187,19 @@
12101187 @Override
12111188 public Configuration getConfiguration() {
12121189 Policies policies = new Policies(
1213- loadBalancingPolicy == null ? Policies.defaultLoadBalancingPolicy() : loadBalancingPolicy,
1214- Objects.firstNonNull(reconnectionPolicy, Policies.defaultReconnectionPolicy()),
1215- Objects.firstNonNull(retryPolicy, Policies.defaultRetryPolicy()),
1216- Objects.firstNonNull(addressTranslater, Policies.defaultAddressTranslater()),
1217- Objects.firstNonNull(speculativeExecutionPolicy, Policies.defaultSpeculativeExecutionPolicy())
1190+ loadBalancingPolicy == null ? Policies.defaultLoadBalancingPolicy() : loadBalancingPolicy,
1191+ Objects.firstNonNull(reconnectionPolicy, Policies.defaultReconnectionPolicy()),
1192+ Objects.firstNonNull(retryPolicy, Policies.defaultRetryPolicy()),
1193+ Objects.firstNonNull(addressTranslater, Policies.defaultAddressTranslater()),
1194+ Objects.firstNonNull(speculativeExecutionPolicy, Policies.defaultSpeculativeExecutionPolicy())
12181195 );
12191196 return new Configuration(policies,
1220- new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider).setCompression(compression),
1221- poolingOptions == null ? new PoolingOptions() : poolingOptions,
1222- socketOptions == null ? new SocketOptions() : socketOptions,
1223- metricsEnabled ? new MetricsOptions(jmxEnabled) : null,
1224- queryOptions == null ? new QueryOptions() : queryOptions,
1225- nettyOptions);
1197+ new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider).setCompression(compression),
1198+ poolingOptions == null ? new PoolingOptions() : poolingOptions,
1199+ socketOptions == null ? new SocketOptions() : socketOptions,
1200+ metricsEnabled ? new MetricsOptions(jmxEnabled) : null,
1201+ queryOptions == null ? new QueryOptions() : queryOptions,
1202+ nettyOptions);
12261203 }
12271204
12281205 @Override
@@ -1233,7 +1210,7 @@
12331210 /**
12341211 * Builds the cluster with the configured set of initial contact points
12351212 * and policies.
1236- * <p>
1213+ * <p/>
12371214 * This is a convenience method for {@code Cluster.buildFrom(this)}.
12381215 *
12391216 * @return the newly built Cluster instance.
@@ -1253,7 +1230,7 @@
12531230
12541231 /**
12551232 * The sessions and hosts managed by this a Cluster instance.
1256- * <p>
1233+ * <p/>
12571234 * Note: the reason we create a Manager object separate from Cluster is
12581235 * that Manager is not publicly visible. For instance, we wouldn't want
12591236 * user to be able to call the {@link #onUp} and {@link #onDown} methods.
@@ -1304,7 +1281,7 @@
13041281
13051282 final Set<Host.StateListener> listeners;
13061283 final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>();
1307- final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>();
1284+ final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>();
13081285
13091286 EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer;
13101287 EventDebouncer<NodeRefreshRequest> nodeRefreshRequestDebouncer;
@@ -1348,23 +1325,23 @@
13481325 // create debouncers - at this stage, they are not running yet
13491326 QueryOptions queryOptions = configuration.getQueryOptions();
13501327 this.nodeListRefreshRequestDebouncer = new EventDebouncer<NodeListRefreshRequest>(
1351- "Node list refresh",
1352- scheduledTasksExecutor,
1353- new NodeListRefreshRequestDeliveryCallback(),
1354- queryOptions.getRefreshNodeListIntervalMillis(),
1355- queryOptions.getMaxPendingRefreshNodeListRequests());
1328+ "Node list refresh",
1329+ scheduledTasksExecutor,
1330+ new NodeListRefreshRequestDeliveryCallback(),
1331+ queryOptions.getRefreshNodeListIntervalMillis(),
1332+ queryOptions.getMaxPendingRefreshNodeListRequests());
13561333 this.nodeRefreshRequestDebouncer = new EventDebouncer<NodeRefreshRequest>(
1357- "Node refresh",
1358- scheduledTasksExecutor,
1359- new NodeRefreshRequestDeliveryCallback(),
1360- queryOptions.getRefreshNodeIntervalMillis(),
1361- queryOptions.getMaxPendingRefreshNodeRequests());
1334+ "Node refresh",
1335+ scheduledTasksExecutor,
1336+ new NodeRefreshRequestDeliveryCallback(),
1337+ queryOptions.getRefreshNodeIntervalMillis(),
1338+ queryOptions.getMaxPendingRefreshNodeRequests());
13621339 this.schemaRefreshRequestDebouncer = new EventDebouncer<SchemaRefreshRequest>(
1363- "Schema refresh",
1364- scheduledTasksExecutor,
1365- new SchemaRefreshRequestDeliveryCallback(),
1366- queryOptions.getRefreshSchemaIntervalMillis(),
1367- queryOptions.getMaxPendingRefreshSchemaRequests());
1340+ "Schema refresh",
1341+ scheduledTasksExecutor,
1342+ new SchemaRefreshRequestDeliveryCallback(),
1343+ queryOptions.getRefreshSchemaIntervalMillis(),
1344+ queryOptions.getMaxPendingRefreshSchemaRequests());
13681345
13691346 this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
13701347
@@ -1475,11 +1452,11 @@
14751452
14761453 private ListeningExecutorService makeExecutor(int threads, String name, LinkedBlockingQueue<Runnable> workQueue) {
14771454 ThreadPoolExecutor executor = new ThreadPoolExecutor(threads,
1478- threads,
1479- DEFAULT_THREAD_KEEP_ALIVE,
1480- TimeUnit.SECONDS,
1481- workQueue,
1482- threadFactory(name));
1455+ threads,
1456+ DEFAULT_THREAD_KEEP_ALIVE,
1457+ TimeUnit.SECONDS,
1458+ workQueue,
1459+ threadFactory(name));
14831460
14841461 executor.allowCoreThreadTimeOut(true);
14851462 return MoreExecutors.listeningDecorator(executor);
@@ -1557,13 +1534,13 @@
15571534 // And the load balancing policy
15581535 LoadBalancingPolicy loadBalancingPolicy = loadBalancingPolicy();
15591536 if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy)
1560- ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close();
1537+ ((CloseableLoadBalancingPolicy) loadBalancingPolicy).close();
15611538
15621539 speculativeRetryPolicy().close();
15631540
15641541 AddressTranslater translater = configuration.getPolicies().getAddressTranslater();
15651542 if (translater instanceof CloseableAddressTranslater)
1566- ((CloseableAddressTranslater)translater).close();
1543+ ((CloseableAddressTranslater) translater).close();
15671544
15681545 for (SchemaChangeListener listener : schemaChangeListeners) {
15691546 listener.onUnregister(Cluster.this);
@@ -1582,8 +1559,8 @@
15821559 }
15831560
15841561 return closeFuture.compareAndSet(null, future)
1585- ? future
1586- : closeFuture.get(); // We raced, it's ok, return the future that was actually set
1562+ ? future
1563+ : closeFuture.get(); // We raced, it's ok, return the future that was actually set
15871564 }
15881565
15891566 private void shutdownNow(ExecutorService executor) {
@@ -1591,20 +1568,20 @@
15911568 // If some tasks were submitted to this executor but not yet commenced, make sure the corresponding futures complete
15921569 for (Runnable pendingTask : pendingTasks) {
15931570 if (pendingTask instanceof FutureTask<?>)
1594- ((FutureTask<?>)pendingTask).cancel(false);
1571+ ((FutureTask<?>) pendingTask).cancel(false);
15951572 }
15961573 }
15971574
15981575 void logUnsupportedVersionProtocol(Host host) {
15991576 logger.warn("Detected added or restarted Cassandra host {} but ignoring it since it does not support the version 2 of the native "
1600- + "protocol which is currently in use. If you want to force the use of the version 1 of the native protocol, use "
1601- + "Cluster.Builder#usingProtocolVersion() when creating the Cluster instance.", host);
1577+ + "protocol which is currently in use. If you want to force the use of the version 1 of the native protocol, use "
1578+ + "Cluster.Builder#usingProtocolVersion() when creating the Cluster instance.", host);
16021579 }
16031580
16041581 void logClusterNameMismatch(Host host, String expectedClusterName, String actualClusterName) {
16051582 logger.warn("Detected added or restarted Cassandra host {} but ignoring it since its cluster name '{}' does not match the one "
1606- + "currently known ({})",
1607- host, actualClusterName, expectedClusterName);
1583+ + "currently known ({})",
1584+ host, actualClusterName, expectedClusterName);
16081585 }
16091586
16101587 public ListenableFuture<?> triggerOnUp(final Host host) {
@@ -1727,7 +1704,7 @@
17271704 }
17281705
17291706 public ListenableFuture<?> triggerOnDown(final Host host, final boolean isHostAddition, final boolean startReconnection) {
1730- if(!isClosed()) {
1707+ if (!isClosed()) {
17311708 return executor.submit(new ExceptionCatchingRunnable() {
17321709 @Override
17331710 public void runMayThrow() throws InterruptedException, ExecutionException {
@@ -2083,7 +2060,7 @@
20832060 PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().id, stmt);
20842061 if (previous != null) {
20852062 logger.warn("Re-preparing already prepared query {}. Please note that preparing the same query more than once is "
2086- + "generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.", stmt.getQueryString());
2063+ + "generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.", stmt.getQueryString());
20872064
20882065 // The one object in the cache will get GCed once it's not referenced by the client anymore since we use a weak reference.
20892066 // So we need to make sure that the instance we do return to the user is the one that is in the cache.
@@ -2096,7 +2073,7 @@
20962073 * @param reusedConnection an existing connection (from a reconnection attempt) that we want to
20972074 * reuse to prepare the statements (might be null).
20982075 * @return a connection that the rest of the initialization process can use (it will be made part
2099- * of a connection pool). Can be reusedConnection, or one that was open in the method.
2076+ * of a connection pool). Can be reusedConnection, or one that was open in the method.
21002077 */
21012078 private Connection prepareAllQueries(Host host, Connection reusedConnection) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
21022079 if (preparedQueries.isEmpty())
@@ -2106,8 +2083,8 @@
21062083 Connection connection = null;
21072084 try {
21082085 connection = (reusedConnection == null)
2109- ? connectionFactory.open(host)
2110- : reusedConnection;
2086+ ? connectionFactory.open(host)
2087+ : reusedConnection;
21112088
21122089 try {
21132090 controlConnection.waitForSchemaAgreement();
@@ -2247,13 +2224,13 @@
22472224 return;
22482225 }
22492226
2250- final ProtocolEvent event = ((Responses.Event)response).event;
2227+ final ProtocolEvent event = ((Responses.Event) response).event;
22512228
22522229 logger.debug("Received event {}, scheduling delivery", response);
22532230
22542231 switch (event.type) {
22552232 case TOPOLOGY_CHANGE:
2256- ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange)event;
2233+ ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange) event;
22572234 InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress());
22582235 Host.statesLogger.debug("[{}] received event {}", tpAddr, tpc.change);
22592236 switch (tpc.change) {
@@ -2269,7 +2246,7 @@
22692246 }
22702247 break;
22712248 case STATUS_CHANGE:
2272- ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange)event;
2249+ ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange) event;
22732250 InetSocketAddress stAddr = translateAddress(stc.node.getAddress());
22742251 Host.statesLogger.debug("[{}] received event {}", stAddr, stc.status);
22752252 switch (stc.status) {
@@ -2285,7 +2262,7 @@
22852262 if (!configuration.getQueryOptions().isMetadataEnabled())
22862263 return;
22872264
2288- ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event;
2265+ ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange) event;
22892266 switch (scc.change) {
22902267 case CREATED:
22912268 if (scc.table.isEmpty())
@@ -2296,7 +2273,7 @@
22962273 case DROPPED:
22972274 if (scc.table.isEmpty()) {
22982275 final KeyspaceMetadata removed = manager.metadata.removeKeyspace(scc.keyspace);
2299- if(removed != null) {
2276+ if (removed != null) {
23002277 executor.submit(new Runnable() {
23012278 @Override
23022279 public void run() {
@@ -2308,7 +2285,7 @@
23082285 KeyspaceMetadata keyspace = manager.metadata.getKeyspaceInternal(scc.keyspace);
23092286 if (keyspace == null)
23102287 logger.warn("Received a DROPPED notification for {}.{}, but this keyspace is unknown in our metadata",
2311- scc.keyspace, scc.table);
2288+ scc.keyspace, scc.table);
23122289 else {
23132290 final TableMetadata removed = keyspace.removeTable(scc.table);
23142291 if (removed != null) {
@@ -2409,7 +2386,8 @@
24092386 }
24102387
24112388 private class CleanupIdleConnectionsTask implements Runnable {
2412- @Override public void run() {
2389+ @Override
2390+ public void run() {
24132391 try {
24142392 long now = System.currentTimeMillis();
24152393 for (SessionManager session : sessions) {
@@ -2443,22 +2421,22 @@
24432421 * @return A coalesced request
24442422 */
24452423 SchemaRefreshRequest coalesce(SchemaRefreshRequest that) {
2446- if(this.keyspace == null || that.keyspace == null)
2424+ if (this.keyspace == null || that.keyspace == null)
24472425 return new SchemaRefreshRequest(null, null);
2448- if(!this.keyspace.equals(that.keyspace))
2426+ if (!this.keyspace.equals(that.keyspace))
24492427 return new SchemaRefreshRequest(null, null);
2450- if(this.table == null || that.table == null)
2428+ if (this.table == null || that.table == null)
24512429 return new SchemaRefreshRequest(keyspace, null);
2452- if(!this.table.equals(that.table))
2430+ if (!this.table.equals(that.table))
24532431 return new SchemaRefreshRequest(keyspace, null);
24542432 return this;
24552433 }
24562434
24572435 @Override
24582436 public String toString() {
2459- if(this.keyspace == null)
2437+ if (this.keyspace == null)
24602438 return "Refresh ALL";
2461- if(this.table == null)
2439+ if (this.table == null)
24622440 return "Refresh keyspace " + keyspace;
24632441 return "Refresh keyspace " + keyspace + " table " + table;
24642442 }
@@ -2538,7 +2516,7 @@
25382516 // If host already existed, retrieve it and check its state, if it's not up schedule a
25392517 // hostUp event.
25402518 Host existingHost = metadata.getHost(address);
2541- if(!existingHost.isUp())
2519+ if (!existingHost.isUp())
25422520 futures.add(schedule(hostUp(existingHost)));
25432521 }
25442522 break;
@@ -2677,7 +2655,7 @@
26772655
26782656 /**
26792657 * Periodically ensures that closed connections are properly terminated once they have no more pending requests.
2680- *
2658+ * <p/>
26812659 * This is normally done when the connection errors out, or when the last request is processed; this class acts as
26822660 * a last-effort protection since unterminated connections can lead to deadlocks. If it terminates a connection,
26832661 * 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 +9 −9
@@ -110,7 +110,7 @@
110110 if (o == null || getClass() != o.getClass())
111111 return false;
112112
113- ColumnMetadata that = (ColumnMetadata)o;
113+ ColumnMetadata that = (ColumnMetadata) o;
114114
115115 if (isStatic != that.isStatic)
116116 return false;
@@ -166,7 +166,7 @@
166166
167167 /**
168168 * Returns whether this index is a custom one.
169- * <p>
169+ * <p/>
170170 * If it is indeed a custom index, {@link #getIndexClassName} will
171171 * return the name of the class used in Cassandra to implement that
172172 * index.
@@ -189,7 +189,7 @@
189189
190190 /**
191191 * Returns a CQL query representing this index.
192- *
192+ * <p/>
193193 * This method returns a single 'CREATE INDEX' query corresponding to
194194 * this index definition.
195195 *
@@ -201,8 +201,8 @@
201201 String cfName = Metadata.escapeId(table.getName());
202202 String colName = Metadata.escapeId(column.getName());
203203 return isCustomIndex()
204- ? String.format("CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s';", name, ksName, cfName, colName, customClassName)
205- : String.format("CREATE INDEX %s ON %s.%s (%s);", name, ksName, cfName, colName);
204+ ? String.format("CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s';", name, ksName, cfName, colName, customClassName)
205+ : String.format("CREATE INDEX %s ON %s.%s (%s);", name, ksName, cfName, colName);
206206 }
207207
208208 @Override
@@ -212,7 +212,7 @@
212212 if (o == null || getClass() != o.getClass())
213213 return false;
214214
215- IndexMetadata that = (IndexMetadata)o;
215+ IndexMetadata that = (IndexMetadata) o;
216216
217217 if (!name.equals(that.name))
218218 return false;
@@ -252,7 +252,7 @@
252252 // Temporary class that is used to make building the schema easier. Not meant to be
253253 // exposed publicly at all.
254254 static class Raw {
255- public enum Kind { PARTITION_KEY, CLUSTERING_KEY, REGULAR, COMPACT_VALUE, STATIC }
255+ public enum Kind {PARTITION_KEY, CLUSTERING_KEY, REGULAR, COMPACT_VALUE, STATIC}
256256
257257 public final String name;
258258 public final Kind kind;
@@ -274,8 +274,8 @@
274274
275275 String name = row.getString(COLUMN_NAME);
276276 Kind kind = version.getMajor() < 2 || row.isNull(KIND)
277- ? Kind.REGULAR
278- : Enum.valueOf(Kind.class, row.getString(KIND).toUpperCase());
277+ ? Kind.REGULAR
278+ : Enum.valueOf(Kind.class, row.getString(KIND).toUpperCase());
279279 int componentIndex = row.isNull(COMPONENT_INDEX) ? 0 : row.getInt(COMPONENT_INDEX);
280280 String validatorStr = row.getString(VALIDATOR);
281281 boolean reversed = CassandraTypeParser.isReversed(validatorStr);
modified driver-core/src/main/java/com/datastax/driver/core/Configuration.java +21 −20
@@ -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(new Policies(),
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,
@@ -126,7 +126,7 @@
126126
127127 /**
128128 * Returns the metrics configuration, if metrics are enabled.
129- * <p>
129+ * <p/>
130130 * Metrics collection is enabled by default but can be disabled at cluster
131131 * construction time through {@link Cluster.Builder#withoutMetrics}.
132132 *
@@ -147,6 +147,7 @@
147147
148148 /**
149149 * Returns the {@link NettyOptions} instance for this configuration.
150+ *
150151 * @return the {@link NettyOptions} instance for this configuration.
151152 */
152153 public NettyOptions getNettyOptions() {
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +94 −95
@@ -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;
@@ -134,9 +132,9 @@
134132 Bootstrap bootstrap = factory.newBootstrap();
135133 ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
136134 bootstrap.handler(
137- new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(),
138- factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
139- factory.configuration.getNettyOptions()));
135+ new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(),
136+ factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
137+ factory.configuration.getNettyOptions()));
140138
141139 ChannelFuture future = bootstrap.connect(address);
142140
@@ -175,7 +173,7 @@
175173 Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor();
176174
177175 ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture,
178- onChannelReady(protocolVersion, initExecutor), initExecutor);
176+ onChannelReady(protocolVersion, initExecutor), initExecutor);
179177
180178
181179 // Fallback on initializeTransportFuture so we can properly propagate specific exceptions.
@@ -191,10 +189,10 @@
191189 } else {
192190 // Defunct to ensure that the error will be signaled (marking the host down)
193191 Exception e = (t instanceof ConnectionException || t instanceof DriverException || t instanceof InterruptedException)
194- ? (Exception)t
195- : new ConnectionException(Connection.this.address,
196- String.format("Unexpected error during transport initialization (%s)", t),
197- t);
192+ ? (Exception) t
193+ : new ConnectionException(Connection.this.address,
194+ String.format("Unexpected error during transport initialization (%s)", t),
195+ t);
198196 future.setException(defunct(e));
199197 }
200198 return future;
@@ -218,8 +216,8 @@
218216 if (t == null)
219217 return "";
220218 String msg = t.getMessage() == null || t.getMessage().isEmpty()
221- ? t.toString()
222- : t.getMessage();
219+ ? t.toString()
220+ : t.getMessage();
223221 return " (" + msg + ')';
224222 }
225223
@@ -230,7 +228,7 @@
230228 ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
231229 Future startupResponseFuture = write(new Requests.Startup(compression));
232230 return Futures.transform(startupResponseFuture,
233- onStartupResponse(protocolVersion, initExecutor), initExecutor);
231+ onStartupResponse(protocolVersion, initExecutor), initExecutor);
234232 }
235233 };
236234 }
@@ -243,22 +241,20 @@
243241 case READY:
244242 return checkClusterName(initExecutor);
245243 case ERROR:
246- Responses.Error error = (Responses.Error)response;
244+ Responses.Error error = (Responses.Error) response;
247245 // Testing for a specific string is a tad fragile but well, we don't have much choice
248246 if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version"))
249247 throw unsupportedProtocolVersionException(protocolVersion);
250248 throw new TransportException(address, String.format("Error initializing connection: %s", error.message));
251249 case AUTHENTICATE:
252250 Authenticator authenticator = factory.authProvider.newAuthenticator(address);
253- if (protocolVersion == 1)
254- {
251+ if (protocolVersion == 1) {
255252 if (authenticator instanceof ProtocolV1Authenticator)
256253 return authenticateV1(authenticator, initExecutor);
257254 else
258255 // DSE 3.x always uses SASL authentication backported from protocol v2
259256 return authenticateV2(authenticator, initExecutor);
260- }
261- else
257+ } else
262258 return authenticateV2(authenticator, initExecutor);
263259 default:
264260 throw new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type));
@@ -279,21 +275,21 @@
279275 return MoreFutures.VOID_SUCCESS;
280276 }
281277
282- DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local"));
278+ DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null, new Requests.Query("select cluster_name from system.local"));
283279 try {
284280 write(clusterNameFuture);
285281 return Futures.transform(clusterNameFuture,
286- new AsyncFunction<ResultSet, Void>() {
287- @Override
288- public ListenableFuture<Void> apply(ResultSet rs) throws Exception {
289- Row row = rs.one();
290- String actual = row.getString("cluster_name");
291- if (!expected.equals(actual))
292- throw new ClusterNameMismatchException(address, actual, expected);
293- markInitialized();
294- return MoreFutures.VOID_SUCCESS;
295- }
296- }, executor);
282+ new AsyncFunction<ResultSet, Void>() {
283+ @Override
284+ public ListenableFuture<Void> apply(ResultSet rs) throws Exception {
285+ Row row = rs.one();
286+ String actual = row.getString("cluster_name");
287+ if (!expected.equals(actual))
288+ throw new ClusterNameMismatchException(address, actual, expected);
289+ markInitialized();
290+ return MoreFutures.VOID_SUCCESS;
291+ }
292+ }, executor);
297293 } catch (Exception e) {
298294 return Futures.immediateFailedFuture(e);
299295 }
@@ -305,23 +301,23 @@
305301 }
306302
307303 private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final Executor executor) {
308- Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials());
304+ Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator) authenticator).getCredentials());
309305 try {
310306 Future authResponseFuture = write(creds);
311307 return Futures.transform(authResponseFuture,
312- new AsyncFunction<Message.Response, Void>() {
313- @Override
314- public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
315- switch (authResponse.type) {
316- case READY:
317- return checkClusterName(executor);
318- case ERROR:
319- throw new AuthenticationException(address, ((Responses.Error)authResponse).message);
320- default:
321- throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type));
308+ new AsyncFunction<Message.Response, Void>() {
309+ @Override
310+ public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
311+ switch (authResponse.type) {
312+ case READY:
313+ return checkClusterName(executor);
314+ case ERROR:
315+ throw new AuthenticationException(address, ((Responses.Error) authResponse).message);
316+ default:
317+ throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type));
318+ }
322319 }
323- }
324- }, executor);
320+ }, executor);
325321 } catch (Exception e) {
326322 return Futures.immediateFailedFuture(e);
327323 }
@@ -347,10 +343,10 @@
347343 switch (authResponse.type) {
348344 case AUTH_SUCCESS:
349345 logger.trace("{} Authentication complete", this);
350- authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token);
346+ authenticator.onAuthenticationSuccess(((Responses.AuthSuccess) authResponse).token);
351347 return checkClusterName(executor);
352348 case AUTH_CHALLENGE:
353- byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token);
349+ byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge) authResponse).token);
354350 if (responseToServer == null) {
355351 // If we generate a null response, then authentication has completed, proceed without
356352 // sending a further response back to the server.
@@ -367,10 +363,10 @@
367363 // attempted v2 auth against a server which only supports v1
368364 // The AIOOBE indicates that the server didn't recognise the
369365 // initial AuthResponse message
370- String message = ((Responses.Error)authResponse).message;
366+ String message = ((Responses.Error) authResponse).message;
371367 if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15"))
372368 message = String.format("Cannot use authenticator %s with protocol version 1, "
373- + "only plain text authentication is supported with this protocol version", authenticator);
369+ + "only plain text authentication is supported with this protocol version", authenticator);
374370 throw new AuthenticationException(address, message);
375371 default:
376372 throw new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type));
@@ -435,14 +431,14 @@
435431 throw defunct(e);
436432 } catch (BusyConnectionException e) {
437433 logger.warn("Tried to set the keyspace on busy {}. "
438- + "This should not happen but is not critical (it will be retried)", this);
434+ + "This should not happen but is not critical (it will be retried)", this);
439435 throw new ConnectionException(address, "Tried to set the keyspace on busy connection");
440436 } catch (ExecutionException e) {
441437 Throwable cause = e.getCause();
442438 if (cause instanceof OperationTimedOutException) {
443439 // Rethrow so that the caller doesn't try to use the connection, but do not defunct as we don't want to mark down
444440 logger.warn("Timeout while setting keyspace on {}. "
445- + "This should not happen but is not critical (it will be retried)", this);
441+ + "This should not happen but is not critical (it will be retried)", this);
446442 throw new ConnectionException(address, "Timeout while setting keyspace on connection");
447443 } else {
448444 throw defunct(new ConnectionException(address, "Error while setting keyspace", cause));
@@ -458,11 +454,11 @@
458454 @Override
459455 public ListenableFuture<Void> apply(Message.Response response) throws Exception {
460456 if (response instanceof SetKeyspace) {
461- Connection.this.keyspace = ((SetKeyspace)response).keyspace;
457+ Connection.this.keyspace = ((SetKeyspace) response).keyspace;
462458 return MoreFutures.VOID_SUCCESS;
463459 } else if (response.type == ERROR) {
464460 closeAsync().force();
465- Responses.Error error = (Responses.Error)response;
461+ Responses.Error error = (Responses.Error) response;
466462 throw error.asException(address);
467463 } else {
468464 closeAsync().force();
@@ -477,9 +473,8 @@
477473 *
478474 * @param request the request to send
479475 * @return a future on the server response
480- *
481476 * @throws ConnectionException if the connection is closed
482- * @throws TransportException if an I/O error while sending the request
477+ * @throws TransportException if an I/O error while sending the request
483478 */
484479 public Future write(Message.Request request) throws ConnectionException, BusyConnectionException {
485480 Future future = new Future(request);
@@ -573,7 +568,9 @@
573568 return this.ownerRef.get() != null;
574569 }
575570
576- /** @return whether the connection was already associated with an owner */
571+ /**
572+ * @return whether the connection was already associated with an owner
573+ */
577574 boolean setOwner(Owner owner) {
578575 return ownerRef.compareAndSet(null, owner);
579576 }
@@ -585,7 +582,7 @@
585582 void release() {
586583 Owner owner = ownerRef.get();
587584 if (owner instanceof HostConnectionPool)
588- ((HostConnectionPool)owner).returnConnection(this);
585+ ((HostConnectionPool) owner).returnConnection(this);
589586 }
590587
591588 public boolean isClosed() {
@@ -594,13 +591,12 @@
594591
595592 /**
596593 * Closes the connection: no new writes will be accepted after this method has returned.
597- *
594+ * <p/>
598595 * However, a closed connection might still have ongoing queries awaiting for their result.
599596 * When all these ongoing queries have completed, the underlying channel will be closed; we
600597 * refer to this final state as "terminated".
601598 *
602599 * @return a future that will complete once the connection has terminated.
603- *
604600 * @see #tryTerminate(boolean)
605601 */
606602 public CloseFuture closeAsync() {
@@ -640,12 +636,11 @@
640636
641637 /**
642638 * Tries to terminate a closed connection, i.e. release system resources.
643- *
639+ * <p/>
644640 * This is called both by "normal" code and by {@link Cluster.ConnectionReaper}.
645641 *
646642 * @param force whether to proceed if there are still outstanding requests.
647643 * @return whether the connection has actually terminated.
648- *
649644 * @see #closeAsync()
650645 */
651646 boolean tryTerminate(boolean force) {
@@ -715,7 +710,6 @@
715710 * Opens a new connection to the node this factory points to.
716711 *
717712 * @return the newly created (and initialized) connection.
718- *
719713 * @throws ConnectionException if connection attempt fails.
720714 */
721715 public Connection open(Host host) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
@@ -767,15 +761,15 @@
767761 static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
768762 Throwable t = e.getCause();
769763 if (t instanceof ConnectionException)
770- throw (ConnectionException)t;
764+ throw (ConnectionException) t;
771765 if (t instanceof InterruptedException)
772- throw (InterruptedException)t;
766+ throw (InterruptedException) t;
773767 if (t instanceof UnsupportedProtocolVersionException)
774- throw (UnsupportedProtocolVersionException)t;
768+ throw (UnsupportedProtocolVersionException) t;
775769 if (t instanceof ClusterNameMismatchException)
776- throw (ClusterNameMismatchException)t;
770+ throw (ClusterNameMismatchException) t;
777771 if (t instanceof DriverException)
778- throw (DriverException)t;
772+ throw (DriverException) t;
779773
780774 return new RuntimeException("Unexpected exception during connection initialization", t);
781775 }
@@ -798,7 +792,7 @@
798792 private Bootstrap newBootstrap() {
799793 Bootstrap b = new Bootstrap();
800794 b.group(eventLoopGroup)
801- .channel(channelClass);
795+ .channel(channelClass);
802796
803797 SocketOptions options = configuration.getSocketOptions();
804798
@@ -896,7 +890,7 @@
896890 }
897891
898892 private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new MapMaker()
899- .concurrencyLevel(16)
893+ .concurrencyLevel(16)
900894 .weakKeys()
901895 .makeMap();
902896
@@ -965,7 +959,7 @@
965959 protected void channelRead0(ChannelHandlerContext ctx, Message.Response response) throws Exception {
966960 int streamId = response.getStreamId();
967961
968- if(logger.isTraceEnabled())
962+ if (logger.isTraceEnabled())
969963 logger.trace("{}, stream {}, received: {}", Connection.this, streamId, asDebugString(response));
970964
971965 if (streamId < 0) {
@@ -988,7 +982,7 @@
988982 streamIdHandler.unmark(streamId);
989983 if (logger.isDebugEnabled())
990984 logger.debug("{} Response received on stream {} but no handler set anymore (either the request has "
991- + "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
985+ + "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
992986 return;
993987 }
994988 handler.cancelTimeout();
@@ -1002,7 +996,7 @@
1002996
1003997 @Override
1004998 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
1005- if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) {
999+ if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == ALL_IDLE) {
10061000 logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
10071001 write(HEARTBEAT_CALLBACK);
10081002 }
@@ -1034,8 +1028,7 @@
10341028
10351029 public void errorOutAllHandler(ConnectionException ce) {
10361030 Iterator<ResponseHandler> iter = pending.values().iterator();
1037- while (iter.hasNext())
1038- {
1031+ while (iter.hasNext()) {
10391032 ResponseHandler handler = iter.next();
10401033 handler.cancelTimeout();
10411034 handler.callback.onException(Connection.this, ce, System.nanoTime() - handler.startTime, handler.retryCount);
@@ -1188,9 +1181,13 @@
11881181
11891182 interface ResponseCallback {
11901183 public Message.Request request();
1184+
11911185 public int retryCount();
1186+
11921187 public void onSet(Connection connection, Message.Response response, long latency, int retryCount);
1188+
11931189 public void onException(Connection connection, Exception exception, long latency, int retryCount);
1190+
11941191 public boolean onTimeout(Connection connection, long latency, int retryCount);
11951192 }
11961193
@@ -1308,7 +1305,9 @@
13081305 }
13091306 }
13101307
1311- /** A component that "owns" a connection, and should be notified when it dies. */
1308+ /**
1309+ * A component that "owns" a connection, and should be notified when it dies.
1310+ */
13121311 interface Owner {
13131312 void onConnectionDefunct(Connection connection);
13141313 }
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 +24 −24
@@ -15,22 +15,22 @@
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
3535 class ControlConnection implements Host.StateListener, Connection.Owner {
3636
@@ -98,8 +98,8 @@
9898 Host connectedHost() {
9999 Connection current = connectionRef.get();
100100 return (current == null)
101- ? null
102- : cluster.metadata.getHost(current.address);
101+ ? null
102+ : cluster.metadata.getHost(current.address);
103103 }
104104
105105 void triggerReconnect() {
@@ -257,9 +257,9 @@
257257 try {
258258 logger.trace("[Control connection] Registering for events");
259259 List<ProtocolEvent.Type> evs = Arrays.asList(
260- ProtocolEvent.Type.TOPOLOGY_CHANGE,
261- ProtocolEvent.Type.STATUS_CHANGE,
262- ProtocolEvent.Type.SCHEMA_CHANGE
260+ ProtocolEvent.Type.TOPOLOGY_CHANGE,
261+ ProtocolEvent.Type.STATUS_CHANGE,
262+ ProtocolEvent.Type.SCHEMA_CHANGE
263263 );
264264 connection.write(new Requests.Register(evs));
265265
@@ -295,7 +295,7 @@
295295 }
296296
297297 void refreshSchema(String keyspace, String table) throws InterruptedException {
298- if(keyspace == null && table == null) {
298+ if (keyspace == null && table == null) {
299299 logger.debug("[Control connection] Refreshing schema");
300300 } else {
301301 logger.debug("[Control connection] Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table);
@@ -335,8 +335,8 @@
335335 }
336336
337337 DefaultResultSetFuture ksFuture = table == null
338- ? new DefaultResultSetFuture(null, new Requests.Query(SELECT_KEYSPACES + whereClause))
339- : null;
338+ ? new DefaultResultSetFuture(null, new Requests.Query(SELECT_KEYSPACES + whereClause))
339+ : null;
340340 DefaultResultSetFuture cfFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_COLUMN_FAMILIES + whereClause));
341341 DefaultResultSetFuture colsFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_COLUMNS + whereClause));
342342
@@ -353,7 +353,7 @@
353353 if (host == null || host.getCassandraVersion() == null) {
354354 cassandraVersion = cluster.protocolVersion() == 1 ? VersionNumber.parse("1.2.0") : VersionNumber.parse("2.0.0");
355355 logger.warn("Cannot find Cassandra version for host {} to parse the schema, using {} based on protocol version in use. "
356- + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion);
356+ + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion);
357357 } else {
358358 cassandraVersion = host.getCassandraVersion();
359359 }
@@ -417,8 +417,8 @@
417417 boolean isConnectedHost = c.address.equals(host.getSocketAddress());
418418 if (isConnectedHost || host.listenAddress != null) {
419419 DefaultResultSetFuture future = isConnectedHost
420- ? new DefaultResultSetFuture(null, new Requests.Query(SELECT_LOCAL))
421- : new DefaultResultSetFuture(null, new Requests.Query(SELECT_PEERS + " WHERE peer='" + host.listenAddress.getHostAddress() + '\''));
420+ ? new DefaultResultSetFuture(null, new Requests.Query(SELECT_LOCAL))
421+ : new DefaultResultSetFuture(null, new Requests.Query(SELECT_PEERS + " WHERE peer='" + host.listenAddress.getHostAddress() + '\''));
422422 c.write(future);
423423 return future.get().one();
424424 }
@@ -499,8 +499,8 @@
499499 String version = row.getString("release_version");
500500 // We don't know if it's a 'local' or a 'peers' row, and only 'peers' rows have the 'peer' field.
501501 InetAddress listenAddress = row.getColumnDefinitions().contains("peer")
502- ? row.getInet("peer")
503- : null;
502+ ? row.getInet("peer")
503+ : null;
504504
505505 host.setVersionAndListenAdress(version, listenAddress);
506506 }
@@ -692,7 +692,7 @@
692692
693693 if (current != null && current.address.equals(host.getSocketAddress())) {
694694 logger.debug("[Control connection] {} is down/removed and it was the control host, triggering reconnect",
695- current.address);
695+ current.address);
696696 if (!current.isClosed())
697697 current.closeAsync();
698698 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 +81 −85
@@ -15,19 +15,18 @@
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 io.netty.buffer.ByteBuf;
2824
29-import com.datastax.driver.core.exceptions.DriverInternalError;
30-import com.datastax.driver.core.exceptions.InvalidTypeException;
25+import java.math.BigDecimal;
26+import java.math.BigInteger;
27+import java.net.InetAddress;
28+import java.nio.ByteBuffer;
29+import java.util.*;
3130
3231 /**
3332 * Data types supported by cassandra.
@@ -39,31 +38,32 @@
3938 */
4039 public enum Name {
4140
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- CUSTOM (0, ByteBuffer.class);
41+ ASCII(1, String.class),
42+ BIGINT(2, Long.class),
43+ BLOB(3, ByteBuffer.class),
44+ BOOLEAN(4, Boolean.class),
45+ COUNTER(5, Long.class),
46+ DECIMAL(6, BigDecimal.class),
47+ DOUBLE(7, Double.class),
48+ FLOAT(8, Float.class),
49+ INET(16, InetAddress.class),
50+ INT(9, Integer.class),
51+ TEXT(10, String.class),
52+ TIMESTAMP(11, Date.class),
53+ UUID(12, UUID.class),
54+ VARCHAR(13, String.class),
55+ VARINT(14, BigInteger.class),
56+ TIMEUUID(15, UUID.class),
57+ LIST(32, List.class),
58+ SET(34, Set.class),
59+ MAP(33, Map.class),
60+ CUSTOM(0, ByteBuffer.class);
6261
6362 final int protocolId;
6463 final Class<?> javaType;
6564
6665 private static final Name[] nameToIds;
66+
6767 static {
6868 int maxCode = -1;
6969 for (Name name : Name.values())
@@ -107,31 +107,31 @@
107107
108108 /**
109109 * Returns the Java Class corresponding to this CQL type name.
110- *
110+ * <p/>
111111 * The correspondence between CQL types and java ones is as follow:
112112 * <table>
113- * <caption>DataType to Java class correspondence</caption>
114- * <tr><th>DataType (CQL)</th><th>Java Class</th></tr>
115- * <tr><td>ASCII </td><td>String</td></tr>
116- * <tr><td>BIGINT </td><td>Long</td></tr>
117- * <tr><td>BLOB </td><td>ByteBuffer</td></tr>
118- * <tr><td>BOOLEAN </td><td>Boolean</td></tr>
119- * <tr><td>COUNTER </td><td>Long</td></tr>
120- * <tr><td>CUSTOM </td><td>ByteBuffer</td></tr>
121- * <tr><td>DECIMAL </td><td>BigDecimal</td></tr>
122- * <tr><td>DOUBLE </td><td>Double</td></tr>
123- * <tr><td>FLOAT </td><td>Float</td></tr>
124- * <tr><td>INET </td><td>InetAddress</td></tr>
125- * <tr><td>INT </td><td>Integer</td></tr>
126- * <tr><td>LIST </td><td>List</td></tr>
127- * <tr><td>MAP </td><td>Map</td></tr>
128- * <tr><td>SET </td><td>Set</td></tr>
129- * <tr><td>TEXT </td><td>String</td></tr>
130- * <tr><td>TIMESTAMP </td><td>Date</td></tr>
131- * <tr><td>UUID </td><td>UUID</td></tr>
132- * <tr><td>VARCHAR </td><td>String</td></tr>
133- * <tr><td>VARINT </td><td>BigInteger</td></tr>
134- * <tr><td>TIMEUUID </td><td>UUID</td></tr>
113+ * <caption>DataType to Java class correspondence</caption>
114+ * <tr><th>DataType (CQL)</th><th>Java Class</th></tr>
115+ * <tr><td>ASCII </td><td>String</td></tr>
116+ * <tr><td>BIGINT </td><td>Long</td></tr>
117+ * <tr><td>BLOB </td><td>ByteBuffer</td></tr>
118+ * <tr><td>BOOLEAN </td><td>Boolean</td></tr>
119+ * <tr><td>COUNTER </td><td>Long</td></tr>
120+ * <tr><td>CUSTOM </td><td>ByteBuffer</td></tr>
121+ * <tr><td>DECIMAL </td><td>BigDecimal</td></tr>
122+ * <tr><td>DOUBLE </td><td>Double</td></tr>
123+ * <tr><td>FLOAT </td><td>Float</td></tr>
124+ * <tr><td>INET </td><td>InetAddress</td></tr>
125+ * <tr><td>INT </td><td>Integer</td></tr>
126+ * <tr><td>LIST </td><td>List</td></tr>
127+ * <tr><td>MAP </td><td>Map</td></tr>
128+ * <tr><td>SET </td><td>Set</td></tr>
129+ * <tr><td>TEXT </td><td>String</td></tr>
130+ * <tr><td>TIMESTAMP </td><td>Date</td></tr>
131+ * <tr><td>UUID </td><td>UUID</td></tr>
132+ * <tr><td>VARCHAR </td><td>String</td></tr>
133+ * <tr><td>VARINT </td><td>BigInteger</td></tr>
134+ * <tr><td>TIMEUUID </td><td>UUID</td></tr>
135135 * </table>
136136 *
137137 * @return the java Class corresponding to this CQL type name.
@@ -152,12 +152,14 @@
152152 private final TypeCodec<?> codec;
153153
154154 private static final Map<Name, DataType> primitiveTypeMap = new EnumMap<Name, DataType>(Name.class);
155+
155156 static {
156157 for (Name name : Name.values()) {
157158 if (!name.isCollection() && name != Name.CUSTOM)
158159 primitiveTypeMap.put(name, new DataType(name, Collections.<DataType>emptyList(), TypeCodec.createFor(name)));
159160 }
160161 }
162+
161163 private static final Set<DataType> primitiveTypeSet = ImmutableSet.copyOf(primitiveTypeMap.values());
162164
163165 private DataType(DataType.Name name, List<DataType> typeArguments, TypeCodec<?> codec) {
@@ -191,7 +193,7 @@
191193
192194 @SuppressWarnings("unchecked")
193195 TypeCodec<Object> codec() {
194- return (TypeCodec<Object>)codec;
196+ return (TypeCodec<Object>) codec;
195197 }
196198
197199 /**
@@ -364,7 +366,7 @@
364366 /**
365367 * Returns the type of maps of {@code keyType} to {@code valueType} elements.
366368 *
367- * @param keyType the type of the map keys.
369+ * @param keyType the type of the map keys.
368370 * @param valueType the type of the map values.
369371 * @return the type of map of {@code keyType} to {@code valueType} elements.
370372 */
@@ -374,13 +376,13 @@
374376
375377 /**
376378 * Returns a Custom type.
377- * <p>
379+ * <p/>
378380 * A custom type is defined by the name of the class used on the Cassandra
379381 * side to implement it. Note that the support for custom type by the
380382 * driver is limited: values of a custom type won't be interpreted by the
381383 * driver in any way. They will thus have to be set (by {@link BoundStatement#setBytesUnsafe}
382384 * and retrieved (by {@link Row#getBytesUnsafe}) as raw ByteBuffer.
383- * <p>
385+ * <p/>
384386 * The use of custom types is rarely useful and is thus not encouraged.
385387 *
386388 * @param typeClassName the server-side fully qualified class name for the type.
@@ -403,17 +405,17 @@
403405
404406 /**
405407 * Returns the type arguments of this type.
406- * <p>
408+ * <p/>
407409 * Note that only the collection types (LIST, MAP, SET) have type
408410 * arguments. For the other types, this will return an empty list.
409- * <p>
411+ * <p/>
410412 * For the collection types:
411413 * <ul>
412- * <li>For lists and sets, this method returns one argument, the type of
413- * the elements.</li>
414- * <li>For maps, this method returns two arguments, the first one is the
415- * type of the map keys, the second one is the type of the map
416- * values.</li>
414+ * <li>For lists and sets, this method returns one argument, the type of
415+ * the elements.</li>
416+ * <li>For maps, this method returns two arguments, the first one is the
417+ * type of the map keys, the second one is the type of the map
418+ * values.</li>
417419 * </ul>
418420 *
419421 * @return an immutable list containing the type arguments of this type.
@@ -435,21 +437,20 @@
435437 /**
436438 * Parses a string value for the type this object represent, returning its
437439 * Cassandra binary representation.
438- * <p>
440+ * <p/>
439441 * Please note that currently, parsing collections is not supported and will
440442 * throw an {@code InvalidTypeException}.
441443 *
442444 * @param value the value to parse.
443445 * @return the binary representation of {@code value}.
444- *
445446 * @throws InvalidTypeException if {@code value} is not a valid string
446- * representation for this type. Please note that values for custom types
447- * can never be parsed and will always return this exception.
447+ * representation for this type. Please note that values for custom types
448+ * can never be parsed and will always return this exception.
448449 */
449450 public ByteBuffer parse(String value) {
450451 if (name == Name.CUSTOM)
451452 throw new InvalidTypeException(String.format("Cannot parse '%s' as value of custom type of class '%s' "
452- + "(values for custom type cannot be parse and must be inputted as bytes directly)", value, customClassName));
453+ + "(values for custom type cannot be parse and must be inputted as bytes directly)", value, customClassName));
453454
454455 if (name.isCollection())
455456 throw new InvalidTypeException(String.format("Cannot parse value as %s, parsing collections is not currently supported", name));
@@ -462,10 +463,9 @@
462463 *
463464 * @param value the value to format.
464465 * @return a string corresponding to the CQL representation of {@code value}.
465- *
466466 * @throws InvalidTypeException if {@code value} does not correspond to
467- * a CQL value (known by the driver). Please note that for custom types this
468- * method will always return this exception.
467+ * a CQL value (known by the driver). Please note that for custom types this
468+ * method will always return this exception.
469469 */
470470 public String format(Object value) {
471471 return value == null ? null : codec().format(value);
@@ -482,11 +482,10 @@
482482
483483 /**
484484 * Returns the Java Class corresponding to this type.
485- *
485+ * <p/>
486486 * This is a shortcut for {@code getName().asJavaClass()}.
487487 *
488488 * @return the java Class corresponding to this type.
489- *
490489 * @see Name#asJavaClass
491490 */
492491 public Class<?> asJavaClass() {
@@ -506,15 +505,14 @@
506505
507506 /**
508507 * Serialize a value of this type to bytes.
509- * <p>
508+ * <p/>
510509 * The actual format of the resulting bytes will correspond to the
511510 * Cassandra encoding for this type.
512511 *
513512 * @param value the value to serialize.
514513 * @return the value serialized, or {@code null} if {@code value} is null.
515- *
516514 * @throws InvalidTypeException if {@code value} is not a valid object
517- * for this {@code DataType}.
515+ * for this {@code DataType}.
518516 */
519517 public ByteBuffer serialize(Object value) {
520518 Class<?> providedClass = value.getClass();
@@ -532,7 +530,7 @@
532530
533531 /**
534532 * Deserialize a value of this type from the provided bytes.
535- * <p>
533+ * <p/>
536534 * The format of {@code bytes} must correspond to the Cassandra
537535 * encoding for this type.
538536 *
@@ -546,9 +544,8 @@
546544 * throwing an exception in that case. It is however highly discouraged to
547545 * store empty byte buffers for types for which it doesn't make sense, so
548546 * this implementation can generally be ignored).
549- *
550547 * @throws InvalidTypeException if {@code bytes} is not a valid
551- * encoding of an object of this {@code DataType}.
548+ * encoding of an object of this {@code DataType}.
552549 */
553550 public Object deserialize(ByteBuffer bytes) {
554551 return codec().deserialize(bytes);
@@ -556,7 +553,7 @@
556553
557554 /**
558555 * Serialize an object based on its java class.
559- * <p>
556+ * <p/>
560557 * This is equivalent to {@link #serialize} but with the difference that
561558 * the actual {@code DataType} of the resulting value is inferred from the
562559 * java class of {@code value}. The correspondence between CQL {@code DataType}
@@ -566,10 +563,9 @@
566563 *
567564 * @param value the value to serialize.
568565 * @return the value serialized, or {@code null} if {@code value} is null.
569- *
570566 * @throws IllegalArgumentException if {@code value} is not of a type
571- * corresponding to a CQL3 type, i.e. is not a Class that could be returned
572- * by {@link DataType#asJavaClass}.
567+ * corresponding to a CQL3 type, i.e. is not a Class that could be returned
568+ * by {@link DataType#asJavaClass}.
573569 */
574570 public static ByteBuffer serializeValue(Object value) {
575571 if (value == null)
@@ -591,15 +587,15 @@
591587
592588 @Override
593589 public final int hashCode() {
594- return Arrays.hashCode(new Object[]{ name, typeArguments, customClassName });
590+ return Arrays.hashCode(new Object[]{name, typeArguments, customClassName});
595591 }
596592
597593 @Override
598594 public final boolean equals(Object o) {
599- if(!(o instanceof DataType))
595+ if (!(o instanceof DataType))
600596 return false;
601597
602- DataType d = (DataType)o;
598+ DataType d = (DataType) o;
603599 return name == d.name && typeArguments.equals(d.typeArguments) && Objects.equal(customClassName, d.customClassName);
604600 }
605601
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 PreparedStatement{
23+public class DefaultPreparedStatement implements PreparedStatement {
2424
2525 final PreparedId preparedId;
2626
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +39 −37
@@ -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.
@@ -57,11 +59,11 @@
5759 try {
5860 switch (response.type) {
5961 case RESULT:
60- Responses.Result rm = (Responses.Result)response;
62+ Responses.Result rm = (Responses.Result) response;
6163 switch (rm.kind) {
6264 case SET_KEYSPACE:
6365 // propagate the keyspace change to other connections
64- session.poolsState.setKeyspace(((Responses.Result.SetKeyspace)rm).keyspace);
66+ session.poolsState.setKeyspace(((Responses.Result.SetKeyspace) rm).keyspace);
6567 set(ArrayBackedResultSet.fromMessage(rm, session, info, statement));
6668 break;
6769 case SCHEMA_CHANGE:
@@ -70,7 +72,7 @@
7072 if (!cluster.configuration.getQueryOptions().isMetadataEnabled()) {
7173 cluster.waitForSchemaAgreementAndSignal(connection, this, rs);
7274 } else {
73- Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm;
75+ Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange) rm;
7476 switch (scc.change) {
7577 case CREATED:
7678 if (scc.columnFamily.isEmpty()) {
@@ -99,7 +101,7 @@
99101 KeyspaceMetadata keyspace = cluster.metadata.getKeyspaceInternal(scc.keyspace);
100102 if (keyspace == null)
101103 logger.warn("Received a DROPPED notification for {}.{}, but this keyspace is unknown in our metadata",
102- scc.keyspace, scc.columnFamily);
104+ scc.keyspace, scc.columnFamily);
103105 else {
104106 final TableMetadata removed = keyspace.removeTable(scc.columnFamily);
105107 if (removed != null) {
@@ -133,7 +135,7 @@
133135 }
134136 break;
135137 case ERROR:
136- setException(((Responses.Error)response).asException(connection.address));
138+ setException(((Responses.Error) response).asException(connection.address));
137139 break;
138140 default:
139141 // This mean we have probably have a bad node, so defunct the connection
@@ -176,23 +178,23 @@
176178
177179 /**
178180 * Waits for the query to return and return its result.
179- *
181+ * <p/>
180182 * This method is usually more convenient than {@link #get} because it:
181183 * <ul>
182- * <li>Waits for the result uninterruptibly, and so doesn't throw
183- * {@link InterruptedException}.</li>
184- * <li>Returns meaningful exceptions, instead of having to deal
185- * with ExecutionException.</li>
184+ * <li>Waits for the result uninterruptibly, and so doesn't throw
185+ * {@link InterruptedException}.</li>
186+ * <li>Returns meaningful exceptions, instead of having to deal
187+ * with ExecutionException.</li>
186188 * </ul>
187189 * As such, it is the preferred way to get the future result.
188190 *
189191 * @throws NoHostAvailableException if no host in the cluster can be
190- * contacted successfully to execute this query.
191- * @throws QueryExecutionException if the query triggered an execution
192- * exception, that is an exception thrown by Cassandra when it cannot execute
193- * the query with the requested consistency level successfully.
192+ * contacted successfully to execute this query.
193+ * @throws QueryExecutionException if the query triggered an execution
194+ * exception, that is an exception thrown by Cassandra when it cannot execute
195+ * the query with the requested consistency level successfully.
194196 * @throws QueryValidationException if the query is invalid (syntax error,
195- * unauthorized or any other validation problem).
197+ * unauthorized or any other validation problem).
196198 */
197199 public ResultSet getUninterruptibly() {
198200 try {
@@ -205,26 +207,26 @@
205207 /**
206208 * Waits for the provided time for the query to return and return its
207209 * result if available.
208- *
210+ * <p/>
209211 * This method is usually more convenient than {@link #get} because it:
210212 * <ul>
211- * <li>Waits for the result uninterruptibly, and so doesn't throw
212- * {@link InterruptedException}.</li>
213- * <li>Returns meaningful exceptions, instead of having to deal
214- * with ExecutionException.</li>
213+ * <li>Waits for the result uninterruptibly, and so doesn't throw
214+ * {@link InterruptedException}.</li>
215+ * <li>Returns meaningful exceptions, instead of having to deal
216+ * with ExecutionException.</li>
215217 * </ul>
216218 * As such, it is the preferred way to get the future result.
217219 *
218220 * @throws NoHostAvailableException if no host in the cluster can be
219- * contacted successfully to execute this query.
220- * @throws QueryExecutionException if the query triggered an execution
221- * exception, that is an exception thrown by Cassandra when it cannot execute
222- * the query with the requested consistency level successfully.
221+ * contacted successfully to execute this query.
222+ * @throws QueryExecutionException if the query triggered an execution
223+ * exception, that is an exception thrown by Cassandra when it cannot execute
224+ * the query with the requested consistency level successfully.
223225 * @throws QueryValidationException if the query if invalid (syntax error,
224- * unauthorized or any other validation problem).
225- * @throws TimeoutException if the wait timed out (Note that this is
226- * different from a Cassandra timeout, which is a {@code
227- * QueryExecutionException}).
226+ * unauthorized or any other validation problem).
227+ * @throws TimeoutException if the wait timed out (Note that this is
228+ * different from a Cassandra timeout, which is a {@code
229+ * QueryExecutionException}).
228230 */
229231 public ResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException {
230232 try {
@@ -237,12 +239,12 @@
237239 /**
238240 * Attempts to cancel the execution of the request corresponding to this
239241 * future. This attempt will fail if the request has already returned.
240- * <p>
242+ * <p/>
241243 * Please note that this only cancels the request driver side, but nothing
242244 * is done to interrupt the execution of the request Cassandra side (and that even
243245 * if {@code mayInterruptIfRunning} is true) since Cassandra does not
244246 * support such interruption.
245- * <p>
247+ * <p/>
246248 * This method can be used to ensure no more work is performed driver side
247249 * (which, while it doesn't include stopping a request already submitted
248250 * to a Cassandra node, may include not retrying another Cassandra host on
@@ -262,7 +264,7 @@
262264 * <pre>
263265 *
264266 * @param mayInterruptIfRunning the value of this parameter is currently
265- * ignored.
267+ * ignored.
266268 * @return {@code false} if the future could not be cancelled (it has already
267269 * completed normally); {@code true} otherwise.
268270 */
@@ -271,7 +273,7 @@
271273 if (!super.cancel(mayInterruptIfRunning))
272274 return false;
273275
274- if(handler != null) {
276+ if (handler != null) {
275277 handler.cancel();
276278 }
277279 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 */
@@ -62,7 +62,7 @@
6262
6363 /**
6464 * The list of tried hosts for this query.
65- * <p>
65+ * <p/>
6666 * In general, this will be a singleton list with the host that coordinated
6767 * that query. However:
6868 * <ul>
@@ -74,7 +74,7 @@
7474 * <li>if {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}
7575 * are enabled, other hosts might have been tried speculatively as well.</li>
7676 * </ul>
77- * <p>
77+ * <p/>
7878 * If you are only interested in fetching the final (and often only) node
7979 * coordinating the query, {@link #getQueriedHost} provides a shortcut to
8080 * fetch the last element of the list returned by this method.
@@ -87,7 +87,7 @@
8787
8888 /**
8989 * Return the Cassandra host that coordinated this query.
90- * <p>
90+ * <p/>
9191 * This is a shortcut for {@code getTriedHosts().get(getTriedHosts().size())}.
9292 *
9393 * @return return the Cassandra host that coordinated this query.
@@ -101,7 +101,7 @@
101101 * due to the {@link com.datastax.driver.core.policies.RetryPolicy}, this
102102 * return the biggest consistency level that has been actually achieved by
103103 * the query.
104- * <p>
104+ * <p/>
105105 * Note that the default {@code RetryPolicy}
106106 * ({@link com.datastax.driver.core.policies.DefaultRetryPolicy})
107107 * will never allow a query to be successful without achieving the
@@ -131,12 +131,11 @@
131131
132132 /**
133133 * The paging state of the query.
134- *
134+ * <p/>
135135 * This object represents the next page to be fetched if this query is
136136 * multi page. It can be saved and reused later on the same statement.
137137 *
138138 * @return the paging state or null if there is no next page.
139- *
140139 * @see Statement#setPagingState(PagingState)
141140 */
142141 public PagingState getPagingState() {
@@ -147,12 +146,11 @@
147146
148147 /**
149148 * Returns the "raw" paging state of the query.
150- *
149+ * <p/>
151150 * Contrary to {@link #getPagingState()}, there will be no validation when
152151 * this is later reinjected into a statement.
153152 *
154153 * @return the paging state or null if there is no next page.
155- *
156154 * @see Statement#setPagingStateUnsafe(byte[])
157155 */
158156 public byte[] getPagingStateUnsafe() {
@@ -163,15 +161,15 @@
163161
164162 /**
165163 * Whether the cluster had reached schema agreement after the execution of this query.
166- *
164+ * <p/>
167165 * After a successful schema-altering query (ex: creating a table), the driver
168166 * will check if the cluster's nodes agree on the new schema version. If not,
169167 * it will keep retrying for a given delay (configurable via
170168 * {@link Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int)}).
171- * <p>
169+ * <p/>
172170 * If this method returns {@code false}, clients can call {@link Metadata#checkSchemaAgreement()}
173171 * later to perform the check manually.
174- * <p>
172+ * <p/>
175173 * Note that the schema agreement check is only performed for schema-altering queries
176174 * For other query types, this method will always return {@code true}.
177175 *
modified driver-core/src/main/java/com/datastax/driver/core/Frame.java +11 −13
@@ -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,13 +32,13 @@
3332 /**
3433 * On-wire frame.
3534 * Frames are defined as:
36- *
37- * 0 8 16 24 32
38- * +---------+---------+---------+---------+
39- * | version | flags | stream | opcode |
40- * +---------+---------+---------+---------+
41- * | length |
42- * +---------+---------+---------+---------+
35+ * <p/>
36+ * 0 8 16 24 32
37+ * +---------+---------+---------+---------+
38+ * | version | flags | stream | opcode |
39+ * +---------+---------+---------+---------+
40+ * | length |
41+ * +---------+---------+---------+---------+
4342 */
4443 private Frame(Header header, ByteBuf body) {
4544 this.header = header;
@@ -88,8 +87,7 @@
8887 this.opcode = opcode;
8988 }
9089
91- public static enum Flag
92- {
90+ public static enum Flag {
9391 // The order of that enum matters!!
9492 COMPRESSED,
9593 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/GettableData.java +65 −101
@@ -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 be retrieved by index (starting at 0), or by name.
2828 */
@@ -32,7 +32,6 @@
3232 *
3333 * @param i the index ({@code 0 <= i < size()}) of the value to check.
3434 * @return whether the {@code i}th value is NULL.
35- *
3635 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
3736 */
3837 boolean isNull(int i);
@@ -42,7 +41,6 @@
4241 *
4342 * @param name the name of the value to check.
4443 * @return whether the value for {@code name} is NULL.
45- *
4644 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
4745 */
4846 boolean isNull(String name);
@@ -53,9 +51,8 @@
5351 * @param i the index to retrieve.
5452 * @return the boolean value of the {@code i}th value. If the
5553 * value is NULL, {@code false} is returned.
56- *
5754 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
58- * @throws InvalidTypeException if value {@code i} is not of type BOOLEAN.
55+ * @throws InvalidTypeException if value {@code i} is not of type BOOLEAN.
5956 */
6057 boolean getBool(int i);
6158
@@ -65,9 +62,8 @@
6562 * @param name the name to retrieve.
6663 * @return the boolean value for {@code name}. If the value is NULL,
6764 * {@code false} is returned.
68- *
6965 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
70- * @throws InvalidTypeException if value {@code name} is not of type BOOLEAN.
66+ * @throws InvalidTypeException if value {@code name} is not of type BOOLEAN.
7167 */
7268 boolean getBool(String name);
7369
@@ -77,9 +73,8 @@
7773 * @param i the index to retrieve.
7874 * @return the value of the {@code i}th value as an integer. If the
7975 * value is NULL, {@code 0} is returned.
80- *
8176 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
82- * @throws InvalidTypeException if value {@code i} is not of type INT.
77+ * @throws InvalidTypeException if value {@code i} is not of type INT.
8378 */
8479 int getInt(int i);
8580
@@ -89,9 +84,8 @@
8984 * @param name the name to retrieve.
9085 * @return the value for {@code name} as an integer. If the value is NULL,
9186 * {@code 0} is returned.
92- *
9387 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
94- * @throws InvalidTypeException if value {@code name} is not of type INT.
88+ * @throws InvalidTypeException if value {@code name} is not of type INT.
9589 */
9690 int getInt(String name);
9791
@@ -101,9 +95,8 @@
10195 * @param i the index to retrieve.
10296 * @return the value of the {@code i}th value as a long. If the
10397 * value is NULL, {@code 0L} is returned.
104- *
10598 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
106- * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
99+ * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
107100 */
108101 long getLong(int i);
109102
@@ -113,9 +106,8 @@
113106 * @param name the name to retrieve.
114107 * @return the value for {@code name} as a long. If the value is NULL,
115108 * {@code 0L} is returned.
116- *
117109 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
118- * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
110+ * @throws InvalidTypeException if value {@code i} is not of type BIGINT or COUNTER.
119111 */
120112 long getLong(String name);
121113
@@ -125,9 +117,8 @@
125117 * @param i the index to retrieve.
126118 * @return the value of the {@code i}th value as a data. If the
127119 * value is NULL, {@code null} is returned.
128- *
129120 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
130- * @throws InvalidTypeException if value {@code i} is not of type TIMESTAMP.
121+ * @throws InvalidTypeException if value {@code i} is not of type TIMESTAMP.
131122 */
132123 Date getDate(int i);
133124
@@ -137,9 +128,8 @@
137128 * @param name the name to retrieve.
138129 * @return the value for {@code name} as a date. If the value is NULL,
139130 * {@code null} is returned.
140- *
141131 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
142- * @throws InvalidTypeException if value {@code name} is not of type TIMESTAMP.
132+ * @throws InvalidTypeException if value {@code name} is not of type TIMESTAMP.
143133 */
144134 Date getDate(String name);
145135
@@ -149,9 +139,8 @@
149139 * @param i the index to retrieve.
150140 * @return the value of the {@code i}th value as a float. If the
151141 * value is NULL, {@code 0.0f} is returned.
152- *
153142 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
154- * @throws InvalidTypeException if value {@code i} is not of type FLOAT.
143+ * @throws InvalidTypeException if value {@code i} is not of type FLOAT.
155144 */
156145 float getFloat(int i);
157146
@@ -161,9 +150,8 @@
161150 * @param name the name to retrieve.
162151 * @return the value for {@code name} as a float. If the value is NULL,
163152 * {@code 0.0f} is returned.
164- *
165153 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
166- * @throws InvalidTypeException if value {@code name} is not of type FLOAT.
154+ * @throws InvalidTypeException if value {@code name} is not of type FLOAT.
167155 */
168156 float getFloat(String name);
169157
@@ -173,9 +161,8 @@
173161 * @param i the index to retrieve.
174162 * @return the value of the {@code i}th value as a double. If the
175163 * value is NULL, {@code 0.0} is returned.
176- *
177164 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
178- * @throws InvalidTypeException if value {@code i} is not of type DOUBLE.
165+ * @throws InvalidTypeException if value {@code i} is not of type DOUBLE.
179166 */
180167 double getDouble(int i);
181168
@@ -185,15 +172,14 @@
185172 * @param name the name to retrieve.
186173 * @return the value for {@code name} as a double. If the value is NULL,
187174 * {@code 0.0} is returned.
188- *
189175 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
190- * @throws InvalidTypeException if value {@code name} is not of type DOUBLE.
176+ * @throws InvalidTypeException if value {@code name} is not of type DOUBLE.
191177 */
192178 double getDouble(String name);
193179
194180 /**
195181 * Returns the {@code i}th value as a ByteBuffer.
196- *
182+ * <p/>
197183 * Note: this method always return the bytes composing the value, even if
198184 * it is not of type BLOB. That is, this method never throw an
199185 * InvalidTypeException. However, if the type is not BLOB, it is up to the
@@ -202,14 +188,13 @@
202188 * @param i the index to retrieve.
203189 * @return the value of the {@code i}th value as a ByteBuffer. If the
204190 * value is NULL, {@code null} is returned.
205- *
206191 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
207192 */
208193 ByteBuffer getBytesUnsafe(int i);
209194
210195 /**
211196 * Returns the value for {@code name} as a ByteBuffer.
212- *
197+ * <p/>
213198 * Note: this method always return the bytes composing the value, even if
214199 * it is not of type BLOB. That is, this method never throw an
215200 * InvalidTypeException. However, if the type is not BLOB, it is up to the
@@ -218,38 +203,35 @@
218203 * @param name the name to retrieve.
219204 * @return the value for {@code name} as a ByteBuffer. If the value is NULL,
220205 * {@code null} is returned.
221- *
222206 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
223207 */
224208 ByteBuffer getBytesUnsafe(String name);
225209
226210 /**
227211 * Returns the {@code i}th value as a byte array.
228- * <p>
212+ * <p/>
229213 * Note that this method validate that the value is of type BLOB. If you want to retrieve
230214 * the bytes for any type of values, use {@link #getBytesUnsafe(int)} instead.
231215 *
232216 * @param i the index to retrieve.
233217 * @return the value of the {@code i}th value as a byte array. If the
234218 * value is NULL, {@code null} is returned.
235- *
236219 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
237- * @throws InvalidTypeException if value {@code i} type is not of type BLOB.
220+ * @throws InvalidTypeException if value {@code i} type is not of type BLOB.
238221 */
239222 ByteBuffer getBytes(int i);
240223
241224 /**
242225 * Returns the value for {@code name} as a byte array.
243- * <p>
226+ * <p/>
244227 * Note that this method validate that the value is of type BLOB. If you want to retrieve
245228 * the bytes for any type of values, use {@link #getBytesUnsafe(String)} instead.
246229 *
247230 * @param name the name to retrieve.
248231 * @return the value for {@code name} as a byte array. If the value is NULL,
249232 * {@code null} is returned.
250- *
251233 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
252- * @throws InvalidTypeException if value {@code i} type is not of type BLOB.
234+ * @throws InvalidTypeException if value {@code i} type is not of type BLOB.
253235 */
254236 ByteBuffer getBytes(String name);
255237
@@ -259,10 +241,9 @@
259241 * @param i the index to retrieve.
260242 * @return the value of the {@code i}th value as a string. If the
261243 * value is NULL, {@code null} is returned.
262- *
263244 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
264- * @throws InvalidTypeException if value {@code i} type is none of:
265- * VARCHAR, TEXT or ASCII.
245+ * @throws InvalidTypeException if value {@code i} type is none of:
246+ * VARCHAR, TEXT or ASCII.
266247 */
267248 String getString(int i);
268249
@@ -272,10 +253,9 @@
272253 * @param name the name to retrieve.
273254 * @return the value for {@code name} as a string. If the value is NULL,
274255 * {@code null} is returned.
275- *
276256 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
277- * @throws InvalidTypeException if value {@code name} type is none of:
278- * VARCHAR, TEXT or ASCII.
257+ * @throws InvalidTypeException if value {@code name} type is none of:
258+ * VARCHAR, TEXT or ASCII.
279259 */
280260 String getString(String name);
281261
@@ -285,9 +265,8 @@
285265 * @param i the index to retrieve.
286266 * @return the value of the {@code i}th value as a variable
287267 * length integer. If the value is NULL, {@code null} is returned.
288- *
289268 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
290- * @throws InvalidTypeException if value {@code i} is not of type VARINT.
269+ * @throws InvalidTypeException if value {@code i} is not of type VARINT.
291270 */
292271 BigInteger getVarint(int i);
293272
@@ -297,9 +276,8 @@
297276 * @param name the name to retrieve.
298277 * @return the value for {@code name} as a variable length integer.
299278 * If the value is NULL, {@code null} is returned.
300- *
301279 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
302- * @throws InvalidTypeException if value {@code name} is not of type VARINT.
280+ * @throws InvalidTypeException if value {@code name} is not of type VARINT.
303281 */
304282 BigInteger getVarint(String name);
305283
@@ -309,9 +287,8 @@
309287 * @param i the index to retrieve.
310288 * @return the value of the {@code i}th value as a variable
311289 * length decimal. If the value is NULL, {@code null} is returned.
312- *
313290 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
314- * @throws InvalidTypeException if value {@code i} is not of type DECIMAL.
291+ * @throws InvalidTypeException if value {@code i} is not of type DECIMAL.
315292 */
316293 BigDecimal getDecimal(int i);
317294
@@ -321,9 +298,8 @@
321298 * @param name the name to retrieve.
322299 * @return the value for {@code name} as a variable length decimal.
323300 * If the value is NULL, {@code null} is returned.
324- *
325301 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
326- * @throws InvalidTypeException if value {@code name} is not of type DECIMAL.
302+ * @throws InvalidTypeException if value {@code name} is not of type DECIMAL.
327303 */
328304 BigDecimal getDecimal(String name);
329305
@@ -333,10 +309,9 @@
333309 * @param i the index to retrieve.
334310 * @return the value of the {@code i}th value as a UUID.
335311 * If the value is NULL, {@code null} is returned.
336- *
337312 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
338- * @throws InvalidTypeException if value {@code i} is not of type UUID
339- * or TIMEUUID.
313+ * @throws InvalidTypeException if value {@code i} is not of type UUID
314+ * or TIMEUUID.
340315 */
341316 UUID getUUID(int i);
342317
@@ -346,10 +321,9 @@
346321 * @param name the name to retrieve.
347322 * @return the value for {@code name} as a UUID.
348323 * If the value is NULL, {@code null} is returned.
349- *
350324 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
351- * @throws InvalidTypeException if value {@code name} is not of type
352- * UUID or TIMEUUID.
325+ * @throws InvalidTypeException if value {@code name} is not of type
326+ * UUID or TIMEUUID.
353327 */
354328 UUID getUUID(String name);
355329
@@ -359,9 +333,8 @@
359333 * @param i the index to retrieve.
360334 * @return the value of the {@code i}th value as an InetAddress.
361335 * If the value is NULL, {@code null} is returned.
362- *
363336 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
364- * @throws InvalidTypeException if value {@code i} is not of type INET.
337+ * @throws InvalidTypeException if value {@code i} is not of type INET.
365338 */
366339 InetAddress getInet(int i);
367340
@@ -371,120 +344,113 @@
371344 * @param name the name to retrieve.
372345 * @return the value for {@code name} as an InetAddress.
373346 * If the value is NULL, {@code null} is returned.
374- *
375347 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
376- * @throws InvalidTypeException if value {@code name} is not of type
377- * INET.
348+ * @throws InvalidTypeException if value {@code name} is not of type
349+ * INET.
378350 */
379351 InetAddress getInet(String name);
380352
381353 /**
382354 * Returns the {@code i}th value as a list.
383355 *
384- * @param <T> the type of the elements of the list to return.
385- * @param i the index to retrieve.
356+ * @param <T> the type of the elements of the list to return.
357+ * @param i the index to retrieve.
386358 * @param elementsClass the class for the elements of the list to retrieve.
387359 * @return the value of the {@code i}th value as a list of
388360 * {@code elementsClass} objects. If the value is NULL, an empty list is
389361 * returned (note that Cassandra makes no difference between an empty list
390362 * and column of type list that is not set). The returned list is immutable.
391- *
392363 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
393- * @throws InvalidTypeException if value {@code i} is not a list or if its
394- * elements are not of class {@code elementsClass}.
364+ * @throws InvalidTypeException if value {@code i} is not a list or if its
365+ * elements are not of class {@code elementsClass}.
395366 */
396367 <T> List<T> getList(int i, Class<T> elementsClass);
397368
398369 /**
399370 * Returns the value for {@code name} as a list.
400371 *
401- * @param <T> the type of the elements of the list to return.
402- * @param name the name to retrieve.
372+ * @param <T> the type of the elements of the list to return.
373+ * @param name the name to retrieve.
403374 * @param elementsClass the class for the elements of the list to retrieve.
404375 * @return the value of the {@code i}th value as a list of
405376 * {@code elementsClass} objects. If the value is NULL, an empty list is
406377 * returned (note that Cassandra makes no difference between an empty list
407378 * and column of type list that is not set). The returned list is immutable.
408- *
409379 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
410- * @throws InvalidTypeException if value {@code name} is not a list or if its
411- * elements are not of class {@code elementsClass}.
380+ * @throws InvalidTypeException if value {@code name} is not a list or if its
381+ * elements are not of class {@code elementsClass}.
412382 */
413383 <T> List<T> getList(String name, Class<T> elementsClass);
414384
415385 /**
416386 * Returns the {@code i}th value as a set.
417387 *
418- * @param <T> the type of the elements of the set to return.
419- * @param i the index to retrieve.
388+ * @param <T> the type of the elements of the set to return.
389+ * @param i the index to retrieve.
420390 * @param elementsClass the class for the elements of the set to retrieve.
421391 * @return the value of the {@code i}th value as a set of
422392 * {@code elementsClass} objects. If the value is NULL, an empty set is
423393 * returned (note that Cassandra makes no difference between an empty set
424394 * and column of type set that is not set). The returned set is immutable.
425- *
426395 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
427- * @throws InvalidTypeException if value {@code i} is not a set or if its
428- * elements are not of class {@code elementsClass}.
396+ * @throws InvalidTypeException if value {@code i} is not a set or if its
397+ * elements are not of class {@code elementsClass}.
429398 */
430399 <T> Set<T> getSet(int i, Class<T> elementsClass);
431400
432401 /**
433402 * Returns the value for {@code name} as a set.
434403 *
435- * @param <T> the type of the elements of the set to return.
436- * @param name the name to retrieve.
404+ * @param <T> the type of the elements of the set to return.
405+ * @param name the name to retrieve.
437406 * @param elementsClass the class for the elements of the set to retrieve.
438407 * @return the value of the {@code i}th value as a set of
439408 * {@code elementsClass} objects. If the value is NULL, an empty set is
440409 * returned (note that Cassandra makes no difference between an empty set
441410 * and column of type set that is not set). The returned set is immutable.
442- *
443411 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
444- * @throws InvalidTypeException if value {@code name} is not a set or if its
445- * elements are not of class {@code elementsClass}.
412+ * @throws InvalidTypeException if value {@code name} is not a set or if its
413+ * elements are not of class {@code elementsClass}.
446414 */
447415 <T> Set<T> getSet(String name, Class<T> elementsClass);
448416
449417 /**
450418 * Returns the {@code i}th value as a map.
451419 *
452- * @param <K> the type of the keys of the map to return.
453- * @param <V> the type of the values of the map to return.
454- * @param i the index to retrieve.
455- * @param keysClass the class for the keys of the map to retrieve.
420+ * @param <K> the type of the keys of the map to return.
421+ * @param <V> the type of the values of the map to return.
422+ * @param i the index to retrieve.
423+ * @param keysClass the class for the keys of the map to retrieve.
456424 * @param valuesClass the class for the values of the map to retrieve.
457425 * @return the value of the {@code i}th value as a map of
458426 * {@code keysClass} to {@code valuesClass} objects. If the value is NULL,
459427 * an empty map is returned (note that Cassandra makes no difference
460428 * between an empty map and column of type map that is not set). The
461429 * returned map is immutable.
462- *
463430 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
464- * @throws InvalidTypeException if value {@code i} is not a map, if its
465- * keys are not of class {@code keysClass} or if its values are not of
466- * class {@code valuesClass}.
431+ * @throws InvalidTypeException if value {@code i} is not a map, if its
432+ * keys are not of class {@code keysClass} or if its values are not of
433+ * class {@code valuesClass}.
467434 */
468435 <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass);
469436
470437 /**
471438 * Returns the value for {@code name} as a map.
472439 *
473- * @param <K> the type of the keys of the map to return.
474- * @param <V> the type of the values of the map to return.
475- * @param name the name to retrieve.
476- * @param keysClass the class for the keys of the map to retrieve.
440+ * @param <K> the type of the keys of the map to return.
441+ * @param <V> the type of the values of the map to return.
442+ * @param name the name to retrieve.
443+ * @param keysClass the class for the keys of the map to retrieve.
477444 * @param valuesClass the class for the values of the map to retrieve.
478445 * @return the value of the {@code i}th value as a map of
479446 * {@code keysClass} to {@code valuesClass} objects. If the value is NULL,
480447 * an empty map is returned (note that Cassandra makes no difference
481448 * between an empty map and column of type map that is not set). The
482449 * returned map is immutable.
483- *
484450 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
485- * @throws InvalidTypeException if value {@code name} is not a map, if its
486- * keys are not of class {@code keysClass} or if its values are not of
487- * class {@code valuesClass}.
451+ * @throws InvalidTypeException if value {@code name} is not a map, if its
452+ * keys are not of class {@code keysClass} or if its values are not of
453+ * class {@code valuesClass}.
488454 */
489455 <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass);
490456
@@ -496,7 +462,6 @@
496462 * @return the value of the {@code i}th value as the Java type matching its CQL type.
497463 * If the value is NULL and is a simple type, NULL is returned.
498464 * If it is NULL and is a collection type, an empty (immutable) collection is returned.
499- *
500465 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
501466 */
502467 Object getObject(int i);
@@ -508,7 +473,6 @@
508473 * @return the value of the {@code i}th value as the Java type matching its CQL type.
509474 * If the value is NULL and is a simple type, NULL is returned.
510475 * If it is NULL and is a collection type, an empty (immutable) collection is returned.
511- *
512476 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
513477 */
514478 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 +31 −26
@@ -15,6 +15,14 @@
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.base.Throwables;
21+import com.google.common.collect.Lists;
22+import com.google.common.util.concurrent.*;
23+import org.slf4j.Logger;
24+import org.slf4j.LoggerFactory;
25+
1826 import java.util.ArrayList;
1927 import java.util.List;
2028 import java.util.ListIterator;
@@ -26,19 +34,7 @@
2634 import java.util.concurrent.locks.Lock;
2735 import java.util.concurrent.locks.ReentrantLock;
2836
29-import com.google.common.base.Throwables;
30-import com.google.common.collect.Lists;
31-import com.google.common.util.concurrent.*;
32-import org.slf4j.Logger;
33-import org.slf4j.LoggerFactory;
34-
35-import com.datastax.driver.core.exceptions.AuthenticationException;
36-import com.datastax.driver.core.utils.MoreFutures;
37-
38-import static com.datastax.driver.core.Connection.State.GONE;
39-import static com.datastax.driver.core.Connection.State.OPEN;
40-import static com.datastax.driver.core.Connection.State.RESURRECTING;
41-import static com.datastax.driver.core.Connection.State.TRASHED;
37+import static com.datastax.driver.core.Connection.State.*;
4238
4339 class HostConnectionPool implements Connection.Owner {
4440
@@ -57,9 +53,13 @@
5753
5854 final List<Connection> connections;
5955 private final AtomicInteger open;
60- /** The total number of in-flight requests on all connections of this pool. */
56+ /**
57+ * The total number of in-flight requests on all connections of this pool.
58+ */
6159 final AtomicInteger totalInFlight = new AtomicInteger();
62- /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/
60+ /**
61+ * The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}
62+ */
6363 private final AtomicInteger maxTotalInFlight = new AtomicInteger();
6464 final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
6565
@@ -73,10 +73,11 @@
7373
7474 private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
7575
76- private enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING }
76+ private enum Phase {INITIALIZING, READY, INIT_FAILED, CLOSING}
77+
7778 private final AtomicReference<Phase> phase = new AtomicReference<Phase>(Phase.INITIALIZING);
7879
79- public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager){
80+ public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager) {
8081 assert hostDistance != HostDistance.IGNORED;
8182 this.host = host;
8283 this.hostDistance = hostDistance;
@@ -144,7 +145,7 @@
144145 forceClose(connections);
145146 } else {
146147 logger.debug("Created connection pool to host {} ({} connections needed, {} successfully opened)",
147- host, coreSize, connections.size());
148+ host, coreSize, connections.size());
148149 phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
149150 initFuture.set(null);
150151 }
@@ -264,7 +265,7 @@
264265 } else if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
265266 // Add a connection if we fill the first n-1 connections and almost fill the last one
266267 int currentCapacity = (connectionCount - 1) * StreamIdGenerator.MAX_STREAM_PER_CONNECTION
267- + options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance);
268+ + options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance);
268269 if (totalInFlightCount > currentCapacity)
269270 maybeSpawnNewConnection();
270271 }
@@ -398,7 +399,7 @@
398399 return true;
399400
400401 // First, make sure we don't go below core connections
401- for (;;) {
402+ for (; ; ) {
402403 int opened = open.get();
403404 if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
404405 connection.state.set(OPEN);
@@ -422,7 +423,7 @@
422423 private boolean addConnectionIfUnderMaximum() {
423424
424425 // First, make sure we don't cross the allowed limit of open connections
425- for(;;) {
426+ for (; ; ) {
426427 int opened = open.get();
427428 if (opened >= options().getMaxConnectionsPerHost(hostDistance))
428429 return false;
@@ -541,7 +542,9 @@
541542 cleanupTrash(now);
542543 }
543544
544- /** If we have more active connections than needed, trash some of them */
545+ /**
546+ * If we have more active connections than needed, trash some of them
547+ */
545548 private void shrinkIfBelowCapacity() {
546549 int currentLoad = maxTotalInFlight.getAndSet(totalInFlight.get());
547550
@@ -553,7 +556,7 @@
553556 int toTrash = Math.max(0, actual - needed);
554557
555558 logger.trace("Current inFlight = {}, {} connections needed, {} connections available, trashing {}",
556- currentLoad, needed, actual, toTrash);
559+ currentLoad, needed, actual, toTrash);
557560
558561 if (toTrash <= 0)
559562 return;
@@ -566,7 +569,9 @@
566569 }
567570 }
568571
569- /** Close connections that have been sitting in the trash for too long */
572+ /**
573+ * Close connections that have been sitting in the trash for too long
574+ */
570575 private void cleanupTrash(long now) {
571576 for (Connection connection : trash) {
572577 if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) {
@@ -606,8 +611,8 @@
606611 future = new CloseFuture.Forwarding(discardAvailableConnections());
607612
608613 return closeFuture.compareAndSet(null, future)
609- ? future
610- : closeFuture.get(); // We raced, it's ok, return the future that was actually set
614+ ? future
615+ : closeFuture.get(); // We raced, it's ok, return the future that was actually set
611616 }
612617
613618 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/KeyspaceMetadata.java +7 −7
@@ -26,9 +26,9 @@
2626 */
2727 public class KeyspaceMetadata {
2828
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";
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";
3232 private static final String STRATEGY_OPTIONS = "strategy_options";
3333
3434 private final String name;
@@ -114,10 +114,10 @@
114114 /**
115115 * Returns a {@code String} containing CQL queries representing this
116116 * keyspace and the table it contains.
117- *
117+ * <p/>
118118 * In other words, this method returns the queries that would allow to
119119 * recreate the schema of this keyspace, along with all its table.
120- *
120+ * <p/>
121121 * Note that the returned String is formatted to be human readable (for
122122 * some definition of human readable at least).
123123 *
@@ -137,7 +137,7 @@
137137
138138 /**
139139 * Returns a CQL query representing this keyspace.
140- *
140+ * <p/>
141141 * This method returns a single 'CREATE KEYSPACE' query with the options
142142 * corresponding to this keyspace definition.
143143 *
@@ -166,7 +166,7 @@
166166 if (o == null || getClass() != o.getClass())
167167 return false;
168168
169- KeyspaceMetadata that = (KeyspaceMetadata)o;
169+ KeyspaceMetadata that = (KeyspaceMetadata) o;
170170
171171 if (durableWrites != that.durableWrites)
172172 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 +49 −39
@@ -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);
41+
4242 public int encodedSize(R request);
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, Requests.Startup.coder),
66- CREDENTIALS (4, Requests.Credentials.coder, null),
67- OPTIONS (5, Requests.Options.coder, Requests.Options.coder),
68- QUERY (7, Requests.Query.coderV1, Requests.Query.coderV2),
69- PREPARE (9, Requests.Prepare.coder, Requests.Prepare.coder),
70- EXECUTE (10, Requests.Execute.coderV1, Requests.Execute.coderV2),
71- REGISTER (11, Requests.Register.coder, Requests.Register.coder),
72- BATCH (13, null, Requests.Batch.coder),
73- AUTH_RESPONSE (15, Requests.AuthResponse.coder, Requests.AuthResponse.coder);
66+ STARTUP(1, Requests.Startup.coder, Requests.Startup.coder),
67+ CREDENTIALS(4, Requests.Credentials.coder, null),
68+ OPTIONS(5, Requests.Options.coder, Requests.Options.coder),
69+ QUERY(7, Requests.Query.coderV1, Requests.Query.coderV2),
70+ PREPARE(9, Requests.Prepare.coder, Requests.Prepare.coder),
71+ EXECUTE(10, Requests.Execute.coderV1, Requests.Execute.coderV2),
72+ REGISTER(11, Requests.Register.coder, Requests.Register.coder),
73+ BATCH(13, null, Requests.Batch.coder),
74+ AUTH_RESPONSE(15, Requests.AuthResponse.coder, Requests.AuthResponse.coder);
7475
7576 public final int opcode;
7677 private final Coder<?> coderV1;
@@ -82,8 +83,7 @@
8283 this.coderV2 = coderV2;
8384 }
8485
85- public Coder<?> coder(int version)
86- {
86+ public Coder<?> coder(int version) {
8787 assert version == 1 || version == 2 : "Unsupported protocol version, we shouldn't have arrived here";
8888 return version == 1 ? coderV1 : coderV2;
8989 }
@@ -107,26 +107,36 @@
107107
108108 ConsistencyLevel consistency() {
109109 switch (this.type) {
110- case QUERY: return ((Requests.Query)this).options.consistency;
111- case EXECUTE: return ((Requests.Execute)this).options.consistency;
112- case BATCH: return ((Requests.Batch)this).consistency;
113- default: return null;
110+ case QUERY:
111+ return ((Requests.Query) this).options.consistency;
112+ case EXECUTE:
113+ return ((Requests.Execute) this).options.consistency;
114+ case BATCH:
115+ return ((Requests.Batch) this).consistency;
116+ default:
117+ return null;
114118 }
115119 }
116120
117121 ConsistencyLevel serialConsistency() {
118122 switch (this.type) {
119- case QUERY: return ((Requests.Query)this).options.serialConsistency;
120- case EXECUTE: return ((Requests.Execute)this).options.serialConsistency;
121- default: return null;
123+ case QUERY:
124+ return ((Requests.Query) this).options.serialConsistency;
125+ case EXECUTE:
126+ return ((Requests.Execute) this).options.serialConsistency;
127+ default:
128+ return null;
122129 }
123130 }
124131
125132 ByteBuffer pagingState() {
126133 switch (this.type) {
127- case QUERY: return ((Requests.Query)this).options.pagingState;
128- case EXECUTE: return ((Requests.Execute)this).options.pagingState;
129- default: return null;
134+ case QUERY:
135+ return ((Requests.Query) this).options.pagingState;
136+ case EXECUTE:
137+ return ((Requests.Execute) this).options.pagingState;
138+ default:
139+ return null;
130140 }
131141 }
132142
@@ -142,20 +152,21 @@
142152 public static abstract class Response extends Message {
143153
144154 public enum Type {
145- ERROR (0, Responses.Error.decoder, Responses.Error.decoder),
146- READY (2, Responses.Ready.decoder, Responses.Ready.decoder),
147- AUTHENTICATE (3, Responses.Authenticate.decoder, Responses.Authenticate.decoder),
148- SUPPORTED (6, Responses.Supported.decoder, Responses.Supported.decoder),
149- RESULT (8, Responses.Result.decoderV1, Responses.Result.decoderV2),
150- EVENT (12, Responses.Event.decoder, Responses.Event.decoder),
151- AUTH_CHALLENGE (14, Responses.AuthChallenge.decoder, Responses.AuthChallenge.decoder),
152- AUTH_SUCCESS (16, Responses.AuthSuccess.decoder, Responses.AuthSuccess.decoder);
155+ ERROR(0, Responses.Error.decoder, Responses.Error.decoder),
156+ READY(2, Responses.Ready.decoder, Responses.Ready.decoder),
157+ AUTHENTICATE(3, Responses.Authenticate.decoder, Responses.Authenticate.decoder),
158+ SUPPORTED(6, Responses.Supported.decoder, Responses.Supported.decoder),
159+ RESULT(8, Responses.Result.decoderV1, Responses.Result.decoderV2),
160+ EVENT(12, Responses.Event.decoder, Responses.Event.decoder),
161+ AUTH_CHALLENGE(14, Responses.AuthChallenge.decoder, Responses.AuthChallenge.decoder),
162+ AUTH_SUCCESS(16, Responses.AuthSuccess.decoder, Responses.AuthSuccess.decoder);
153163
154164 public final int opcode;
155165 private final Decoder<?> decoderV1;
156166 private final Decoder<?> decoderV2;
157167
158168 private static final Type[] opcodeIdx;
169+
159170 static {
160171 int maxOpcode = -1;
161172 for (Type type : Type.values())
@@ -181,8 +192,7 @@
181192 return t;
182193 }
183194
184- public Decoder<?> decoder(int version)
185- {
195+ public Decoder<?> decoder(int version) {
186196 assert version == 1 || version == 2 : "Unsupported protocol version, we shouldn't have arrived here";
187197 return version == 1 ? decoderV1 : decoderV2;
188198 }
@@ -239,7 +249,7 @@
239249 flags.add(Frame.Header.Flag.TRACING);
240250
241251 @SuppressWarnings("unchecked")
242- Coder<Request> coder = (Coder<Request>)request.type.coder(protocolVersion);
252+ Coder<Request> coder = (Coder<Request>) request.type.coder(protocolVersion);
243253 ByteBuf body = ctx.alloc().buffer(coder.encodedSize(request));
244254 coder.encode(request, body);
245255
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +43 −46
@@ -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,12 +28,6 @@
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-
3131 /**
3232 * Keeps metadata on the connected cluster, including known nodes and schema definitions.
3333 */
@@ -127,7 +127,7 @@
127127
128128 private Map<String, TableMetadata> buildTables(KeyspaceMetadata keyspace, List<Row> tableRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) {
129129 Map<String, TableMetadata> tables = new LinkedHashMap<String, TableMetadata>();
130- if(tableRows != null) {
130+ if (tableRows != null) {
131131 for (Row tableDef : tableRows) {
132132 String cfName = tableDef.getString(TableMetadata.CF_NAME);
133133 try {
@@ -156,8 +156,8 @@
156156 } catch (RuntimeException e) {
157157 // See ControlConnection#refreshSchema for why we'd rather not probably this further
158158 logger.error(String.format("Error parsing schema for table %s.%s: "
159- + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
160- keyspace.getName(), cfName, keyspace.getName(), cfName), e);
159+ + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
160+ keyspace.getName(), cfName, keyspace.getName(), cfName), e);
161161 }
162162 }
163163 }
@@ -169,11 +169,11 @@
169169 * This method also takes care of triggering the relevant events
170170 * as the updates take place.
171171 *
172- * @param oldKeyspaces the set of keyspaces to be updated.
173- * @param newKeyspaces the temporary set of keyspaces built with information gathered
174- * from schema tables.
172+ * @param oldKeyspaces the set of keyspaces to be updated.
173+ * @param newKeyspaces the temporary set of keyspaces built with information gathered
174+ * from schema tables.
175175 * @param keyspaceToRebuild If we are rebuilding just one keyspace, the update operation will be limited
176- * to this keyspace only (in which case {@code newKeyspaces} shoudl contain only one entry for it)
176+ * to this keyspace only (in which case {@code newKeyspaces} shoudl contain only one entry for it)
177177 */
178178 private void updateKeyspaces(Map<String, KeyspaceMetadata> oldKeyspaces, Map<String, KeyspaceMetadata> newKeyspaces, String keyspaceToRebuild) {
179179 Iterator<KeyspaceMetadata> it = oldKeyspaces.values().iterator();
@@ -205,11 +205,11 @@
205205 * This method also takes care of triggering the relevant events
206206 * as the updates take place.
207207 *
208- * @param oldTables the set of tables to be updated.
209- * @param newTables the temporary set of tables built with information gathered
210- * from schema tables.
208+ * @param oldTables the set of tables to be updated.
209+ * @param newTables the temporary set of tables built with information gathered
210+ * from schema tables.
211211 * @param tableToRebuild If we are rebuilding just one table, the update operation will be limited
212- * to this table only (in which case {@code newTables} shoudl contain only one entry for it)
212+ * to this table only (in which case {@code newTables} shoudl contain only one entry for it)
213213 */
214214 private void updateTables(Map<String, TableMetadata> oldTables, Map<String, TableMetadata> newTables, String tableToRebuild) {
215215 Iterator<TableMetadata> it = oldTables.values().iterator();
@@ -274,8 +274,8 @@
274274 return;
275275
276276 Token.Factory factory = partitioner == null
277- ? (tokenMap == null ? null : tokenMap.factory)
278- : Token.getFactory(partitioner);
277+ ? (tokenMap == null ? null : tokenMap.factory)
278+ : Token.getFactory(partitioner);
279279 if (factory == null)
280280 return;
281281
@@ -335,7 +335,7 @@
335335
336336 /**
337337 * Quote a keyspace, table or column identifier to make it case sensitive.
338- * <p>
338+ * <p/>
339339 * CQL identifiers, including keyspace, table and column ones, are case insensitive
340340 * by default. Case sensitive identifiers can however be provided by enclosing
341341 * the identifier in double quotes (see the
@@ -355,7 +355,7 @@
355355
356356 /**
357357 * Returns the token ranges that define data distribution in the ring.
358- * <p>
358+ * <p/>
359359 * Note that this information is refreshed asynchronously by the control
360360 * connection, when schema or ring topology changes. It might occasionally
361361 * be stale.
@@ -371,13 +371,13 @@
371371 /**
372372 * Returns the token ranges that are replicated on the given host, for the given
373373 * keyspace.
374- * <p>
374+ * <p/>
375375 * Note that this information is refreshed asynchronously by the control
376376 * connection, when schema or ring topology changes. It might occasionally
377377 * be stale (or even empty).
378378 *
379379 * @param keyspace the name of the keyspace to get token ranges for.
380- * @param host the host.
380+ * @param host the host.
381381 * @return the (immutable) set of token ranges for {@code host} as known
382382 * by the driver. Note that the result might be stale or empty if metadata
383383 * was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -400,14 +400,14 @@
400400
401401 /**
402402 * Returns the set of hosts that are replica for a given partition key.
403- * <p>
403+ * <p/>
404404 * Note that this information is refreshed asynchronously by the control
405405 * connection, when schema or ring topology changes. It might occasionally
406406 * be stale (or even empty).
407407 *
408- * @param keyspace the name of the keyspace to get replicas for.
408+ * @param keyspace the name of the keyspace to get replicas for.
409409 * @param partitionKey the partition key for which to find the set of
410- * replica.
410+ * replica.
411411 * @return the (immutable) set of replicas for {@code partitionKey} as known
412412 * by the driver. Note that the result might be stale or empty if metadata was
413413 * explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -425,13 +425,13 @@
425425
426426 /**
427427 * Returns the set of hosts that are replica for a given token range.
428- * <p>
428+ * <p/>
429429 * Note that this information is refreshed asynchronously by the control
430430 * connection, when schema or ring topology changes. It might occasionally
431431 * be stale (or even empty).
432432 *
433433 * @param keyspace the name of the keyspace to get replicas for.
434- * @param range the token range.
434+ * @param range the token range.
435435 * @return the (immutable) set of replicas for {@code range} as known by the driver.
436436 * Note that the result might be stale or empty if metadata was explicitly disabled
437437 * with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -476,7 +476,7 @@
476476
477477 /**
478478 * Checks whether hosts that are currently up agree on the schema definition.
479- * <p>
479+ * <p/>
480480 * This method performs a one-time check only, without any form of retry; therefore {@link Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int)}
481481 * does not apply in this case.
482482 *
@@ -496,7 +496,7 @@
496496 * Returns the metadata of a keyspace given its name.
497497 *
498498 * @param keyspace the name of the keyspace for which metadata should be
499- * returned.
499+ * returned.
500500 * @return the metadata of the requested keyspace or {@code null} if {@code
501501 * keyspace} is not a known keyspace. Note that the result might be stale or null if
502502 * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -533,13 +533,13 @@
533533 /**
534534 * Returns a {@code String} containing CQL queries representing the schema
535535 * of this cluster.
536- *
536+ * <p/>
537537 * In other words, this method returns the queries that would allow to
538538 * recreate the schema of this cluster.
539- *
539+ * <p/>
540540 * Note that the returned String is formatted to be human readable (for
541541 * some definition of human readable at least).
542- *
542+ * <p/>
543543 * It might be stale or empty if metadata was explicitly disabled with
544544 * {@link QueryOptions#setMetadataEnabled(boolean)}.
545545 *
@@ -561,10 +561,9 @@
561561 *
562562 * @param tokenStr the string representation.
563563 * @return the token.
564- *
565564 * @throws IllegalStateException if the token factory was not initialized. This would typically
566- * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
567- * before startup.
565+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
566+ * before startup.
568567 */
569568 public Token newToken(String tokenStr) {
570569 TokenMap current = tokenMap;
@@ -578,12 +577,11 @@
578577 * Builds a new {@link TokenRange}.
579578 *
580579 * @param start the start token.
581- * @param end the end token.
580+ * @param end the end token.
582581 * @return the range.
583- *
584582 * @throws IllegalStateException if the token factory was not initialized. This would typically
585- * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
586- * before startup.
583+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
584+ * before startup.
587585 */
588586 public TokenRange newTokenRange(Token start, Token end) {
589587 TokenMap current = tokenMap;
@@ -655,12 +653,11 @@
655653
656654 Map<String, Map<Token, Set<Host>>> tokenToHosts = new HashMap<String, Map<Token, Set<Host>>>();
657655 Map<String, Map<Host, Set<TokenRange>>> hostsToRanges = new HashMap<String, Map<Host, Set<TokenRange>>>();
658- for (KeyspaceMetadata keyspace : keyspaces)
659- {
656+ for (KeyspaceMetadata keyspace : keyspaces) {
660657 ReplicationStrategy strategy = keyspace.replicationStrategy();
661658 Map<Token, Set<Host>> ksTokens = (strategy == null)
662- ? makeNonReplicatedMap(tokenToPrimary)
663- : strategy.computeTokenToReplicaMap(tokenToPrimary, ring);
659+ ? makeNonReplicatedMap(tokenToPrimary)
660+ : strategy.computeTokenToReplicaMap(tokenToPrimary, ring);
664661
665662 tokenToHosts.put(keyspace.getName(), ksTokens);
666663
@@ -711,8 +708,8 @@
711708 private static Set<TokenRange> makeTokenRanges(List<Token> ring, Token.Factory factory) {
712709 ImmutableSet.Builder<TokenRange> builder = ImmutableSet.builder();
713710 // JAVA-684: if there is only one token, return the range ]minToken, minToken]
714- if(ring.size() == 1) {
715- builder.add(new TokenRange(factory.minToken(), factory.minToken(), factory));
711+ if (ring.size() == 1) {
712+ builder.add(new TokenRange(factory.minToken(), factory.minToken(), factory));
716713 } else {
717714 for (int i = 0; i < ring.size(); i++) {
718715 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 +11 −14
@@ -16,21 +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.InvalidQueryException;
25-import com.datastax.driver.core.exceptions.PagingStateException;
26-import com.datastax.driver.core.utils.Bytes;
27-
2827 /**
2928 * The paging state of a query.
30- *
29+ * <p/>
3130 * This object represents the next page to be fetched if the query is
3231 * multi page. It can be saved and reused later on the same statement.
33- *
32+ * <p/>
3433 * The PagingState can be serialized and deserialized either as a String
3534 * or as a byte array.
3635 *
@@ -53,7 +52,7 @@
5352 int hashSize = pagingStateBB.getShort();
5453 if (pagingSize + hashSize != pagingStateBB.remaining()) {
5554 throw new PagingStateException("Cannot deserialize paging state, invalid format. "
56- + "The serialized form was corrupted, or not initially generated from a PagingState object.");
55+ + "The serialized form was corrupted, or not initially generated from a PagingState object.");
5756 }
5857 this.pagingState = extractPagingState(complete);
5958 this.hash = extractHashDigest(complete);
@@ -67,12 +66,12 @@
6766 try {
6867 md = MessageDigest.getInstance("MD5");
6968 if (statement instanceof BoundStatement) {
70- BoundStatement bs = ((BoundStatement)statement);
69+ BoundStatement bs = ((BoundStatement) statement);
7170 md.update(bs.preparedStatement().getQueryString().getBytes());
7271 values = bs.values;
7372 } else {
7473 //it is a RegularStatement since Batch statements are not allowed
75- RegularStatement rs = (RegularStatement)statement;
74+ RegularStatement rs = (RegularStatement) statement;
7675 md.update(rs.getQueryString().getBytes());
7776 values = rs.getValues();
7877 }
@@ -118,8 +117,8 @@
118117 private ByteBuffer generateCompleteOutput() {
119118 ByteBuffer res = ByteBuffer.allocate(pagingState.length + hash.length + 4);
120119
121- res.putShort((short)pagingState.length);
122- res.putShort((short)hash.length);
120+ res.putShort((short) pagingState.length);
121+ res.putShort((short) hash.length);
123122
124123 res.put(pagingState);
125124 res.put(hash);
@@ -143,7 +142,6 @@
143142 *
144143 * @param string the string value.
145144 * @return the PagingState object created.
146- *
147145 * @throws PagingStateException if the string does not have the correct format.
148146 */
149147 public static PagingState fromString(String string) {
@@ -152,7 +150,7 @@
152150 return new PagingState(complete);
153151 } catch (Exception e) {
154152 throw new PagingStateException("Cannot deserialize paging state, invalid format. "
155- + "The serialized form was corrupted, or not initially generated from a PagingState object.", e);
153+ + "The serialized form was corrupted, or not initially generated from a PagingState object.", e);
156154 }
157155 }
158156
@@ -170,7 +168,6 @@
170168 *
171169 * @param pagingState The byte array representation.
172170 * @return the PagingState object created.
173- *
174171 * @throws PagingStateException if the byte array does not have the correct format.
175172 */
176173 public static PagingState fromBytes(byte[] pagingState) {
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 +43 −55
@@ -15,20 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.Executor;
19-
2018 import com.google.common.base.Preconditions;
2119 import com.google.common.util.concurrent.MoreExecutors;
2220
21+import java.util.concurrent.Executor;
22+
2323 /**
2424 * Options related to connection pooling.
25- * <p>
25+ * <p/>
2626 * The driver uses connections in an asynchronous manner. Meaning that
2727 * multiple requests can be submitted on the same connection at the same
2828 * time. This means that the driver only needs to maintain a relatively
2929 * small number of connections to each Cassandra host. These options allow
3030 * the driver to control how many connections are kept exactly.
31- * <p>
31+ * <p/>
3232 * For each host, the driver keeps a core pool of connections open at all
3333 * times determined by calling ({@link #getCoreConnectionsPerHost}).
3434 * If the use of those connections reaches a configurable threshold
@@ -37,7 +37,7 @@
3737 * connections ({@link #getMaxConnectionsPerHost}). When the pool exceeds
3838 * the maximum number of connections, connections in excess are
3939 * reclaimed.
40- * <p>
40+ * <p/>
4141 * Each of these parameters can be separately set for {@code LOCAL} and
4242 * {@code REMOTE} hosts ({@link HostDistance}). For {@code IGNORED} hosts,
4343 * the default for all those settings is 0 and cannot be changed.
@@ -62,10 +62,10 @@
6262
6363 private volatile Cluster.Manager manager;
6464
65- private final int[] maxSimultaneousRequests = new int[]{ DEFAULT_MAX_REQUESTS, DEFAULT_MAX_REQUESTS, 0 };
65+ private final int[] maxSimultaneousRequests = new int[]{DEFAULT_MAX_REQUESTS, DEFAULT_MAX_REQUESTS, 0};
6666
67- private final int[] coreConnections = new int[] { DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0 };
68- private final int[] maxConnections = new int[] { DEFAULT_MAX_POOL_LOCAL , DEFAULT_MAX_POOL_REMOTE, 0 };
67+ private final int[] coreConnections = new int[]{DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0};
68+ private final int[] maxConnections = new int[]{DEFAULT_MAX_POOL_LOCAL, DEFAULT_MAX_POOL_REMOTE, 0};
6969
7070 private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
7171 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
@@ -73,7 +73,8 @@
7373
7474 private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR;
7575
76- public PoolingOptions() {}
76+ public PoolingOptions() {
77+ }
7778
7879 void register(Cluster.Manager manager) {
7980 this.manager = manager;
@@ -82,18 +83,17 @@
8283 /**
8384 * Returns the number of simultaneous requests on a connection below which
8485 * connections in excess are reclaimed.
85- * <p>
86+ * <p/>
8687 * If an opened connection to an host at distance {@code distance}
8788 * handles less than this number of simultaneous requests and there is
8889 * more than {@link #getCoreConnectionsPerHost} connections open to this
8990 * host, the connection is closed.
90- * <p>
91+ * <p/>
9192 * The default value for this option is 25 for {@code LOCAL} and
9293 * {@code REMOTE} hosts.
9394 *
9495 * @param distance the {@code HostDistance} for which to return this threshold.
9596 * @return the configured threshold, or the default one if none have been set.
96- *
9797 * @deprecated this option isn't used anymore with the current pool resizing algorithm.
9898 */
9999 @Deprecated
@@ -105,13 +105,11 @@
105105 * Sets the number of simultaneous requests on a connection below which
106106 * connections in excess are reclaimed.
107107 *
108- * @param distance the {@code HostDistance} for which to configure this threshold.
108+ * @param distance the {@code HostDistance} for which to configure this threshold.
109109 * @param newMinSimultaneousRequests the value to set (between 0 and 128).
110110 * @return this {@code PoolingOptions}.
111- *
112111 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code minSimultaneousRequests}
113- * is not in range, or if {@code newMinSimultaneousRequests} is greater than the maximum value for this distance.
114- *
112+ * is not in range, or if {@code newMinSimultaneousRequests} is greater than the maximum value for this distance.
115113 * @deprecated this option isn't used anymore with the current pool resizing algorithm.
116114 */
117115 @Deprecated
@@ -122,16 +120,16 @@
122120 /**
123121 * Returns the number of simultaneous requests on all connections to an host after
124122 * which more connections are created.
125- * <p>
123+ * <p/>
126124 * If all the connections opened to an host at distance {@code
127125 * distance} connection are handling more than this number of
128126 * simultaneous requests and there is less than
129127 * {@link #getMaxConnectionsPerHost} connections open to this host, a
130128 * new connection is open.
131- * <p>
129+ * <p/>
132130 * Note that a given connection cannot handle more than 128
133131 * simultaneous requests (protocol limitation).
134- * <p>
132+ * <p/>
135133 * The default value for this option is 100 for {@code LOCAL} and
136134 * {@code REMOTE} hosts.
137135 *
@@ -146,12 +144,11 @@
146144 * Sets number of simultaneous requests on all connections to an host after
147145 * which more connections are created.
148146 *
149- * @param distance the {@code HostDistance} for which to configure this threshold.
147+ * @param distance the {@code HostDistance} for which to configure this threshold.
150148 * @param newMaxSimultaneousRequests the value to set (between 0 and 128).
151149 * @return this {@code PoolingOptions}.
152- *
153150 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code maxSimultaneousRequests}
154- * is not in range, or if {@code newMaxSimultaneousRequests} is less than the minimum value for this distance.
151+ * is not in range, or if {@code newMaxSimultaneousRequests} is less than the minimum value for this distance.
155152 */
156153 public synchronized PoolingOptions setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance distance, int newMaxSimultaneousRequests) {
157154 if (distance == HostDistance.IGNORED)
@@ -164,7 +161,7 @@
164161
165162 /**
166163 * Returns the core number of connections per host.
167- * <p>
164+ * <p/>
168165 * For the provided {@code distance}, this correspond to the number of
169166 * connections initially created and kept open to each host of that
170167 * distance.
@@ -179,18 +176,16 @@
179176 /**
180177 * Sets the core number of connections per host.
181178 *
182- * @param distance the {@code HostDistance} for which to set this threshold.
179+ * @param distance the {@code HostDistance} for which to set this threshold.
183180 * @param newCoreConnections the value to set
184181 * @return this {@code PoolingOptions}.
185- *
186182 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
187- * or if {@code newCoreConnections} is greater than the maximum value for this distance.
188- *
183+ * or if {@code newCoreConnections} is greater than the maximum value for this distance.
189184 * @see #setConnectionsPerHost(HostDistance, int, int)
190185 */
191186 public synchronized PoolingOptions setCoreConnectionsPerHost(HostDistance distance, int newCoreConnections) {
192187 if (distance == HostDistance.IGNORED)
193- throw new IllegalArgumentException("Cannot set core connections per host for " + distance + " hosts");
188+ throw new IllegalArgumentException("Cannot set core connections per host for " + distance + " hosts");
194189
195190 checkConnectionsPerHostOrder(newCoreConnections, maxConnections[distance.ordinal()], distance);
196191 int oldCore = coreConnections[distance.ordinal()];
@@ -202,7 +197,7 @@
202197
203198 /**
204199 * Returns the maximum number of connections per host.
205- * <p>
200+ * <p/>
206201 * For the provided {@code distance}, this correspond to the maximum
207202 * number of connections that can be created per host at that distance.
208203 *
@@ -216,13 +211,11 @@
216211 /**
217212 * Sets the maximum number of connections per host.
218213 *
219- * @param distance the {@code HostDistance} for which to set this threshold.
214+ * @param distance the {@code HostDistance} for which to set this threshold.
220215 * @param newMaxConnections the value to set
221216 * @return this {@code PoolingOptions}.
222- *
223217 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
224- * or if {@code newMaxConnections} is less than the core value for this distance.
225- *
218+ * or if {@code newMaxConnections} is less than the core value for this distance.
226219 * @see #setConnectionsPerHost(HostDistance, int, int)
227220 */
228221 public synchronized PoolingOptions setMaxConnectionsPerHost(HostDistance distance, int newMaxConnections) {
@@ -236,17 +229,16 @@
236229
237230 /**
238231 * Sets the core and maximum number of connections per host in one call.
239- * <p>
232+ * <p/>
240233 * This is a convenience method that is equivalent to calling {@link #setCoreConnectionsPerHost(HostDistance, int)}
241234 * and {@link #setMaxConnectionsPerHost(HostDistance, int)}.
242235 *
243236 * @param distance the {@code HostDistance} for which to set these threshold.
244- * @param core the core number of connections.
245- * @param max the max number of connections.
237+ * @param core the core number of connections.
238+ * @param max the max number of connections.
246239 * @return this {@code PoolingOptions}.
247- *
248240 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
249- * or if {@code core} > {@code max}.
241+ * or if {@code core} > {@code max}.
250242 */
251243 public synchronized PoolingOptions setConnectionsPerHost(HostDistance distance, int core, int max) {
252244 if (distance == HostDistance.IGNORED)
@@ -269,13 +261,12 @@
269261
270262 /**
271263 * Sets the timeout before an idle connection is removed.
272- * <p>
264+ * <p/>
273265 * The order of magnitude should be a few minutes (the default is 120 seconds). The
274266 * timeout that triggers the removal has a granularity of 10 seconds.
275267 *
276268 * @param idleTimeoutSeconds the new timeout in seconds.
277269 * @return this {@code PoolingOptions}.
278- *
279270 * @throws IllegalArgumentException if the timeout is negative.
280271 */
281272 public PoolingOptions setIdleTimeoutSeconds(int idleTimeoutSeconds) {
@@ -296,15 +287,14 @@
296287
297288 /**
298289 * Sets the timeout when trying to acquire a connection from a host's pool.
299- * <p>
290+ * <p/>
300291 * If no connection is available within that time, the driver will try the
301292 * next host from the query plan.
302- * <p>
293+ * <p/>
303294 * If this option is set to zero, the driver won't wait at all.
304295 *
305296 * @param poolTimeoutMillis the new value in milliseconds.
306297 * @return this {@code PoolingOptions}
307- *
308298 * @throws IllegalArgumentException if the timeout is negative.
309299 */
310300 public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) {
@@ -316,6 +306,7 @@
316306
317307 /**
318308 * Returns the heart beat interval, after which a message is sent on an idle connection to make sure it's still alive.
309+ *
319310 * @return the interval.
320311 */
321312 public int getHeartbeatIntervalSeconds() {
@@ -324,17 +315,16 @@
324315
325316 /**
326317 * Sets the heart beat interval, after which a message is sent on an idle connection to make sure it's still alive.
327- * <p>
318+ * <p/>
328319 * This is an application-level keep-alive, provided for convenience since adjusting the TCP keep-alive might not be
329320 * practical in all environments.
330- * <p>
321+ * <p/>
331322 * This option should be set higher than {@link SocketOptions#getReadTimeoutMillis()}.
332- * <p>
323+ * <p/>
333324 * The default value for this option is 30 seconds.
334325 *
335326 * @param heartbeatIntervalSeconds the new value in seconds. If set to 0, it will disable the feature.
336327 * @return this {@code PoolingOptions}
337- *
338328 * @throws IllegalArgumentException if the interval is negative.
339329 */
340330 public PoolingOptions setHeartbeatIntervalSeconds(int heartbeatIntervalSeconds) {
@@ -357,11 +347,11 @@
357347
358348 /**
359349 * Sets the executor to use for connection initialization.
360- * <p>
350+ * <p/>
361351 * Connections are open in a completely asynchronous manner. Since initializing the transport
362352 * requires separate CQL queries, the futures representing the completion of these queries are
363353 * transformed and chained. This executor is where these transformations happen.
364- * <p>
354+ * <p/>
365355 * <b>This is an advanced option, which should be rarely needed in practice.</b> It defaults to
366356 * Guava's {@code MoreExecutors.sameThreadExecutor()}, which results in running the transformations
367357 * on the network I/O threads; this is fine if the transformations are fast and not I/O bound
@@ -372,7 +362,6 @@
372362 *
373363 * @param initializationExecutor the executor to use
374364 * @return this {@code PoolingOptions}
375- *
376365 * @throws java.lang.NullPointerException if the executor is null
377366 */
378367 public PoolingOptions setInitializationExecutor(Executor initializationExecutor) {
@@ -385,7 +374,7 @@
385374 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
386375 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
387376 * hosts and to drop/add connections to each hosts according to the computed distance.
388- * <p>
377+ * <p/>
389378 * Note that, due to backward compatibility issues, this method is not interruptible. If the
390379 * caller thread gets interrupted, the method will complete and only then re-interrupt the
391380 * thread (which you can check with {@code Thread.currentThread().isInterrupted()}).
@@ -398,7 +387,6 @@
398387 * Requests the driver to re-evaluate the {@link HostDistance} for a given node.
399388 *
400389 * @param host the host to refresh.
401- *
402390 * @see #refreshConnectedHosts()
403391 */
404392 public void refreshConnectedHost(Host host) {
@@ -408,13 +396,13 @@
408396 private static void checkRequestsPerConnectionRange(int value, String description, HostDistance distance) {
409397 if (value < 0 || value > StreamIdGenerator.MAX_STREAM_PER_CONNECTION)
410398 throw new IllegalArgumentException(String.format("%s for %s hosts must be in the range (0, %d)",
411- description, distance,
412- StreamIdGenerator.MAX_STREAM_PER_CONNECTION));
399+ description, distance,
400+ StreamIdGenerator.MAX_STREAM_PER_CONNECTION));
413401 }
414402
415403 private static void checkConnectionsPerHostOrder(int core, int max, HostDistance distance) {
416404 if (core > max)
417405 throw new IllegalArgumentException(String.format("Core connections for %s hosts must be less than max (%d > %d)",
418- distance, core, max));
406+ distance, core, max));
419407 }
420408 }
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;
@@ -29,8 +28,7 @@
2928
3029 final int[] routingKeyIndexes;
3130
32- PreparedId(MD5Digest id, ColumnDefinitions metadata, ColumnDefinitions resultSetMetadata, int[] routingKeyIndexes)
33- {
31+ PreparedId(MD5Digest id, ColumnDefinitions metadata, ColumnDefinitions resultSetMetadata, int[] routingKeyIndexes) {
3432 this.id = id;
3533 this.metadata = metadata;
3634 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,13 +15,13 @@
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 class ProtocolEvent {
2323
24- public enum Type { TOPOLOGY_CHANGE, STATUS_CHANGE, SCHEMA_CHANGE }
24+ public enum Type {TOPOLOGY_CHANGE, STATUS_CHANGE, SCHEMA_CHANGE}
2525
2626 public final Type type;
2727
@@ -42,7 +42,7 @@
4242 }
4343
4444 public static class TopologyChange extends ProtocolEvent {
45- public enum Change { NEW_NODE, REMOVED_NODE, MOVED_NODE }
45+ public enum Change {NEW_NODE, REMOVED_NODE, MOVED_NODE}
4646
4747 public final Change change;
4848 public final InetSocketAddress node;
@@ -68,7 +68,7 @@
6868
6969 public static class StatusChange extends ProtocolEvent {
7070
71- public enum Status { UP, DOWN }
71+ public enum Status {UP, DOWN}
7272
7373 public final Status status;
7474 public final InetSocketAddress node;
@@ -94,7 +94,7 @@
9494
9595 public static class SchemaChange extends ProtocolEvent {
9696
97- public enum Change { CREATED, UPDATED, DROPPED }
97+ public enum Change {CREATED, UPDATED, DROPPED}
9898
9999 public final Change change;
100100 public final String keyspace;
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java +27 −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.
@@ -104,7 +112,7 @@
104112 /**
105113 * Creates a new {@code ProtocolOptions} instance using the provided port
106114 * (without SSL nor authentication).
107- * <p>
115+ * <p/>
108116 * This is a shortcut for {@code new ProtocolOptions(port, null, AuthProvider.NONE)}.
109117 *
110118 * @param port the port to use for the binary protocol.
@@ -117,15 +125,15 @@
117125 * Creates a new {@code ProtocolOptions} instance using the provided port
118126 * and SSL context.
119127 *
120- * @param port the port to use for the binary protocol.
128+ * @param port the port to use for the binary protocol.
121129 * @param protocolVersion the protocol version to use. This can be a negative number, in which case the
122- * version uses will be the biggest version supported by the <em>first</em> node the driver connects to.
123- * Otherwise, it must be either 1 or 2 to force using a particular protocol version. See
124- * {@link Cluster.Builder#withProtocolVersion} for more details.
125- * @param sslOptions the SSL options to use. Use {@code null} if SSL is not
126- * to be used.
127- * @param authProvider the {@code AuthProvider} to use for authentication against
128- * the Cassandra nodes.
130+ * version uses will be the biggest version supported by the <em>first</em> node the driver connects to.
131+ * Otherwise, it must be either 1 or 2 to force using a particular protocol version. See
132+ * {@link Cluster.Builder#withProtocolVersion} for more details.
133+ * @param sslOptions the SSL options to use. Use {@code null} if SSL is not
134+ * to be used.
135+ * @param authProvider the {@code AuthProvider} to use for authentication against
136+ * the Cassandra nodes.
129137 */
130138 public ProtocolOptions(int port, int protocolVersion, int maxSchemaAgreementWaitSeconds, SSLOptions sslOptions, AuthProvider authProvider) {
131139 this.port = port;
@@ -166,7 +174,7 @@
166174
167175 /**
168176 * Returns the compression used by the protocol.
169- * <p>
177+ * <p/>
170178 * By default, compression is not used.
171179 *
172180 * @return the compression used.
@@ -177,18 +185,17 @@
177185
178186 /**
179187 * Sets the compression to use.
180- * <p>
188+ * <p/>
181189 * Note that while this setting can be changed at any time, it will
182190 * only apply to newly created connections.
183191 *
184192 * @param compression the compression algorithm to use (or {@code
185- * Compression.NONE} to disable compression).
193+ * Compression.NONE} to disable compression).
186194 * @return this {@code ProtocolOptions} object.
187- *
188195 * @throws IllegalStateException if the compression requested is not
189- * available. Most compression algorithms require that the relevant be
190- * present in the classpath. If not, the compression will be
191- * unavailable.
196+ * available. Most compression algorithms require that the relevant be
197+ * present in the classpath. If not, the compression will be
198+ * unavailable.
192199 */
193200 public ProtocolOptions setCompression(Compression compression) {
194201 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/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");
@@ -215,7 +215,7 @@
215215
216216 /**
217217 * Creates a new {@link QueryLogger.Builder} instance.
218- * <p>
218+ * <p/>
219219 * This is a convenience method for {@code new QueryLogger.Builder()}.
220220 *
221221 * @param cluster the {@link Cluster} this QueryLogger will be attached to.
@@ -223,7 +223,7 @@
223223 * @throws NullPointerException if {@code cluster} is {@code null}.
224224 */
225225 public static QueryLogger.Builder builder(Cluster cluster) {
226- if(cluster == null) throw new NullPointerException("QueryLogger.Builder: cluster parameter cannot be null");
226+ if (cluster == null) throw new NullPointerException("QueryLogger.Builder: cluster parameter cannot be null");
227227 return new QueryLogger.Builder(cluster);
228228 }
229229
@@ -288,10 +288,10 @@
288288 /**
289289 * A QueryLogger that uses a dynamic threshold in milliseconds
290290 * to track slow queries.
291- * <p>
291+ * <p/>
292292 * Dynamic thresholds are based on per-host latency percentiles, as computed
293293 * by {@link PerHostPercentileTracker}.
294- * <p>
294+ * <p/>
295295 * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
296296 * to change.</b>
297297 */
@@ -348,7 +348,7 @@
348348 * and logged as such by the driver.
349349 *
350350 * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
351- * It must be comprised between 0 inclusive and 100 exclusive.
351+ * It must be comprised between 0 inclusive and 100 exclusive.
352352 * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdPercentile < 0 || slowQueryLatencyThresholdPercentile >= 100}.
353353 */
354354 public void setSlowQueryLatencyThresholdPercentile(double slowQueryLatencyThresholdPercentile) {
@@ -402,7 +402,7 @@
402402
403403 /**
404404 * Enables slow query latency tracking based on constant thresholds.
405- * <p>
405+ * <p/>
406406 * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
407407 * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
408408 * not both.
@@ -420,22 +420,22 @@
420420
421421 /**
422422 * Enables slow query latency tracking based on dynamic thresholds.
423- * <p>
423+ * <p/>
424424 * Dynamic thresholds are based on per-host latency percentiles, as computed
425425 * by {@link PerHostPercentileTracker}.
426- * <p>
426+ * <p/>
427427 * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
428428 * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
429429 * not both.
430- * <p>
430+ * <p/>
431431 * <b>This feature is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
432432 * to change.</b>
433433 *
434- * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
435- * Cannot be {@code null}.
434+ * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
435+ * Cannot be {@code null}.
436436 * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
437- * It must be comprised between 0 inclusive and 100 exclusive.
438- * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}
437+ * It must be comprised between 0 inclusive and 100 exclusive.
438+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}
439439 * @return this {@link Builder} instance (for method chaining).
440440 */
441441 @Beta
@@ -501,11 +501,12 @@
501501
502502 /**
503503 * Build the {@link QueryLogger} instance.
504+ *
504505 * @return the {@link QueryLogger} instance.
505506 * @throws IllegalArgumentException if the builder is unable to build a valid instance due to incorrect settings.
506507 */
507508 public QueryLogger build() {
508- if(constantThreshold) {
509+ if (constantThreshold) {
509510 return new ConstantThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdMillis);
510511 } else {
511512 return new DynamicThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdPercentile, perHostPercentileLatencyTracker);
@@ -642,13 +643,13 @@
642643 if (showParameterValues) {
643644 StringBuilder params = new StringBuilder();
644645 if (statement instanceof BoundStatement) {
645- appendParameters((BoundStatement)statement, params, maxLoggedParameters);
646+ appendParameters((BoundStatement) statement, params, maxLoggedParameters);
646647 } else if (statement instanceof BatchStatement) {
647- BatchStatement batchStatement = (BatchStatement)statement;
648+ BatchStatement batchStatement = (BatchStatement) statement;
648649 int remaining = maxLoggedParameters;
649650 for (Statement inner : batchStatement.getStatements()) {
650651 if (inner instanceof BoundStatement) {
651- remaining = appendParameters((BoundStatement)inner, params, remaining);
652+ remaining = appendParameters((BoundStatement) inner, params, remaining);
652653 }
653654 }
654655 }
@@ -663,12 +664,12 @@
663664 protected String statementAsString(Statement statement) {
664665 StringBuilder sb = new StringBuilder();
665666 if (statement instanceof BatchStatement) {
666- BatchStatement bs = (BatchStatement)statement;
667+ BatchStatement bs = (BatchStatement) statement;
667668 int statements = bs.getStatements().size();
668669 int boundValues = countBoundValues(bs);
669670 sb.append("[" + statements + " statements, " + boundValues + " bound values] ");
670671 } else if (statement instanceof BoundStatement) {
671- int boundValues = ((BoundStatement)statement).values.length;
672+ int boundValues = ((BoundStatement) statement).values.length;
672673 sb.append("[" + boundValues + " bound values] ");
673674 }
674675
@@ -680,7 +681,7 @@
680681 int count = 0;
681682 for (Statement s : bs.getStatements()) {
682683 if (s instanceof BoundStatement)
683- count += ((BoundStatement)s).values.length;
684+ count += ((BoundStatement) s).values.length;
684685 }
685686 return count;
686687 }
@@ -725,7 +726,7 @@
725726 int maxBufferLength = Math.max(2, (maxParameterValueLength - 2) / 2);
726727 boolean bufferTooLarge = raw.remaining() > maxBufferLength;
727728 if (bufferTooLarge) {
728- raw = (ByteBuffer)raw.duplicate().limit(maxBufferLength);
729+ raw = (ByteBuffer) raw.duplicate().limit(maxBufferLength);
729730 }
730731 Object value = type.deserialize(raw);
731732 valueStr = type.format(value);
@@ -745,14 +746,14 @@
745746
746747 protected int append(Statement statement, StringBuilder buffer, int remaining) {
747748 if (statement instanceof StatementWrapper)
748- statement = ((StatementWrapper)statement).getWrappedStatement();
749+ statement = ((StatementWrapper) statement).getWrappedStatement();
749750
750751 if (statement instanceof RegularStatement) {
751- remaining = append(((RegularStatement)statement).getQueryString().trim(), buffer, remaining);
752+ remaining = append(((RegularStatement) statement).getQueryString().trim(), buffer, remaining);
752753 } else if (statement instanceof BoundStatement) {
753- remaining = append(((BoundStatement)statement).preparedStatement().getQueryString().trim(), buffer, remaining);
754+ remaining = append(((BoundStatement) statement).preparedStatement().getQueryString().trim(), buffer, remaining);
754755 } else if (statement instanceof BatchStatement) {
755- BatchStatement batchStatement = (BatchStatement)statement;
756+ BatchStatement batchStatement = (BatchStatement) statement;
756757 remaining = append("BEGIN", buffer, remaining);
757758 switch (batchStatement.batchType) {
758759 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 +4 −4
@@ -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
@@ -51,7 +52,6 @@
5152 *
5253 * @return the values to use for this statement or {@code null} if there is
5354 * no such values.
54- *
5555 * @see SimpleStatement#SimpleStatement(String, Object...)
5656 */
5757 public abstract ByteBuffer[] getValues();
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(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 datacenter {}: "
193- + "could not achieve replication factor {} (found {} replicas only), "
194- + "check your keyspace replication settings.",
195- dcName, expectedFactor, achievedFactor);
192+ + "could not achieve replication factor {} (found {} replicas only), "
193+ + "check your keyspace replication settings.",
194+ 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 +44 −40
@@ -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";
@@ -86,9 +87,9 @@
8687
8788 public static class Options extends Message.Request {
8889
89- public static final Message.Coder<Options> coder = new Message.Coder<Options>()
90- {
91- public void encode(Options msg, ByteBuf dest) {}
90+ public static final Message.Coder<Options> coder = new Message.Coder<Options>() {
91+ public void encode(Options msg, ByteBuf dest) {
92+ }
9293
9394 public int encodedSize(Options msg) {
9495 return 0;
@@ -115,7 +116,7 @@
115116
116117 public int encodedSize(Query msg) {
117118 return CBUtil.sizeOfLongString(msg.query)
118- + CBUtil.sizeOfConsistencyLevel(msg.options.consistency);
119+ + CBUtil.sizeOfConsistencyLevel(msg.options.consistency);
119120 }
120121 };
121122
@@ -127,7 +128,7 @@
127128
128129 public int encodedSize(Query msg) {
129130 return CBUtil.sizeOfLongString(msg.query)
130- + msg.options.encodedSize();
131+ + msg.options.encodedSize();
131132 }
132133 };
133134
@@ -171,8 +172,8 @@
171172
172173 public int encodedSize(Execute msg) {
173174 return CBUtil.sizeOfBytes(msg.statementId.bytes)
174- + CBUtil.sizeOfValueList(msg.options.values)
175- + CBUtil.sizeOfConsistencyLevel(msg.options.consistency);
175+ + CBUtil.sizeOfValueList(msg.options.values)
176+ + CBUtil.sizeOfConsistencyLevel(msg.options.consistency);
176177 }
177178 };
178179
@@ -184,7 +185,7 @@
184185
185186 public int encodedSize(Execute msg) {
186187 return CBUtil.sizeOfBytes(msg.statementId.bytes)
187- + msg.options.encodedSize();
188+ + msg.options.encodedSize();
188189 }
189190 };
190191
@@ -226,8 +227,7 @@
226227 public static EnumSet<Flag> deserialize(int flags) {
227228 EnumSet<Flag> set = EnumSet.noneOf(Flag.class);
228229 Flag[] values = Flag.values();
229- for (int n = 0; n < values.length; n++)
230- {
230+ for (int n = 0; n < values.length; n++) {
231231 if ((flags & (1 << n)) != 0)
232232 set.add(values[n]);
233233 }
@@ -243,11 +243,11 @@
243243 }
244244
245245 public static final QueryProtocolOptions DEFAULT = new QueryProtocolOptions(ConsistencyLevel.ONE,
246- Collections.<ByteBuffer>emptyList(),
247- false,
248- -1,
249- null,
250- ConsistencyLevel.SERIAL);
246+ Collections.<ByteBuffer>emptyList(),
247+ false,
248+ -1,
249+ null,
250+ ConsistencyLevel.SERIAL);
251251
252252 private final EnumSet<Flag> flags = EnumSet.noneOf(Flag.class);
253253 public final ConsistencyLevel consistency;
@@ -291,7 +291,7 @@
291291 public void encode(ByteBuf dest) {
292292 CBUtil.writeConsistencyLevel(consistency, dest);
293293
294- dest.writeByte((byte)Flag.serialize(flags));
294+ dest.writeByte((byte) Flag.serialize(flags));
295295
296296 if (flags.contains(Flag.VALUES))
297297 CBUtil.writeValueList(values, dest);
@@ -304,17 +304,17 @@
304304 }
305305
306306 public int encodedSize() {
307- int size = CBUtil.sizeOfConsistencyLevel(consistency) + 1;
308-
309- if (flags.contains(Flag.VALUES))
310- size += CBUtil.sizeOfValueList(values);
311- if (flags.contains(Flag.PAGE_SIZE))
312- size += 4;
313- if (flags.contains(Flag.PAGING_STATE))
314- size += CBUtil.sizeOfValue(pagingState);
315- if (flags.contains(Flag.SERIAL_CONSISTENCY))
316- size += CBUtil.sizeOfConsistencyLevel(serialConsistency);
317- return size;
307+ int size = CBUtil.sizeOfConsistencyLevel(consistency) + 1;
308+
309+ if (flags.contains(Flag.VALUES))
310+ size += CBUtil.sizeOfValueList(values);
311+ if (flags.contains(Flag.PAGE_SIZE))
312+ size += 4;
313+ if (flags.contains(Flag.PAGING_STATE))
314+ size += CBUtil.sizeOfValue(pagingState);
315+ if (flags.contains(Flag.SERIAL_CONSISTENCY))
316+ size += CBUtil.sizeOfConsistencyLevel(serialConsistency);
317+ return size;
318318 }
319319
320320 @Override
@@ -335,11 +335,11 @@
335335
336336 for (int i = 0; i < queries; i++) {
337337 Object q = msg.queryOrIdList.get(i);
338- dest.writeByte((byte)(q instanceof String ? 0 : 1));
338+ dest.writeByte((byte) (q instanceof String ? 0 : 1));
339339 if (q instanceof String)
340- CBUtil.writeLongString((String)q, dest);
340+ CBUtil.writeLongString((String) q, dest);
341341 else
342- CBUtil.writeBytes(((MD5Digest)q).bytes, dest);
342+ CBUtil.writeBytes(((MD5Digest) q).bytes, dest);
343343
344344 CBUtil.writeValueList(msg.values.get(i), dest);
345345 }
@@ -352,8 +352,8 @@
352352 for (int i = 0; i < msg.queryOrIdList.size(); i++) {
353353 Object q = msg.queryOrIdList.get(i);
354354 size += 1 + (q instanceof String
355- ? CBUtil.sizeOfLongString((String)q)
356- : CBUtil.sizeOfBytes(((MD5Digest)q).bytes));
355+ ? CBUtil.sizeOfLongString((String) q)
356+ : CBUtil.sizeOfBytes(((MD5Digest) q).bytes));
357357
358358 size += CBUtil.sizeOfValueList(msg.values.get(i));
359359 }
@@ -363,10 +363,14 @@
363363
364364 private byte fromType(BatchStatement.Type type) {
365365 switch (type) {
366- case LOGGED: return 0;
367- case UNLOGGED: return 1;
368- case COUNTER: return 2;
369- default: throw new AssertionError();
366+ case LOGGED:
367+ return 0;
368+ case UNLOGGED:
369+ return 1;
370+ case COUNTER:
371+ return 2;
372+ default:
373+ throw new AssertionError();
370374 }
371375 }
372376 };
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +46 −31
@@ -15,18 +15,18 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.*;
19+import com.datastax.driver.core.utils.Bytes;
20+import io.netty.buffer.ByteBuf;
21+
1822 import java.net.InetSocketAddress;
1923 import java.nio.ByteBuffer;
2024 import java.util.*;
2125
22-import io.netty.buffer.ByteBuf;
23-
24-import com.datastax.driver.core.exceptions.*;
25-import com.datastax.driver.core.utils.Bytes;
26-
2726 class Responses {
2827
29- private Responses() {}
28+ private Responses() {
29+ }
3030
3131 public static class Error extends Message.Response {
3232
@@ -82,22 +82,38 @@
8282
8383 public DriverException asException(InetSocketAddress host) {
8484 switch (code) {
85- case SERVER_ERROR: return new ServerError(host, message);
86- case PROTOCOL_ERROR: return new ProtocolError(host, message);
87- case BAD_CREDENTIALS: return new AuthenticationException(host, message);
88- case UNAVAILABLE: return ((UnavailableException)infos).copy(host); // We copy to have a nice stack trace
89- case OVERLOADED: return new OverloadedException(host, message);
90- case IS_BOOTSTRAPPING: return new BootstrappingException(host, message);
91- case TRUNCATE_ERROR: return new TruncateException(host, message);
92- case WRITE_TIMEOUT: return ((WriteTimeoutException)infos).copy(host);
93- case READ_TIMEOUT: return ((ReadTimeoutException)infos).copy(host);
94- case SYNTAX_ERROR: return new SyntaxError(host, message);
95- case UNAUTHORIZED: return new UnauthorizedException(host, message);
96- case INVALID: return new InvalidQueryException(host, message);
97- case CONFIG_ERROR: return new InvalidConfigurationInQueryException(host, message);
98- case ALREADY_EXISTS: return ((AlreadyExistsException)infos).copy(host);
99- case UNPREPARED: return new UnpreparedException(host, message);
100- default: return new DriverInternalError(String.format("Unknown protocol error code %s returned by %s. The error message was: %s", code, host, message));
85+ case SERVER_ERROR:
86+ return new ServerError(host, message);
87+ case PROTOCOL_ERROR:
88+ return new ProtocolError(host, message);
89+ case BAD_CREDENTIALS:
90+ return new AuthenticationException(host, message);
91+ case UNAVAILABLE:
92+ return ((UnavailableException) infos).copy(host); // We copy to have a nice stack trace
93+ case OVERLOADED:
94+ return new OverloadedException(host, message);
95+ case IS_BOOTSTRAPPING:
96+ return new BootstrappingException(host, message);
97+ case TRUNCATE_ERROR:
98+ return new TruncateException(host, message);
99+ case WRITE_TIMEOUT:
100+ return ((WriteTimeoutException) infos).copy(host);
101+ case READ_TIMEOUT:
102+ return ((ReadTimeoutException) infos).copy(host);
103+ case SYNTAX_ERROR:
104+ return new SyntaxError(host, message);
105+ case UNAUTHORIZED:
106+ return new UnauthorizedException(host, message);
107+ case INVALID:
108+ return new InvalidQueryException(host, message);
109+ case CONFIG_ERROR:
110+ return new InvalidConfigurationInQueryException(host, message);
111+ case ALREADY_EXISTS:
112+ return ((AlreadyExistsException) infos).copy(host);
113+ case UNPREPARED:
114+ return new UnpreparedException(host, message);
115+ default:
116+ return new DriverInternalError(String.format("Unknown protocol error code %s returned by %s. The error message was: %s", code, host, message));
101117 }
102118 }
103119
@@ -202,10 +218,10 @@
202218 };
203219
204220 public enum Kind {
205- VOID (1, Void.subcodec, Void.subcodec),
206- ROWS (2, Rows.subcodec, Rows.subcodec),
207- SET_KEYSPACE (3, SetKeyspace.subcodec, SetKeyspace.subcodec),
208- PREPARED (4, Prepared.subcodecV1, Prepared.subcodecV2),
221+ VOID(1, Void.subcodec, Void.subcodec),
222+ ROWS(2, Rows.subcodec, Rows.subcodec),
223+ SET_KEYSPACE(3, SetKeyspace.subcodec, SetKeyspace.subcodec),
224+ PREPARED(4, Prepared.subcodecV1, Prepared.subcodecV2),
209225 SCHEMA_CHANGE(5, SchemaChange.subcodec, SchemaChange.subcodec);
210226
211227 private final int id;
@@ -213,6 +229,7 @@
213229 private final Message.Decoder<Result> subDecoderV2;
214230
215231 private static final Kind[] ids;
232+
216233 static {
217234 int maxId = -1;
218235 for (Kind k : Kind.values())
@@ -289,8 +306,7 @@
289306
290307 public static class Metadata {
291308
292- private static enum Flag
293- {
309+ private static enum Flag {
294310 // The order of that enum matters!!
295311 GLOBAL_TABLES_SPEC,
296312 HAS_MORE_PAGES,
@@ -470,15 +486,14 @@
470486
471487 public static class SchemaChange extends Result {
472488
473- public enum Change { CREATED, UPDATED, DROPPED }
489+ public enum Change {CREATED, UPDATED, DROPPED}
474490
475491 public final Change change;
476492 public final String keyspace;
477493 public final String columnFamily;
478494
479495 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
480- public Result decode(ByteBuf body)
481- {
496+ public Result decode(ByteBuf body) {
482497 Change change = CBUtil.readEnumValue(Change.class, body);
483498 String keyspace = CBUtil.readString(body);
484499 String columnFamily = CBUtil.readString(body);
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}.
@@ -44,7 +44,6 @@
4444 *
4545 * @param i the index ({@code 0 <= i < size()}) of the column to check.
4646 * @return whether the {@code i}th value of this row is NULL.
47- *
4847 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
4948 */
5049 @Override
@@ -55,9 +54,8 @@
5554 *
5655 * @param name the name of the column to check.
5756 * @return whether the value of column {@code name} is NULL.
58- *
5957 * @throws IllegalArgumentException if {@code name} is not part of the
60- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
58+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
6159 */
6260 @Override
6361 public boolean isNull(String name);
@@ -68,9 +66,8 @@
6866 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
6967 * @return the boolean value of the {@code i}th column in this row. If the
7068 * value is NULL, {@code false} is returned.
71- *
7269 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
73- * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
70+ * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
7471 */
7572 @Override
7673 public boolean getBool(int i);
@@ -81,10 +78,9 @@
8178 * @param name the name of the column to retrieve.
8279 * @return the boolean value of column {@code name}. If the value is NULL,
8380 * {@code false} is returned.
84- *
8581 * @throws IllegalArgumentException if {@code name} is not part of the
86- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
87- * @throws InvalidTypeException if column {@code name} is not of type BOOLEAN.
82+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
83+ * @throws InvalidTypeException if column {@code name} is not of type BOOLEAN.
8884 */
8985 @Override
9086 public boolean getBool(String name);
@@ -95,9 +91,8 @@
9591 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
9692 * @return the value of the {@code i}th column in this row as an integer. If the
9793 * value is NULL, {@code 0} is returned.
98- *
9994 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
100- * @throws InvalidTypeException if column {@code i} is not of type INT.
95+ * @throws InvalidTypeException if column {@code i} is not of type INT.
10196 */
10297 @Override
10398 public int getInt(int i);
@@ -108,10 +103,9 @@
108103 * @param name the name of the column to retrieve.
109104 * @return the value of column {@code name} as an integer. If the value is NULL,
110105 * {@code 0} is returned.
111- *
112106 * @throws IllegalArgumentException if {@code name} is not part of the
113- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
114- * @throws InvalidTypeException if column {@code name} is not of type INT.
107+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
108+ * @throws InvalidTypeException if column {@code name} is not of type INT.
115109 */
116110 @Override
117111 public int getInt(String name);
@@ -122,9 +116,8 @@
122116 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
123117 * @return the value of the {@code i}th column in this row as a long. If the
124118 * value is NULL, {@code 0L} is returned.
125- *
126119 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
127- * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
120+ * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
128121 */
129122 @Override
130123 public long getLong(int i);
@@ -135,10 +128,9 @@
135128 * @param name the name of the column to retrieve.
136129 * @return the value of column {@code name} as a long. If the value is NULL,
137130 * {@code 0L} is returned.
138- *
139131 * @throws IllegalArgumentException if {@code name} is not part of the
140- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
141- * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
132+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
133+ * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
142134 */
143135 @Override
144136 public long getLong(String name);
@@ -149,9 +141,8 @@
149141 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
150142 * @return the value of the {@code i}th column in this row as a data. If the
151143 * value is NULL, {@code null} is returned.
152- *
153144 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
154- * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
145+ * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
155146 */
156147 @Override
157148 public Date getDate(int i);
@@ -162,10 +153,9 @@
162153 * @param name the name of the column to retrieve.
163154 * @return the value of column {@code name} as a date. If the value is NULL,
164155 * {@code null} is returned.
165- *
166156 * @throws IllegalArgumentException if {@code name} is not part of the
167- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
168- * @throws InvalidTypeException if column {@code name} is not of type TIMESTAMP.
157+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
158+ * @throws InvalidTypeException if column {@code name} is not of type TIMESTAMP.
169159 */
170160 @Override
171161 public Date getDate(String name);
@@ -176,9 +166,8 @@
176166 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
177167 * @return the value of the {@code i}th column in this row as a float. If the
178168 * value is NULL, {@code 0.0f} is returned.
179- *
180169 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
181- * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
170+ * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
182171 */
183172 @Override
184173 public float getFloat(int i);
@@ -189,10 +178,9 @@
189178 * @param name the name of the column to retrieve.
190179 * @return the value of column {@code name} as a float. If the value is NULL,
191180 * {@code 0.0f} is returned.
192- *
193181 * @throws IllegalArgumentException if {@code name} is not part of the
194- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
195- * @throws InvalidTypeException if column {@code name} is not of type FLOAT.
182+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
183+ * @throws InvalidTypeException if column {@code name} is not of type FLOAT.
196184 */
197185 @Override
198186 public float getFloat(String name);
@@ -203,9 +191,8 @@
203191 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
204192 * @return the value of the {@code i}th column in this row as a double. If the
205193 * value is NULL, {@code 0.0} is returned.
206- *
207194 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
208- * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
195+ * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
209196 */
210197 @Override
211198 public double getDouble(int i);
@@ -216,17 +203,16 @@
216203 * @param name the name of the column to retrieve.
217204 * @return the value of column {@code name} as a double. If the value is NULL,
218205 * {@code 0.0} is returned.
219- *
220206 * @throws IllegalArgumentException if {@code name} is not part of the
221- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
222- * @throws InvalidTypeException if column {@code name} is not of type DOUBLE.
207+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
208+ * @throws InvalidTypeException if column {@code name} is not of type DOUBLE.
223209 */
224210 @Override
225211 public double getDouble(String name);
226212
227213 /**
228214 * Returns the {@code i}th value of this row as a ByteBuffer.
229- *
215+ * <p/>
230216 * Note: this method always return the bytes composing the value, even if
231217 * the column is not of type BLOB. That is, this method never throw an
232218 * InvalidTypeException. However, if the type is not BLOB, it is up to the
@@ -235,7 +221,6 @@
235221 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
236222 * @return the value of the {@code i}th column in this row as a ByteBuffer. If the
237223 * value is NULL, {@code null} is returned.
238- *
239224 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
240225 */
241226 @Override
@@ -243,7 +228,7 @@
243228
244229 /**
245230 * Returns the value of column {@code name} as a ByteBuffer.
246- *
231+ * <p/>
247232 * Note: this method always return the bytes composing the value, even if
248233 * the column is not of type BLOB. That is, this method never throw an
249234 * InvalidTypeException. However, if the type is not BLOB, it is up to the
@@ -252,42 +237,39 @@
252237 * @param name the name of the column to retrieve.
253238 * @return the value of column {@code name} as a ByteBuffer. If the value is NULL,
254239 * {@code null} is returned.
255- *
256240 * @throws IllegalArgumentException if {@code name} is not part of the
257- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
241+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
258242 */
259243 @Override
260244 public ByteBuffer getBytesUnsafe(String name);
261245
262246 /**
263247 * Returns the {@code i}th value of this row as a byte array.
264- * <p>
248+ * <p/>
265249 * Note that this method validate that the column is of type BLOB. If you want to retrieve
266250 * the bytes for any type of columns, use {@link #getBytesUnsafe(int)} instead.
267251 *
268252 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
269253 * @return the value of the {@code i}th column in this row as a byte array. If the
270254 * value is NULL, {@code null} is returned.
271- *
272255 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
273- * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
256+ * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
274257 */
275258 @Override
276259 public ByteBuffer getBytes(int i);
277260
278261 /**
279262 * Returns the value of column {@code name} as a byte array.
280- * <p>
263+ * <p/>
281264 * Note that this method validate that the column is of type BLOB. If you want to retrieve
282265 * the bytes for any type of columns, use {@link #getBytesUnsafe(String)} instead.
283266 *
284267 * @param name the name of the column to retrieve.
285268 * @return the value of column {@code name} as a byte array. If the value is NULL,
286269 * {@code null} is returned.
287- *
288270 * @throws IllegalArgumentException if {@code name} is not part of the
289- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
290- * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
271+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
272+ * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
291273 */
292274 @Override
293275 public ByteBuffer getBytes(String name);
@@ -298,10 +280,9 @@
298280 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
299281 * @return the value of the {@code i}th column in this row as a string. If the
300282 * value is NULL, {@code null} is returned.
301- *
302283 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
303- * @throws InvalidTypeException if column {@code i} type is none of:
304- * VARCHAR, TEXT or ASCII.
284+ * @throws InvalidTypeException if column {@code i} type is none of:
285+ * VARCHAR, TEXT or ASCII.
305286 */
306287 @Override
307288 public String getString(int i);
@@ -312,11 +293,10 @@
312293 * @param name the name of the column to retrieve.
313294 * @return the value of column {@code name} as a string. If the value is NULL,
314295 * {@code null} is returned.
315- *
316296 * @throws IllegalArgumentException if {@code name} is not part of the
317- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
318- * @throws InvalidTypeException if column {@code name} type is none of:
319- * VARCHAR, TEXT or ASCII.
297+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
298+ * @throws InvalidTypeException if column {@code name} type is none of:
299+ * VARCHAR, TEXT or ASCII.
320300 */
321301 @Override
322302 public String getString(String name);
@@ -327,9 +307,8 @@
327307 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
328308 * @return the value of the {@code i}th column in this row as a variable
329309 * length integer. If the value is NULL, {@code null} is returned.
330- *
331310 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
332- * @throws InvalidTypeException if column {@code i} is not of type VARINT.
311+ * @throws InvalidTypeException if column {@code i} is not of type VARINT.
333312 */
334313 @Override
335314 public BigInteger getVarint(int i);
@@ -340,10 +319,9 @@
340319 * @param name the name of the column to retrieve.
341320 * @return the value of column {@code name} as a variable length integer.
342321 * If the value is NULL, {@code null} is returned.
343- *
344322 * @throws IllegalArgumentException if {@code name} is not part of the
345- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
346- * @throws InvalidTypeException if column {@code name} is not of type VARINT.
323+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
324+ * @throws InvalidTypeException if column {@code name} is not of type VARINT.
347325 */
348326 @Override
349327 public BigInteger getVarint(String name);
@@ -354,9 +332,8 @@
354332 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
355333 * @return the value of the {@code i}th column in this row as a variable
356334 * length decimal. If the value is NULL, {@code null} is returned.
357- *
358335 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
359- * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
336+ * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
360337 */
361338 @Override
362339 public BigDecimal getDecimal(int i);
@@ -367,10 +344,9 @@
367344 * @param name the name of the column to retrieve.
368345 * @return the value of column {@code name} as a variable length decimal.
369346 * If the value is NULL, {@code null} is returned.
370- *
371347 * @throws IllegalArgumentException if {@code name} is not part of the
372- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
373- * @throws InvalidTypeException if column {@code name} is not of type DECIMAL.
348+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
349+ * @throws InvalidTypeException if column {@code name} is not of type DECIMAL.
374350 */
375351 @Override
376352 public BigDecimal getDecimal(String name);
@@ -381,10 +357,9 @@
381357 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
382358 * @return the value of the {@code i}th column in this row as a UUID.
383359 * If the value is NULL, {@code null} is returned.
384- *
385360 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
386- * @throws InvalidTypeException if column {@code i} is not of type UUID
387- * or TIMEUUID.
361+ * @throws InvalidTypeException if column {@code i} is not of type UUID
362+ * or TIMEUUID.
388363 */
389364 @Override
390365 public UUID getUUID(int i);
@@ -395,11 +370,10 @@
395370 * @param name the name of the column to retrieve.
396371 * @return the value of column {@code name} as a UUID.
397372 * If the value is NULL, {@code null} is returned.
398- *
399373 * @throws IllegalArgumentException if {@code name} is not part of the
400- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
401- * @throws InvalidTypeException if column {@code name} is not of type
402- * UUID or TIMEUUID.
374+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
375+ * @throws InvalidTypeException if column {@code name} is not of type
376+ * UUID or TIMEUUID.
403377 */
404378 @Override
405379 public UUID getUUID(String name);
@@ -410,9 +384,8 @@
410384 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
411385 * @return the value of the {@code i}th column in this row as an InetAddress.
412386 * If the value is NULL, {@code null} is returned.
413- *
414387 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
415- * @throws InvalidTypeException if column {@code i} is not of type INET.
388+ * @throws InvalidTypeException if column {@code i} is not of type INET.
416389 */
417390 @Override
418391 public InetAddress getInet(int i);
@@ -423,49 +396,46 @@
423396 * @param name the name of the column to retrieve.
424397 * @return the value of column {@code name} as an InetAddress.
425398 * If the value is NULL, {@code null} is returned.
426- *
427399 * @throws IllegalArgumentException if {@code name} is not part of the
428- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
429- * @throws InvalidTypeException if column {@code name} is not of type
430- * INET.
400+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
401+ * @throws InvalidTypeException if column {@code name} is not of type
402+ * INET.
431403 */
432404 @Override
433405 public InetAddress getInet(String name);
434406
435407 /**
436408 * Returns the {@code i}th value of this row as a {@link Token}.
437- * <p>
409+ * <p/>
438410 * {@link #getPartitionKeyToken()} should generally be preferred to this method (unless the
439411 * token column is aliased).
440412 *
441413 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
442414 * @return the value of the {@code i}th column in this row as an Token.
443- *
444415 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
445- * @throws InvalidTypeException if column {@code i} is not of the type of token values
446- * for this cluster (this depends on the configured partitioner).
416+ * @throws InvalidTypeException if column {@code i} is not of the type of token values
417+ * for this cluster (this depends on the configured partitioner).
447418 */
448419 public Token getToken(int i);
449420
450421 /**
451422 * Returns the value of column {@code name} as a {@link Token}.
452- * <p>
423+ * <p/>
453424 * {@link #getPartitionKeyToken()} should generally be preferred to this method (unless the
454425 * token column is aliased).
455426 *
456427 * @param name the name of the column to retrieve.
457428 * @return the value of column {@code name} as a Token.
458- *
459429 * @throws IllegalArgumentException if {@code name} is not part of the
460- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
461- * @throws InvalidTypeException if column {@code name} is not of the type of token values
462- * for this cluster (this depends on the configured partitioner).
430+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
431+ * @throws InvalidTypeException if column {@code name} is not of the type of token values
432+ * for this cluster (this depends on the configured partitioner).
463433 */
464434 public Token getToken(String name);
465435
466436 /**
467437 * Returns the value of the first column containing a {@link Token}.
468- * <p>
438+ * <p/>
469439 * This method is a shorthand for queries returning a single token in an unaliased
470440 * column. It will look for the first name matching {@code token(...)}:
471441 * <pre>
@@ -478,28 +448,26 @@
478448 * {@link #getToken(int)} or {@link #getToken(String)}.
479449 *
480450 * @return the value of column {@code name} as a Token.
481- *
482451 * @throws IllegalStateException if no column named {@code token(...)} exists in this
483- * ResultSet.
484- * @throws InvalidTypeException if the first column named {@code token(...)} is not of
485- * the type of token values for this cluster (this depends on the configured partitioner).
452+ * ResultSet.
453+ * @throws InvalidTypeException if the first column named {@code token(...)} is not of
454+ * the type of token values for this cluster (this depends on the configured partitioner).
486455 */
487456 public Token getPartitionKeyToken();
488457
489458 /**
490459 * Returns the {@code i}th value of this row as a list.
491460 *
492- * @param <T> the type of the elements of the list to return.
493- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
461+ * @param <T> the type of the elements of the list to return.
462+ * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
494463 * @param elementsClass the class for the elements of the list to retrieve.
495464 * @return the value of the {@code i}th column in this row as a list of
496465 * {@code elementsClass} objects. If the value is NULL, an empty list is
497466 * returned (note that Cassandra makes no difference between an empty list
498467 * and column of type list that is not set). The returned list is immutable.
499- *
500468 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
501- * @throws InvalidTypeException if column {@code i} is not a list or if its
502- * elements are not of class {@code elementsClass}.
469+ * @throws InvalidTypeException if column {@code i} is not a list or if its
470+ * elements are not of class {@code elementsClass}.
503471 */
504472 @Override
505473 public <T> List<T> getList(int i, Class<T> elementsClass);
@@ -507,18 +475,17 @@
507475 /**
508476 * Returns the value of column {@code name} as a list.
509477 *
510- * @param <T> the type of the elements of the list to return.
511- * @param name the name of the column to retrieve.
478+ * @param <T> the type of the elements of the list to return.
479+ * @param name the name of the column to retrieve.
512480 * @param elementsClass the class for the elements of the list to retrieve.
513481 * @return the value of the {@code i}th column in this row as a list of
514482 * {@code elementsClass} objects. If the value is NULL, an empty list is
515483 * returned (note that Cassandra makes no difference between an empty list
516484 * and column of type list that is not set). The returned list is immutable.
517- *
518485 * @throws IllegalArgumentException if {@code name} is not part of the
519- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
520- * @throws InvalidTypeException if column {@code name} is not a list or if its
521- * elements are not of class {@code elementsClass}.
486+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
487+ * @throws InvalidTypeException if column {@code name} is not a list or if its
488+ * elements are not of class {@code elementsClass}.
522489 */
523490 @Override
524491 public <T> List<T> getList(String name, Class<T> elementsClass);
@@ -526,17 +493,16 @@
526493 /**
527494 * Returns the {@code i}th value of this row as a set.
528495 *
529- * @param <T> the type of the elements of the set to return.
530- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
496+ * @param <T> the type of the elements of the set to return.
497+ * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
531498 * @param elementsClass the class for the elements of the set to retrieve.
532499 * @return the value of the {@code i}th column in this row as a set of
533500 * {@code elementsClass} objects. If the value is NULL, an empty set is
534501 * returned (note that Cassandra makes no difference between an empty set
535502 * and column of type set that is not set). The returned set is immutable.
536- *
537503 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
538- * @throws InvalidTypeException if column {@code i} is not a set or if its
539- * elements are not of class {@code elementsClass}.
504+ * @throws InvalidTypeException if column {@code i} is not a set or if its
505+ * elements are not of class {@code elementsClass}.
540506 */
541507 @Override
542508 public <T> Set<T> getSet(int i, Class<T> elementsClass);
@@ -544,18 +510,17 @@
544510 /**
545511 * Returns the value of column {@code name} as a set.
546512 *
547- * @param <T> the type of the elements of the set to return.
548- * @param name the name of the column to retrieve.
513+ * @param <T> the type of the elements of the set to return.
514+ * @param name the name of the column to retrieve.
549515 * @param elementsClass the class for the elements of the set to retrieve.
550516 * @return the value of the {@code i}th column in this row as a set of
551517 * {@code elementsClass} objects. If the value is NULL, an empty set is
552518 * returned (note that Cassandra makes no difference between an empty set
553519 * and column of type set that is not set). The returned set is immutable.
554- *
555520 * @throws IllegalArgumentException if {@code name} is not part of the
556- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
557- * @throws InvalidTypeException if column {@code name} is not a set or if its
558- * elements are not of class {@code elementsClass}.
521+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
522+ * @throws InvalidTypeException if column {@code name} is not a set or if its
523+ * elements are not of class {@code elementsClass}.
559524 */
560525 @Override
561526 public <T> Set<T> getSet(String name, Class<T> elementsClass);
@@ -563,21 +528,20 @@
563528 /**
564529 * Returns the {@code i}th value of this row as a map.
565530 *
566- * @param <K> the type of the keys of the map to return.
567- * @param <V> the type of the values of the map to return.
568- * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
569- * @param keysClass the class for the keys of the map to retrieve.
531+ * @param <K> the type of the keys of the map to return.
532+ * @param <V> the type of the values of the map to return.
533+ * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
534+ * @param keysClass the class for the keys of the map to retrieve.
570535 * @param valuesClass the class for the values of the map to retrieve.
571536 * @return the value of the {@code i}th column in this row as a map of
572537 * {@code keysClass} to {@code valuesClass} objects. If the value is NULL,
573538 * an empty map is returned (note that Cassandra makes no difference
574539 * between an empty map and column of type map that is not set). The
575540 * returned map is immutable.
576- *
577541 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
578- * @throws InvalidTypeException if column {@code i} is not a map, if its
579- * keys are not of class {@code keysClass} or if its values are not of
580- * class {@code valuesClass}.
542+ * @throws InvalidTypeException if column {@code i} is not a map, if its
543+ * keys are not of class {@code keysClass} or if its values are not of
544+ * class {@code valuesClass}.
581545 */
582546 @Override
583547 public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass);
@@ -585,22 +549,21 @@
585549 /**
586550 * Returns the value of column {@code name} as a map.
587551 *
588- * @param <K> the type of the keys of the map to return.
589- * @param <V> the type of the values of the map to return.
590- * @param name the name of the column to retrieve.
591- * @param keysClass the class for the keys of the map to retrieve.
552+ * @param <K> the type of the keys of the map to return.
553+ * @param <V> the type of the values of the map to return.
554+ * @param name the name of the column to retrieve.
555+ * @param keysClass the class for the keys of the map to retrieve.
592556 * @param valuesClass the class for the values of the map to retrieve.
593557 * @return the value of the {@code i}th column in this row as a map of
594558 * {@code keysClass} to {@code valuesClass} objects. If the value is NULL,
595559 * an empty map is returned (note that Cassandra makes no difference
596560 * between an empty map and column of type map that is not set). The
597561 * returned map is immutable.
598- *
599562 * @throws IllegalArgumentException if {@code name} is not part of the
600- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
601- * @throws InvalidTypeException if column {@code name} is not a map, if its
602- * keys are not of class {@code keysClass} or if its values are not of
603- * class {@code valuesClass}.
563+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
564+ * @throws InvalidTypeException if column {@code name} is not a map, if its
565+ * keys are not of class {@code keysClass} or if its values are not of
566+ * class {@code valuesClass}.
604567 */
605568 @Override
606569 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 +4 −4
@@ -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);
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 +42 −40
@@ -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(), 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 });
@@ -356,7 +358,7 @@
356358 cluster.manager.logUnsupportedVersionProtocol(host);
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 /*
@@ -502,16 +504,16 @@
502504 }
503505
504506 if (statement instanceof StatementWrapper)
505- statement = ((StatementWrapper)statement).getWrappedStatement();
507+ statement = ((StatementWrapper) statement).getWrappedStatement();
506508
507509 if (statement instanceof RegularStatement) {
508- RegularStatement rs = (RegularStatement)statement;
510+ RegularStatement rs = (RegularStatement) statement;
509511
510512 // It saddens me that we special case for the query builder here, but for now this is simpler.
511513 // We could provide a general API in RegularStatement instead at some point but it's unclear what's
512514 // the cleanest way to do that is right now (and it's probably not really that useful anyway).
513515 if (protoVersion == 1 && rs instanceof com.datastax.driver.core.querybuilder.BuiltStatement)
514- ((com.datastax.driver.core.querybuilder.BuiltStatement)rs).setForceNoValues(true);
516+ ((com.datastax.driver.core.querybuilder.BuiltStatement) rs).setForceNoValues(true);
515517
516518 ByteBuffer[] rawValues = rs.getValues();
517519
@@ -523,10 +525,10 @@
523525 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, values, false, fetchSize, usedPagingState, serialConsistency);
524526 return new Requests.Query(qString, options, statement.isTracing());
525527 } else if (statement instanceof BoundStatement) {
526- BoundStatement bs = (BoundStatement)statement;
528+ BoundStatement bs = (BoundStatement) statement;
527529 if (!cluster.manager.preparedQueries.containsKey(bs.statement.getPreparedId().id)) {
528530 throw new InvalidQueryException(String.format("Tried to execute unknown prepared query : %s. "
529- + "You may have used a PreparedStatement that was created with another Cluster instance.", bs.statement.getPreparedId().id));
531+ + "You may have used a PreparedStatement that was created with another Cluster instance.", bs.statement.getPreparedId().id));
530532 }
531533 boolean skipMetadata = protoVersion != 1 && bs.statement.getPreparedId().resultSetMetadata != null;
532534 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, Arrays.asList(bs.values), skipMetadata, fetchSize, usedPagingState, serialConsistency);
@@ -538,7 +540,7 @@
538540 if (protoVersion == 1)
539541 throw new UnsupportedFeatureException("Protocol level batching is not supported");
540542
541- BatchStatement bs = (BatchStatement)statement;
543+ BatchStatement bs = (BatchStatement) statement;
542544 BatchStatement.IdAndValues idAndVals = bs.getIdAndValues();
543545 return new Requests.Batch(bs.batchType, idAndVals.ids, idAndVals.values, consistency, statement.isTracing());
544546 }
@@ -546,7 +548,7 @@
546548
547549 /**
548550 * Execute the provided request.
549- *
551+ * <p/>
550552 * This method will find a suitable node to connect to using the
551553 * {@link LoadBalancingPolicy} and handle host failover.
552554 */
@@ -593,8 +595,8 @@
593595 }
594596 // Return the statement when all futures are done
595597 return Futures.transform(
596- Futures.successfulAsList(futures),
597- Functions.constant(statement));
598+ Futures.successfulAsList(futures),
599+ Functions.constant(statement));
598600 }
599601
600602 ResultSetFuture executeQuery(Message.Request msg, Statement statement) {
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);
9797 } catch (IllegalArgumentException e) {
9898 // Catch and rethrow to provide a more helpful error message (one that include which value is bad)
@@ -119,7 +119,7 @@
119119
120120 /**
121121 * Returns the number of values provided for this statement.
122- * <p>
122+ * <p/>
123123 * This is more efficient than calling {@link #getValues()} and getting the length
124124 * of the returned array, because {@code getValues()} does some internal conversions.
125125 *
@@ -134,8 +134,7 @@
134134 *
135135 * @param i the index to retrieve.
136136 * @return the value of the {@code i}th value of this statement.
137- *
138- * @throws IllegalStateException if this statement does not have values.
137+ * @throws IllegalStateException if this statement does not have values.
139138 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
140139 */
141140 public Object getObject(int i) {
@@ -148,14 +147,13 @@
148147
149148 /**
150149 * Returns the routing key for the query.
151- * <p>
150+ * <p/>
152151 * Unless the routing key has been explicitly set through
153152 * {@link #setRoutingKey}, this method will return {@code null} to
154153 * avoid having to parse the query string to retrieve the partition key.
155154 *
156155 * @return the routing key set through {@link #setRoutingKey} if such a key
157156 * was set, {@code null} otherwise.
158- *
159157 * @see Statement#getRoutingKey
160158 */
161159 @Override
@@ -165,18 +163,17 @@
165163
166164 /**
167165 * Sets the routing key for this query.
168- * <p>
166+ * <p/>
169167 * This method allows you to manually provide a routing key for this query. It
170168 * is thus optional since the routing key is only an hint for token aware
171169 * load balancing policy but is never mandatory.
172- * <p>
170+ * <p/>
173171 * If the partition key for the query is composite, use the
174172 * {@link #setRoutingKey(ByteBuffer...)} method instead to build the
175173 * routing key.
176174 *
177175 * @param routingKey the raw (binary) value to use as routing key.
178176 * @return this {@code SimpleStatement} object.
179- *
180177 * @see Statement#getRoutingKey
181178 */
182179 public SimpleStatement setRoutingKey(ByteBuffer routingKey) {
@@ -186,14 +183,13 @@
186183
187184 /**
188185 * Returns the keyspace this query operates on.
189- * <p>
186+ * <p/>
190187 * Unless the keyspace has been explicitly set through {@link #setKeyspace},
191188 * this method will return {@code null} to avoid having to parse the query
192189 * string.
193190 *
194191 * @return the keyspace set through {@link #setKeyspace} if such keyspace was
195192 * set, {@code null} otherwise.
196- *
197193 * @see Statement#getKeyspace
198194 */
199195 @Override
@@ -203,18 +199,17 @@
203199
204200 /**
205201 * Sets the keyspace this query operates on.
206- * <p>
202+ * <p/>
207203 * This method allows you to manually provide a keyspace for this query. It
208204 * is thus optional since the value returned by this method is only an hint
209205 * for token aware load balancing policy but is never mandatory.
210- * <p>
206+ * <p/>
211207 * Do note that if the query does not use a fully qualified keyspace, then
212208 * you do not need to set the keyspace through that method as the
213209 * currently logged in keyspace will be used.
214210 *
215211 * @param keyspace the name of the keyspace this query operates on.
216212 * @return this {@code SimpleStatement} object.
217- *
218213 * @see Statement#getKeyspace
219214 */
220215 public SimpleStatement setKeyspace(String keyspace) {
@@ -224,15 +219,14 @@
224219
225220 /**
226221 * Sets the routing key for this query.
227- * <p>
222+ * <p/>
228223 * See {@link #setRoutingKey(ByteBuffer)} for more information. This
229224 * method is a variant for when the query partition key is composite and
230225 * thus the routing key must be built from multiple values.
231226 *
232227 * @param routingKeyComponents the raw (binary) values to compose to obtain
233- * the routing key.
228+ * the routing key.
234229 * @return this {@code SimpleStatement} object.
235- *
236230 * @see Statement#getRoutingKey
237231 */
238232 public SimpleStatement setRoutingKey(ByteBuffer... routingKeyComponents) {
@@ -247,8 +241,7 @@
247241 totalLength += 2 + bb.remaining() + 1;
248242
249243 ByteBuffer out = ByteBuffer.allocate(totalLength);
250- for (ByteBuffer buffer : buffers)
251- {
244+ for (ByteBuffer buffer : buffers) {
252245 ByteBuffer bb = buffer.duplicate();
253246 putShortLength(out, bb.remaining());
254247 out.put(bb);
modified driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +25 −34
@@ -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 *
@@ -79,10 +80,10 @@
7980
8081 /**
8182 * The per-host read timeout in milliseconds.
82- * <p>
83+ * <p/>
8384 * This defines how long the driver will wait for a given Cassandra node to
8485 * answer a query.
85- * <p>
86+ * <p/>
8687 * Please note that this is not the maximum time a call to {@link Session#execute} may block;
8788 * this is the maximum time that call will wait for one particular
8889 * Cassandra host, but other hosts will be tried if one of them times out. In
@@ -92,12 +93,12 @@
9293 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy} in use).
9394 * If you want to control how long to wait for a query, use {@link Session#executeAsync}
9495 * and the {@code ResultSetFuture#get(long, TimeUnit)} method.
95- * <p>
96+ * <p/>
9697 * Also note that for efficiency reasons, this read timeout is approximate: it
9798 * has an accuracy of up to 100 milliseconds (i.e. it may fire up to 100 milliseconds late).
9899 * It is not meant to be used for precise timeout, but rather as a protection
99100 * against misbehaving Cassandra nodes.
100- * <p>
101+ * <p/>
101102 *
102103 * @return the read timeout in milliseconds.
103104 */
@@ -107,18 +108,18 @@
107108
108109 /**
109110 * Sets the per-host read timeout in milliseconds.
110- * <p>
111+ * <p/>
111112 * When setting this value, keep in mind the following:
112113 * <ul>
113- * <li>it should be higher than the timeout settings used on the Cassandra side
114- * ({@code *_request_timeout_in_ms} in {@code cassandra.yaml}).</li>
115- * <li>the read timeout is only approximate and only control the timeout to one Cassandra
116- * host, not the full query (see {@link #getReadTimeoutMillis} for more details). If a
117- * high level of precision on the timeout to a request is required, you should use
118- * the {@link ResultSetFuture#get(long, java.util.concurrent.TimeUnit)} method.
119- * </li>
114+ * <li>it should be higher than the timeout settings used on the Cassandra side
115+ * ({@code *_request_timeout_in_ms} in {@code cassandra.yaml}).</li>
116+ * <li>the read timeout is only approximate and only control the timeout to one Cassandra
117+ * host, not the full query (see {@link #getReadTimeoutMillis} for more details). If a
118+ * high level of precision on the timeout to a request is required, you should use
119+ * the {@link ResultSetFuture#get(long, java.util.concurrent.TimeUnit)} method.
120+ * </li>
120121 * </ul>
121- * <p>
122+ * <p/>
122123 * Setting a value of 0 disables read timeouts.
123124 *
124125 * @param readTimeoutMillis the timeout to set.
@@ -141,13 +142,12 @@
141142
142143 /**
143144 * Sets whether to enable TCP keepalive.
144- * <p>
145+ * <p/>
145146 * By default, this option is not set by the driver. The actual value will be the default
146147 * from the underlying Netty transport (Java NIO or native epoll).
147148 *
148149 * @param keepAlive whether to enable or disable the option.
149150 * @return this {@code SocketOptions}.
150- *
151151 * @see java.net.SocketOptions#TCP_NODELAY
152152 */
153153 public SocketOptions setKeepAlive(boolean keepAlive) {
@@ -167,13 +167,12 @@
167167
168168 /**
169169 * Sets whether to enable reuse-address.
170- * <p>
170+ * <p/>
171171 * By default, this option is not set by the driver. The actual value will be the default
172172 * from the underlying Netty transport (Java NIO or native epoll).
173173 *
174174 * @param reuseAddress whether to enable or disable the option.
175175 * @return this {@code SocketOptions}.
176- *
177176 * @see java.net.SocketOptions#SO_REUSEADDR
178177 */
179178 public SocketOptions setReuseAddress(boolean reuseAddress) {
@@ -185,7 +184,6 @@
185184 * Returns the linger-on-close timeout.
186185 *
187186 * @return the value of the option, or {@code null} if it is not set.
188- *
189187 * @see #setSoLinger(int)
190188 */
191189 public Integer getSoLinger() {
@@ -194,13 +192,12 @@
194192
195193 /**
196194 * Sets the linger-on-close timeout.
197- * <p>
195+ * <p/>
198196 * By default, this option is not set by the driver. The actual value will be the default
199197 * from the underlying Netty transport (Java NIO or native epoll).
200-
198+ *
201199 * @param soLinger the new value.
202200 * @return this {@code SocketOptions}.
203- *
204201 * @see java.net.SocketOptions#SO_LINGER
205202 */
206203 public SocketOptions setSoLinger(int soLinger) {
@@ -212,7 +209,6 @@
212209 * Returns whether Nagle's algorithm is disabled.
213210 *
214211 * @return the value of the option ({@code true} means Nagle is disabled), or {@code null} if it is not set.
215- *
216212 * @see #setTcpNoDelay(boolean)
217213 */
218214 public Boolean getTcpNoDelay() {
@@ -221,12 +217,11 @@
221217
222218 /**
223219 * Sets whether to disable Nagle's algorithm.
224- * <p>
220+ * <p/>
225221 * By default, this option is set to {@code true} (Nagle disabled).
226222 *
227223 * @param tcpNoDelay whether to enable or disable the option.
228224 * @return this {@code SocketOptions}.
229- *
230225 * @see java.net.SocketOptions#TCP_NODELAY
231226 */
232227 public SocketOptions setTcpNoDelay(boolean tcpNoDelay) {
@@ -238,7 +233,6 @@
238233 * Returns the hint to the size of the underlying buffers for incoming network I/O.
239234 *
240235 * @return the value of the option, or {@code null} if it is not set.
241- *
242236 * @see #setReceiveBufferSize(int)
243237 */
244238 public Integer getReceiveBufferSize() {
@@ -247,13 +241,12 @@
247241
248242 /**
249243 * Sets a hint to the size of the underlying buffers for incoming network I/O.
250- * <p>
244+ * <p/>
251245 * By default, this option is not set by the driver. The actual value will be the default
252246 * from the underlying Netty transport (Java NIO or native epoll).
253247 *
254248 * @param receiveBufferSize the new value.
255249 * @return this {@code SocketOptions}.
256- *
257250 * @see java.net.SocketOptions#SO_RCVBUF
258251 */
259252 public SocketOptions setReceiveBufferSize(int receiveBufferSize) {
@@ -265,7 +258,6 @@
265258 * Returns the hint to the size of the underlying buffers for outgoing network I/O.
266259 *
267260 * @return the value of the option, or {@code null} if it is not set.
268- *
269261 * @see #setSendBufferSize(int)
270262 */
271263 public Integer getSendBufferSize() {
@@ -274,13 +266,12 @@
274266
275267 /**
276268 * Sets a hint to the size of the underlying buffers for outgoing network I/O.
277- * <p>
269+ * <p/>
278270 * By default, this option is not set by the driver. The actual value will be the default
279271 * from the underlying Netty transport (Java NIO or native epoll).
280272 *
281273 * @param sendBufferSize the new value.
282274 * @return this {@code SocketOptions}.
283- *
284275 * @see java.net.SocketOptions#SO_SNDBUF
285276 */
286277 public SocketOptions setSendBufferSize(int sendBufferSize) {
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +29 −31
@@ -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, ...).
@@ -80,7 +80,7 @@
8080
8181 /**
8282 * Sets the serial consistency level for the query.
83- *
83+ * <p/>
8484 * The serial consistency level is only used by conditional updates (so INSERT, UPDATE
8585 * and DELETE with an IF condition). For those, the serial consistency level defines
8686 * the consistency level of the serial phase (or "paxos" phase) while the
@@ -90,20 +90,19 @@
9090 * QUORUM read is guaranteed to see that write. But if the regular consistency of that
9191 * write is ANY, then only a read with a consistency of SERIAL is guaranteed to see it
9292 * (even a read with consistency ALL is not guaranteed to be enough).
93- * <p>
93+ * <p/>
9494 * The serial consistency can only be one of {@code ConsistencyLevel.SERIAL} or
9595 * {@code ConsistencyLevel.LOCAL_SERIAL}. While {@code ConsistencyLevel.SERIAL} guarantees full
9696 * linearizability (with other SERIAL updates), {@code ConsistencyLevel.LOCAL_SERIAL} only
9797 * guarantees it in the local data center.
98- * <p>
98+ * <p/>
9999 * The serial consistency level is ignored for any query that is not a conditional
100100 * update (serial reads should use the regular consistency level for instance).
101101 *
102102 * @param serialConsistency the serial consistency level to set.
103103 * @return this {@code Statement} object.
104- *
105104 * @throws IllegalArgumentException if {@code serialConsistency} is not one of
106- * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
105+ * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
107106 */
108107 public Statement setSerialConsistencyLevel(ConsistencyLevel serialConsistency) {
109108 if (serialConsistency != ConsistencyLevel.SERIAL && serialConsistency != ConsistencyLevel.LOCAL_SERIAL)
@@ -114,7 +113,7 @@
114113
115114 /**
116115 * The serial consistency level for this query.
117- * <p>
116+ * <p/>
118117 * See {@link #setSerialConsistencyLevel} for more detail on the serial consistency level.
119118 *
120119 * @return the consistency level for this query, or {@code null} if no serial
@@ -127,7 +126,7 @@
127126
128127 /**
129128 * Enables tracing for this query.
130- *
129+ * <p/>
131130 * By default (that is unless you call this method), tracing is not enabled.
132131 *
133132 * @return this {@code Statement} object.
@@ -158,9 +157,9 @@
158157 }
159158
160159 /**
161- * Returns the routing key (in binary raw form) to use for token aware
160+ * Returns the routing key (in binary raw form) to use for token aware
162161 * routing of this query.
163- * <p>
162+ * <p/>
164163 * The routing key is optional in that implementers are free to
165164 * return {@code null}. The routing key is an hint used for token-aware routing (see
166165 * {@link com.datastax.driver.core.policies.TokenAwarePolicy}), and
@@ -175,7 +174,7 @@
175174
176175 /**
177176 * Returns the keyspace this query operates on.
178- * <p>
177+ * <p/>
179178 * Note that not all query specify on which keyspace they operate on, and
180179 * so this method can always return {@code null}. Firstly, some queries do
181180 * not operate inside a keyspace: keyspace creation, {@code USE} queries,
@@ -195,7 +194,7 @@
195194
196195 /**
197196 * Sets the retry policy to use for this query.
198- * <p>
197+ * <p/>
199198 * The default retry policy, if this method is not called, is the one returned by
200199 * {@link com.datastax.driver.core.policies.Policies#getRetryPolicy} in the
201200 * cluster configuration. This method is thus only useful in case you want
@@ -222,7 +221,7 @@
222221
223222 /**
224223 * Sets the query fetch size.
225- * <p>
224+ * <p/>
226225 * The fetch size controls how much resulting rows will be retrieved
227226 * simultaneously (the goal being to avoid loading too much results
228227 * in memory for queries yielding large results). Please note that
@@ -230,9 +229,9 @@
230229 * use such a low value in practice as it will yield very poor
231230 * performance. If in doubt, leaving the default is probably a good
232231 * idea.
233- * <p>
232+ * <p/>
234233 * Only {@code SELECT} queries only ever make use of that setting.
235- * <p>
234+ * <p/>
236235 * Note: Paging is not supported with the native protocol version 1. If
237236 * you call this method with {@code fetchSize &gt; 0} and
238237 * {@code fetchSize != Integer.MAX_VALUE} and the protocol version is in
@@ -241,8 +240,8 @@
241240 * when submitting this statement for execution.
242241 *
243242 * @param fetchSize the fetch size to use. If {@code fetchSize &lte; 0},
244- * the default fetch size will be used. To disable paging of the
245- * result set, use {@code fetchSize == Integer.MAX_VALUE}.
243+ * the default fetch size will be used. To disable paging of the
244+ * result set, use {@code fetchSize == Integer.MAX_VALUE}.
246245 * @return this {@code Statement} object.
247246 */
248247 public Statement setFetchSize(int fetchSize) {
@@ -263,10 +262,10 @@
263262
264263 /**
265264 * Sets the paging state.
266- * <p>
265+ * <p/>
267266 * This will cause the next execution of this statement to fetch results from a given
268267 * page, rather than restarting from the beginning.
269- * <p>
268+ * <p/>
270269 * You get the paging state from a previous execution of the statement (see
271270 * {@link ExecutionInfo#getPagingState()}.
272271 * This is typically used to iterate in a "stateless" manner (e.g. across HTTP requests):
@@ -296,11 +295,11 @@
296295 * }
297296 * }
298297 * </pre>
299- * <p>
298+ * <p/>
300299 * The paging state can only be reused between perfectly identical statements
301300 * (same query string, same bound parameters). Altering the contents of the paging state
302301 * or trying to set it on a different statement will cause this method to fail.
303- * <p>
302+ * <p/>
304303 * Note that, due to internal implementation details, the paging state is not portable
305304 * across native protocol versions (see the
306305 * <a href="http://datastax.github.io/java-driver/features/native_protocol">online documentation</a>
@@ -312,7 +311,6 @@
312311 * @param pagingState the paging state to set, or {@code null} to remove any state that was
313312 * previously set on this statement.
314313 * @return this {@code Statement} object.
315- *
316314 * @throws PagingStateException if the paging state does not match this statement.
317315 */
318316 public Statement setPagingState(PagingState pagingState) {
@@ -325,8 +323,8 @@
325323 this.pagingState = pagingState.getRawState();
326324 } else {
327325 throw new PagingStateException("Paging state mismatch, "
328- + "this means that either the paging state contents were altered, "
329- + "or you're trying to apply it to a different statement");
326+ + "this means that either the paging state contents were altered, "
327+ + "or you're trying to apply it to a different statement");
330328 }
331329 }
332330 return this;
@@ -334,7 +332,7 @@
334332
335333 /**
336334 * Sets the paging state.
337- * <p>
335+ * <p/>
338336 * Contrary to {@link #setPagingState(PagingState)}, this method takes the "raw" form of the
339337 * paging state (previously extracted with {@link ExecutionInfo#getPagingStateUnsafe()}.
340338 * It won't validate that this statement matches the one that the paging state was extracted from.
@@ -362,7 +360,7 @@
362360
363361 /**
364362 * Sets whether this statement is idempotent.
365- * <p>
363+ * <p/>
366364 * See {@link #isIdempotent()} for more explanations about this property.
367365 *
368366 * @param idempotent the new value.
@@ -376,14 +374,14 @@
376374 /**
377375 * Whether this statement is idempotent, i.e. whether it can be applied multiple times
378376 * without changing the result beyond the initial application.
379- * <p>
377+ * <p/>
380378 * Idempotence plays a role in {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}.
381379 * If a statement is <em>not idempotent</em>, the driver will not schedule speculative
382380 * executions for it.
383- * <p>
381+ * <p/>
384382 * Note that this method can return {@code null}, in which case the driver will default to
385383 * {@link QueryOptions#getDefaultIdempotence()}.
386- * <p>
384+ * <p/>
387385 * By default, this method returns {@code null} for all statements, except for
388386 * {@link BuiltStatement}s, where the value will be inferred from the query: if it updates
389387 * counters, prepends/appends to a list, or uses a function call or
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/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 +57 −55
@@ -15,13 +15,13 @@
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.Iterables;
2220 import org.slf4j.Logger;
2321 import org.slf4j.LoggerFactory;
2422
23+import java.util.*;
24+
2525 /**
2626 * Describes a Table.
2727 */
@@ -29,19 +29,19 @@
2929
3030 private static final Logger logger = LoggerFactory.getLogger(TableMetadata.class);
3131
32- static final String CF_NAME = "columnfamily_name";
32+ static final String CF_NAME = "columnfamily_name";
3333
34- private static final String KEY_VALIDATOR = "key_validator";
35- private static final String COMPARATOR = "comparator";
36- private static final String VALIDATOR = "default_validator";
34+ private static final String KEY_VALIDATOR = "key_validator";
35+ private static final String COMPARATOR = "comparator";
36+ private static final String VALIDATOR = "default_validator";
3737
38- private static final String KEY_ALIASES = "key_aliases";
39- private static final String COLUMN_ALIASES = "column_aliases";
40- private static final String VALUE_ALIAS = "value_alias";
38+ private static final String KEY_ALIASES = "key_aliases";
39+ private static final String COLUMN_ALIASES = "column_aliases";
40+ private static final String VALUE_ALIAS = "value_alias";
4141
42- private static final String DEFAULT_KEY_ALIAS = "key";
42+ private static final String DEFAULT_KEY_ALIAS = "key";
4343 private static final String DEFAULT_COLUMN_ALIAS = "column";
44- private static final String DEFAULT_VALUE_ALIAS = "value";
44+ private static final String DEFAULT_VALUE_ALIAS = "value";
4545
4646 private static final Comparator<ColumnMetadata> columnMetadataComparator = new Comparator<ColumnMetadata>() {
4747 public int compare(ColumnMetadata c1, ColumnMetadata c2) {
@@ -61,7 +61,7 @@
6161
6262 /**
6363 * Clustering orders.
64- * <p>
64+ * <p/>
6565 * This is used by {@link #getClusteringOrder} to indicate the clustering
6666 * order of a table.
6767 */
@@ -100,8 +100,8 @@
100100 CassandraTypeParser.ParseResult keyValidator = CassandraTypeParser.parseWithComposite(row.getString(KEY_VALIDATOR));
101101 CassandraTypeParser.ParseResult comparator = CassandraTypeParser.parseWithComposite(row.getString(COMPARATOR));
102102 List<String> columnAliases = cassandraVersion.getMajor() >= 2 || row.getString(COLUMN_ALIASES) == null
103- ? Collections.<String>emptyList()
104- : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES));
103+ ? Collections.<String>emptyList()
104+ : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES));
105105
106106 int clusteringSize = findClusteringSize(comparator, rawCols.values(), columnAliases, cassandraVersion);
107107 boolean isDense = clusteringSize != comparator.types.size() - 1;
@@ -121,8 +121,8 @@
121121 // See ControlConnection#refreshSchema for why we'd rather not probably this further. Since table options is one thing
122122 // that tends to change often in Cassandra, it's worth special casing this.
123123 logger.error(String.format("Error parsing schema options for table %s.%s: "
124- + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\").getOptions() will return null",
125- ksm.getName(), name, ksm.getName(), name), e);
124+ + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\").getOptions() will return null",
125+ ksm.getName(), name, ksm.getName(), name), e);
126126 }
127127
128128 TableMetadata tm = new TableMetadata(ksm, name, partitionKey, clusteringColumns, columns, options, clusteringOrder, cassandraVersion);
@@ -135,8 +135,8 @@
135135 // In C* 1.2, only the REGULAR columns are in the columns schema table, so we need to add the names from
136136 // the aliases (and make sure we handle default aliases).
137137 List<String> keyAliases = row.getString(KEY_ALIASES) == null
138- ? Collections.<String>emptyList()
139- : SimpleJSONParser.parseStringList(row.getString(KEY_ALIASES));
138+ ? Collections.<String>emptyList()
139+ : SimpleJSONParser.parseStringList(row.getString(KEY_ALIASES));
140140 for (int i = 0; i < partitionKey.size(); i++) {
141141 String alias = keyAliases.size() > i ? keyAliases.get(i) : (i == 0 ? DEFAULT_KEY_ALIAS : DEFAULT_KEY_ALIAS + (i + 1));
142142 partitionKey.set(i, ColumnMetadata.forAlias(tm, alias, keyValidator.types.get(i)));
@@ -234,8 +234,8 @@
234234 * Returns metadata on a column of this table.
235235 *
236236 * @param name the name of the column to retrieve ({@code name} will be
237- * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
238- * see {@link Metadata#quote}).
237+ * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
238+ * see {@link Metadata#quote}).
239239 * @return the metadata for the {@code name} column if it exists, or
240240 * {@code null} otherwise.
241241 */
@@ -245,7 +245,7 @@
245245
246246 /**
247247 * Returns a list containing all the columns of this table.
248- *
248+ * <p/>
249249 * The order of the columns in the list is consistent with
250250 * the order of the columns returned by a {@code SELECT * FROM thisTable}:
251251 * the first column is the partition key, next are the clustering
@@ -260,7 +260,7 @@
260260
261261 /**
262262 * Returns the list of columns composing the primary key for this table.
263- *
263+ * <p/>
264264 * A table will always at least have a partition key (that
265265 * may itself be one or more columns), so the returned list at least
266266 * has one element.
@@ -276,7 +276,7 @@
276276
277277 /**
278278 * Returns the list of columns composing the partition key for this table.
279- *
279+ * <p/>
280280 * A table always has a partition key so the returned list has
281281 * at least one element.
282282 *
@@ -298,7 +298,7 @@
298298
299299 /**
300300 * Returns the clustering order for this table.
301- * <p>
301+ * <p/>
302302 * The returned contains the clustering order of each clustering column. The
303303 * {@code i}th element of the result correspond to the order (ascending or
304304 * descending) of the {@code i}th clustering column (see
@@ -328,11 +328,11 @@
328328 /**
329329 * Returns a {@code String} containing CQL queries representing this
330330 * table and the index on it.
331- *
331+ * <p/>
332332 * In other words, this method returns the queries that would allow you to
333333 * recreate the schema of this table, along with the index defined on
334334 * columns of this table.
335- *
335+ * <p/>
336336 * Note that the returned String is formatted to be human readable (for
337337 * some definition of human readable at least).
338338 *
@@ -356,10 +356,10 @@
356356
357357 /**
358358 * Returns a CQL query representing this table.
359- *
359+ * <p/>
360360 * This method returns a single 'CREATE TABLE' query with the options
361361 * corresponding to this table definition.
362- *
362+ * <p/>
363363 * Note that the returned string is a single line; the returned query
364364 * is not formatted in any way.
365365 *
@@ -377,7 +377,7 @@
377377 if (o == null || getClass() != o.getClass())
378378 return false;
379379
380- TableMetadata that = (TableMetadata)o;
380+ TableMetadata that = (TableMetadata) o;
381381
382382 if (!name.equals(that.name))
383383 return false;
@@ -423,7 +423,8 @@
423423 sb.append('(');
424424 boolean first = true;
425425 for (ColumnMetadata cm : partitionKey) {
426- if (first) first = false; else sb.append(", ");
426+ if (first) first = false;
427+ else sb.append(", ");
427428 sb.append(Metadata.escapeId(cm.getName()));
428429 }
429430 sb.append(')');
@@ -449,7 +450,7 @@
449450 and(sb, formatted).append("bloom_filter_fp_chance = ").append(options.bfFpChance);
450451 and(sb, formatted).append("caching = '").append(options.caching).append('\'');
451452 if (options.comment != null)
452- and(sb, formatted).append("comment = '").append(options.comment.replace("'","''")).append('\'');
453+ and(sb, formatted).append("comment = '").append(options.comment.replace("'", "''")).append('\'');
453454 and(sb, formatted).append("compaction = ").append(formatOptionMap(options.compaction));
454455 and(sb, formatted).append("compression = ").append(formatOptionMap(options.compression));
455456 if (cassandraVersion.getMajor() >= 2) {
@@ -475,7 +476,8 @@
475476 sb.append("{ ");
476477 boolean first = true;
477478 for (Map.Entry<String, String> entry : m.entrySet()) {
478- if (first) first = false; else sb.append(", ");
479+ if (first) first = false;
480+ else sb.append(", ");
479481 sb.append('\'').append(entry.getKey()).append('\'');
480482 sb.append(" : ");
481483 try {
@@ -511,23 +513,23 @@
511513
512514 public static class Options {
513515
514- private static final String COMMENT = "comment";
515- private static final String READ_REPAIR = "read_repair_chance";
516- private static final String LOCAL_READ_REPAIR = "local_read_repair_chance";
517- private static final String REPLICATE_ON_WRITE = "replicate_on_write";
518- private static final String GC_GRACE = "gc_grace_seconds";
519- private static final String BF_FP_CHANCE = "bloom_filter_fp_chance";
520- private static final String CACHING = "caching";
521- private static final String COMPACTION_CLASS = "compaction_strategy_class";
522- private static final String COMPACTION_OPTIONS = "compaction_strategy_options";
516+ private static final String COMMENT = "comment";
517+ private static final String READ_REPAIR = "read_repair_chance";
518+ private static final String LOCAL_READ_REPAIR = "local_read_repair_chance";
519+ private static final String REPLICATE_ON_WRITE = "replicate_on_write";
520+ private static final String GC_GRACE = "gc_grace_seconds";
521+ private static final String BF_FP_CHANCE = "bloom_filter_fp_chance";
522+ private static final String CACHING = "caching";
523+ private static final String COMPACTION_CLASS = "compaction_strategy_class";
524+ private static final String COMPACTION_OPTIONS = "compaction_strategy_options";
523525 private static final String MIN_COMPACTION_THRESHOLD = "min_compaction_threshold";
524526 private static final String MAX_COMPACTION_THRESHOLD = "max_compaction_threshold";
525- private static final String POPULATE_CACHE_ON_FLUSH = "populate_io_cache_on_flush";
526- private static final String COMPRESSION_PARAMS = "compression_parameters";
527+ private static final String POPULATE_CACHE_ON_FLUSH = "populate_io_cache_on_flush";
528+ private static final String COMPRESSION_PARAMS = "compression_parameters";
527529 private static final String MEMTABLE_FLUSH_PERIOD_MS = "memtable_flush_period_in_ms";
528- private static final String DEFAULT_TTL = "default_time_to_live";
529- private static final String SPECULATIVE_RETRY = "speculative_retry";
530- private static final String INDEX_INTERVAL = "index_interval";
530+ private static final String DEFAULT_TTL = "default_time_to_live";
531+ private static final String SPECULATIVE_RETRY = "speculative_retry";
532+ private static final String INDEX_INTERVAL = "index_interval";
531533
532534 private static final boolean DEFAULT_REPLICATE_ON_WRITE = true;
533535 private static final double DEFAULT_BF_FP_CHANCE = 0.01;
@@ -577,7 +579,7 @@
577579
578580 private static boolean isNullOrAbsent(Row row, String name) {
579581 return row.getColumnDefinitions().getIndexOf(name) < 0
580- || row.isNull(name);
582+ || row.isNull(name);
581583 }
582584
583585 /**
@@ -618,7 +620,7 @@
618620
619621 /**
620622 * Returns whether replicateOnWrite is set for this table.
621- *
623+ * <p/>
622624 * This is only meaningful for tables holding counters.
623625 *
624626 * @return whether replicateOnWrite is set for this table.
@@ -678,7 +680,7 @@
678680
679681 /**
680682 * Returns the default TTL for this table.
681- * <p>
683+ * <p/>
682684 * Note: this option is not available in Cassandra 1.2 and will return 0 (no default
683685 * TTL) when connected to 1.2 nodes.
684686 *
@@ -691,7 +693,7 @@
691693
692694 /**
693695 * Returns the speculative retry option for this table.
694- * <p>
696+ * <p/>
695697 * Note: this option is not available in Cassandra 1.2 and will return "NONE" (no
696698 * speculative retry) when connected to 1.2 nodes.
697699 *
@@ -703,7 +705,7 @@
703705
704706 /**
705707 * Returns the index interval option for this table.
706- * <p>
708+ * <p/>
707709 * Note: this option is not available in Cassandra 1.2 (more precisely, it is not
708710 * configurable per-table) and will return 128 (the default index interval) when
709711 * connected to 1.2 nodes.
@@ -739,7 +741,7 @@
739741 if (o == null || getClass() != o.getClass())
740742 return false;
741743
742- Options options = (Options)o;
744+ Options options = (Options) o;
743745
744746 if (isCompactStorage != options.isCompactStorage)
745747 return false;
@@ -780,13 +782,13 @@
780782 result = (isCompactStorage ? 1 : 0);
781783 result = 31 * result + (comment != null ? comment.hashCode() : 0);
782784 temp = Double.doubleToLongBits(readRepair);
783- result = 31 * result + (int)(temp ^ (temp >>> 32));
785+ result = 31 * result + (int) (temp ^ (temp >>> 32));
784786 temp = Double.doubleToLongBits(localReadRepair);
785- result = 31 * result + (int)(temp ^ (temp >>> 32));
787+ result = 31 * result + (int) (temp ^ (temp >>> 32));
786788 result = 31 * result + (replicateOnWrite ? 1 : 0);
787789 result = 31 * result + gcGrace;
788790 temp = Double.doubleToLongBits(bfFpChance);
789- result = 31 * result + (int)(temp ^ (temp >>> 32));
791+ result = 31 * result + (int) (temp ^ (temp >>> 32));
790792 result = 31 * result + (caching != null ? caching.hashCode() : 0);
791793 result = 31 * result + (populateCacheOnFlush ? 1 : 0);
792794 result = 31 * result + memtableFlushPeriodMs;
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);
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) {
535- return new RPToken((BigInteger)getTokenType().deserialize(buffer));
573+ return new RPToken((BigInteger) getTokenType().deserialize(buffer));
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/TypeCodec.java +83 −67
@@ -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,42 +31,40 @@
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
3636 private static final Map<DataType.Name, TypeCodec<?>> primitiveCodecs = new EnumMap<DataType.Name, TypeCodec<?>>(DataType.Name.class);
37+
3738 static {
38- primitiveCodecs.put(DataType.Name.ASCII, StringCodec.asciiInstance);
39- primitiveCodecs.put(DataType.Name.BIGINT, LongCodec.instance);
40- primitiveCodecs.put(DataType.Name.BLOB, BytesCodec.instance);
41- primitiveCodecs.put(DataType.Name.BOOLEAN, BooleanCodec.instance);
42- primitiveCodecs.put(DataType.Name.COUNTER, LongCodec.instance);
43- primitiveCodecs.put(DataType.Name.DECIMAL, DecimalCodec.instance);
44- primitiveCodecs.put(DataType.Name.DOUBLE, DoubleCodec.instance);
45- primitiveCodecs.put(DataType.Name.FLOAT, FloatCodec.instance);
46- primitiveCodecs.put(DataType.Name.INET, InetCodec.instance);
47- primitiveCodecs.put(DataType.Name.INT, IntCodec.instance);
48- primitiveCodecs.put(DataType.Name.TEXT, StringCodec.utf8Instance);
39+ primitiveCodecs.put(DataType.Name.ASCII, StringCodec.asciiInstance);
40+ primitiveCodecs.put(DataType.Name.BIGINT, LongCodec.instance);
41+ primitiveCodecs.put(DataType.Name.BLOB, BytesCodec.instance);
42+ primitiveCodecs.put(DataType.Name.BOOLEAN, BooleanCodec.instance);
43+ primitiveCodecs.put(DataType.Name.COUNTER, LongCodec.instance);
44+ primitiveCodecs.put(DataType.Name.DECIMAL, DecimalCodec.instance);
45+ primitiveCodecs.put(DataType.Name.DOUBLE, DoubleCodec.instance);
46+ primitiveCodecs.put(DataType.Name.FLOAT, FloatCodec.instance);
47+ primitiveCodecs.put(DataType.Name.INET, InetCodec.instance);
48+ primitiveCodecs.put(DataType.Name.INT, IntCodec.instance);
49+ primitiveCodecs.put(DataType.Name.TEXT, StringCodec.utf8Instance);
4950 primitiveCodecs.put(DataType.Name.TIMESTAMP, DateCodec.instance);
50- primitiveCodecs.put(DataType.Name.UUID, UUIDCodec.instance);
51- primitiveCodecs.put(DataType.Name.VARCHAR, StringCodec.utf8Instance);
52- primitiveCodecs.put(DataType.Name.VARINT, BigIntegerCodec.instance);
53- primitiveCodecs.put(DataType.Name.TIMEUUID, TimeUUIDCodec.instance);
54- primitiveCodecs.put(DataType.Name.CUSTOM, BytesCodec.instance);
51+ primitiveCodecs.put(DataType.Name.UUID, UUIDCodec.instance);
52+ primitiveCodecs.put(DataType.Name.VARCHAR, StringCodec.utf8Instance);
53+ primitiveCodecs.put(DataType.Name.VARINT, BigIntegerCodec.instance);
54+ primitiveCodecs.put(DataType.Name.TIMEUUID, TimeUUIDCodec.instance);
55+ primitiveCodecs.put(DataType.Name.CUSTOM, BytesCodec.instance);
5556 }
5657
5758 private static final Map<DataType.Name, TypeCodec<List<?>>> primitiveListsCodecs = new EnumMap<DataType.Name, TypeCodec<List<?>>>(DataType.Name.class);
5859 private static final Map<DataType.Name, TypeCodec<Set<?>>> primitiveSetsCodecs = new EnumMap<DataType.Name, TypeCodec<Set<?>>>(DataType.Name.class);
5960 private static final Map<DataType.Name, Map<DataType.Name, TypeCodec<Map<?, ?>>>> primitiveMapsCodecs = new EnumMap<DataType.Name, Map<DataType.Name, TypeCodec<Map<?, ?>>>>(DataType.Name.class);
61+
6062 static {
6163 populatePrimitiveCollectionCodecs();
6264 }
6365
6466 @SuppressWarnings({"unchecked", "rawtypes"})
65- private static void populatePrimitiveCollectionCodecs()
66- {
67+ private static void populatePrimitiveCollectionCodecs() {
6768 for (Map.Entry<DataType.Name, TypeCodec<?>> entry : primitiveCodecs.entrySet()) {
6869 DataType.Name type = entry.getKey();
6970 TypeCodec<?> codec = entry.getValue();
@@ -76,34 +77,37 @@
7677 }
7778 }
7879
79- private TypeCodec() {}
80+ private TypeCodec() {
81+ }
8082
8183 public abstract T parse(String value);
84+
8285 public abstract String format(T value);
8386
8487 public abstract ByteBuffer serialize(T value);
88+
8589 public abstract T deserialize(ByteBuffer bytes);
8690
8791 @SuppressWarnings("unchecked")
8892 static <T> TypeCodec<T> createFor(DataType.Name name) {
8993 assert !name.isCollection();
90- return (TypeCodec<T>)primitiveCodecs.get(name);
94+ return (TypeCodec<T>) primitiveCodecs.get(name);
9195 }
9296
9397 @SuppressWarnings("unchecked")
9498 static <T> TypeCodec<List<T>> listOf(DataType arg) {
9599 TypeCodec<List<?>> codec = primitiveListsCodecs.get(arg.getName());
96100 return codec != null
97- ? (TypeCodec)codec
98- : new ListCodec<T>(TypeCodec.<T>createFor(arg.getName()));
101+ ? (TypeCodec) codec
102+ : new ListCodec<T>(TypeCodec.<T>createFor(arg.getName()));
99103 }
100104
101105 @SuppressWarnings("unchecked")
102106 static <T> TypeCodec<Set<T>> setOf(DataType arg) {
103107 TypeCodec<Set<?>> codec = primitiveSetsCodecs.get(arg.getName());
104108 return codec != null
105- ? (TypeCodec)codec
106- : new SetCodec<T>(TypeCodec.<T>createFor(arg.getName()));
109+ ? (TypeCodec) codec
110+ : new SetCodec<T>(TypeCodec.<T>createFor(arg.getName()));
107111 }
108112
109113 @SuppressWarnings("unchecked")
@@ -111,8 +115,8 @@
111115 Map<DataType.Name, TypeCodec<Map<?, ?>>> valueCodecs = primitiveMapsCodecs.get(keys.getName());
112116 TypeCodec<Map<?, ?>> codec = valueCodecs == null ? null : valueCodecs.get(values.getName());
113117 return codec != null
114- ? (TypeCodec)codec
115- : new MapCodec<K, V>(TypeCodec.<K>createFor(keys.getName()), TypeCodec.<V>createFor(values.getName()));
118+ ? (TypeCodec) codec
119+ : new MapCodec<K, V>(TypeCodec.<K>createFor(keys.getName()), TypeCodec.<V>createFor(values.getName()));
116120 }
117121
118122 /* This is ugly, but not sure how we can do much better/faster
@@ -163,7 +167,7 @@
163167 return DataType.uuid();
164168
165169 if (value instanceof List) {
166- List<?> l = (List<?>)value;
170+ List<?> l = (List<?>) value;
167171 if (l.isEmpty())
168172 return DataType.list(DataType.blob());
169173 DataType eltType = getDataTypeFor(l.get(0));
@@ -171,7 +175,7 @@
171175 }
172176
173177 if (value instanceof Set) {
174- Set<?> s = (Set<?>)value;
178+ Set<?> s = (Set<?>) value;
175179 if (s.isEmpty())
176180 return DataType.set(DataType.blob());
177181 DataType eltType = getDataTypeFor(s.iterator().next());
@@ -179,15 +183,15 @@
179183 }
180184
181185 if (value instanceof Map) {
182- Map<?, ?> m = (Map<?, ?>)value;
186+ Map<?, ?> m = (Map<?, ?>) value;
183187 if (m.isEmpty())
184188 return DataType.map(DataType.blob(), DataType.blob());
185189 Map.Entry<?, ?> e = m.entrySet().iterator().next();
186190 DataType keyType = getDataTypeFor(e.getKey());
187191 DataType valueType = getDataTypeFor(e.getValue());
188192 return keyType == null || valueType == null
189- ? null
190- : DataType.map(keyType, valueType);
193+ ? null
194+ : DataType.map(keyType, valueType);
191195 }
192196
193197 return null;
@@ -198,15 +202,15 @@
198202 if (elements > 65535)
199203 throw new IllegalArgumentException("Native protocol version 2 supports up to 65535 elements in any collection - but collection contains " + elements + " elements");
200204 ByteBuffer result = ByteBuffer.allocate(2 + size);
201- result.putShort((short)elements);
205+ result.putShort((short) elements);
202206 for (ByteBuffer bb : buffers) {
203207 int elemSize = bb.remaining();
204208 if (elemSize > 65535)
205209 throw new IllegalArgumentException("Native protocol version 2 supports only elements with size up to 65535 bytes - but element size is " + elemSize + " bytes");
206- result.putShort((short)elemSize);
210+ result.putShort((short) elemSize);
207211 result.put(bb.duplicate());
208212 }
209- return (ByteBuffer)result.flip();
213+ return (ByteBuffer) result.flip();
210214 }
211215
212216 // Utility method for collections
@@ -245,7 +249,7 @@
245249 int nbMatch = 0;
246250 int start = -1;
247251 do {
248- start = text.indexOf(search, start+1);
252+ start = text.indexOf(search, start + 1);
249253 if (start != -1)
250254 ++nbMatch;
251255 } while (start != -1);
@@ -283,7 +287,8 @@
283287
284288 public static final LongCodec instance = new LongCodec();
285289
286- private LongCodec() {}
290+ private LongCodec() {
291+ }
287292
288293 @Override
289294 public Long parse(String value) {
@@ -327,7 +332,8 @@
327332
328333 public static final BytesCodec instance = new BytesCodec();
329334
330- private BytesCodec() {}
335+ private BytesCodec() {
336+ }
331337
332338 @Override
333339 public ByteBuffer parse(String value) {
@@ -352,12 +358,13 @@
352358
353359 static class BooleanCodec extends TypeCodec<Boolean> {
354360
355- private static final ByteBuffer TRUE = ByteBuffer.wrap(new byte[] {1});
356- private static final ByteBuffer FALSE = ByteBuffer.wrap(new byte[] {0});
361+ private static final ByteBuffer TRUE = ByteBuffer.wrap(new byte[]{1});
362+ private static final ByteBuffer FALSE = ByteBuffer.wrap(new byte[]{0});
357363
358364 public static final BooleanCodec instance = new BooleanCodec();
359365
360- private BooleanCodec() {}
366+ private BooleanCodec() {
367+ }
361368
362369 @Override
363370 public Boolean parse(String value) {
@@ -400,7 +407,8 @@
400407
401408 public static final DecimalCodec instance = new DecimalCodec();
402409
403- private DecimalCodec() {}
410+ private DecimalCodec() {
411+ }
404412
405413 @Override
406414 public BigDecimal parse(String value) {
@@ -448,7 +456,8 @@
448456
449457 public static final DoubleCodec instance = new DoubleCodec();
450458
451- private DoubleCodec() {}
459+ private DoubleCodec() {
460+ }
452461
453462 @Override
454463 public Double parse(String value) {
@@ -492,7 +501,8 @@
492501
493502 public static final FloatCodec instance = new FloatCodec();
494503
495- private FloatCodec() {}
504+ private FloatCodec() {
505+ }
496506
497507 @Override
498508 public Float parse(String value) {
@@ -536,7 +546,8 @@
536546
537547 public static final InetCodec instance = new InetCodec();
538548
539- private InetCodec() {}
549+ private InetCodec() {
550+ }
540551
541552 @Override
542553 public InetAddress parse(String value) {
@@ -571,7 +582,8 @@
571582
572583 public static final IntCodec instance = new IntCodec();
573584
574- private IntCodec() {}
585+ private IntCodec() {
586+ }
575587
576588 @Override
577589 public Integer parse(String value) {
@@ -613,27 +625,28 @@
613625
614626 static class DateCodec extends TypeCodec<Date> {
615627
616- private static final String[] iso8601Patterns = new String[] {
617- "yyyy-MM-dd HH:mm",
618- "yyyy-MM-dd HH:mm:ss",
619- "yyyy-MM-dd HH:mmZ",
620- "yyyy-MM-dd HH:mm:ssZ",
621- "yyyy-MM-dd HH:mm:ss.SSS",
622- "yyyy-MM-dd HH:mm:ss.SSSZ",
623- "yyyy-MM-dd'T'HH:mm",
624- "yyyy-MM-dd'T'HH:mmZ",
625- "yyyy-MM-dd'T'HH:mm:ss",
626- "yyyy-MM-dd'T'HH:mm:ssZ",
627- "yyyy-MM-dd'T'HH:mm:ss.SSS",
628- "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
629- "yyyy-MM-dd",
630- "yyyy-MM-ddZ"
628+ private static final String[] iso8601Patterns = new String[]{
629+ "yyyy-MM-dd HH:mm",
630+ "yyyy-MM-dd HH:mm:ss",
631+ "yyyy-MM-dd HH:mmZ",
632+ "yyyy-MM-dd HH:mm:ssZ",
633+ "yyyy-MM-dd HH:mm:ss.SSS",
634+ "yyyy-MM-dd HH:mm:ss.SSSZ",
635+ "yyyy-MM-dd'T'HH:mm",
636+ "yyyy-MM-dd'T'HH:mmZ",
637+ "yyyy-MM-dd'T'HH:mm:ss",
638+ "yyyy-MM-dd'T'HH:mm:ssZ",
639+ "yyyy-MM-dd'T'HH:mm:ss.SSS",
640+ "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
641+ "yyyy-MM-dd",
642+ "yyyy-MM-ddZ"
631643 };
632644
633645 public static final DateCodec instance = new DateCodec();
634646 private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
635647
636- private DateCodec() {}
648+ private DateCodec() {
649+ }
637650
638651 /*
639652 * Copied and adapted from apache commons DateUtils.parseStrictly method (that is used Cassandra side
@@ -697,7 +710,8 @@
697710
698711 public static final UUIDCodec instance = new UUIDCodec();
699712
700- protected UUIDCodec() {}
713+ protected UUIDCodec() {
714+ }
701715
702716 @Override
703717 public UUID parse(String value) {
@@ -731,7 +745,8 @@
731745
732746 public static final TimeUUIDCodec instance = new TimeUUIDCodec();
733747
734- private TimeUUIDCodec() {}
748+ private TimeUUIDCodec() {
749+ }
735750
736751 @Override
737752 public UUID parse(String value) {
@@ -754,7 +769,8 @@
754769
755770 public static final BigIntegerCodec instance = new BigIntegerCodec();
756771
757- private BigIntegerCodec() {}
772+ private BigIntegerCodec() {
773+ }
758774
759775 @Override
760776 public BigInteger parse(String value) {
modified driver-core/src/main/java/com/datastax/driver/core/UnsupportedProtocolVersionException.java +1 −2
@@ -28,8 +28,7 @@
2828 public final InetSocketAddress address;
2929 public final int versionUnsupported;
3030
31- public UnsupportedProtocolVersionException(InetSocketAddress address, int versionUnsupported)
32- {
31+ public UnsupportedProtocolVersionException(InetSocketAddress address, int versionUnsupported) {
3332 super(String.format("[%s] Host %s does not support protocol version %d", address, address, versionUnsupported));
3433 this.address = address;
3534 this.versionUnsupported = versionUnsupported;
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 +29 −33
@@ -15,35 +15,31 @@
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;
25-import com.google.common.base.*;
20+import com.google.common.base.Joiner;
21+import com.google.common.base.Preconditions;
22+import com.google.common.base.Strings;
2623 import com.google.common.collect.AbstractIterator;
2724 import org.slf4j.Logger;
2825 import org.slf4j.LoggerFactory;
2926
30-import com.datastax.driver.core.Cluster;
31-import com.datastax.driver.core.Configuration;
32-import com.datastax.driver.core.ConsistencyLevel;
33-import com.datastax.driver.core.Host;
34-import com.datastax.driver.core.HostDistance;
35-import com.datastax.driver.core.Statement;
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;
3632
3733 /**
3834 * A data-center aware Round-robin load balancing policy.
39- * <p>
35+ * <p/>
4036 * This policy provides round-robin queries over the node of the local
4137 * data center. It also includes in the query plans returned a configurable
4238 * number of hosts in the remote data centers, but those are always tried
4339 * after the local nodes. In other words, this policy guarantees that no
4440 * host in a remote data center will be queried unless no host in the local
4541 * data center can be reached.
46- * <p>
42+ * <p/>
4743 * If used with a single data center, this policy is equivalent to the
4844 * {@link RoundRobinPolicy}, but its DC awareness incurs a slight overhead
4945 * so the latter should be preferred to this policy in that case.
@@ -160,16 +156,16 @@
160156
161157 @SuppressWarnings("unchecked")
162158 private static CopyOnWriteArrayList<Host> cloneList(CopyOnWriteArrayList<Host> list) {
163- return (CopyOnWriteArrayList<Host>)list.clone();
159+ return (CopyOnWriteArrayList<Host>) list.clone();
164160 }
165161
166162 /**
167163 * Return the HostDistance for the provided host.
168- * <p>
164+ * <p/>
169165 * This policy consider nodes in the local datacenter as {@code LOCAL}.
170166 * For each remote datacenter, it considers a configurable number of
171167 * hosts as {@code REMOTE} and the rest is {@code IGNORED}.
172- * <p>
168+ * <p/>
173169 * To configure how many host in each remote datacenter is considered
174170 * {@code REMOTE}, see {@link #DCAwareRoundRobinPolicy(String, int)}.
175171 *
@@ -189,13 +185,13 @@
189185 // We need to clone, otherwise our subList call is not thread safe
190186 dcHosts = cloneList(dcHosts);
191187 return dcHosts.subList(0, Math.min(dcHosts.size(), usedHostsPerRemoteDc)).contains(host)
192- ? HostDistance.REMOTE
193- : HostDistance.IGNORED;
188+ ? HostDistance.REMOTE
189+ : HostDistance.IGNORED;
194190 }
195191
196192 /**
197193 * Returns the hosts to use for a new query.
198- * <p>
194+ * <p/>
199195 * The returned plan will always try each known host in the local
200196 * datacenter first, and then, if none of the local host is reachable,
201197 * will try up to a configurable number of other host per remote datacenter.
@@ -203,8 +199,8 @@
203199 * Round-robin algorithm.
204200 *
205201 * @param loggedKeyspace the keyspace currently logged in on for this
206- * query.
207- * @param statement the query for which to build the plan.
202+ * query.
203+ * @param statement the query for which to build the plan.
208204 * @return a new query plan, i.e. an iterator indicating which host to
209205 * try first for querying, which one to use as failover, etc...
210206 */
@@ -247,8 +243,8 @@
247243 }
248244
249245 ConsistencyLevel cl = statement.getConsistencyLevel() == null
250- ? configuration.getQueryOptions().getConsistencyLevel()
251- : statement.getConsistencyLevel();
246+ ? configuration.getQueryOptions().getConsistencyLevel()
247+ : statement.getConsistencyLevel();
252248
253249 if (dontHopForLocalCL && cl.isDCLocal())
254250 return endOfData();
@@ -333,10 +329,10 @@
333329
334330 /**
335331 * Sets the name of the datacenter that will be considered "local" by the policy.
336- * <p>
332+ * <p/>
337333 * This must be the name as known by Cassandra (in other words, the name in that appears in
338334 * {@code system.peers}, or in the output of admin tools like nodetool).
339- * <p>
335+ * <p/>
340336 * If this method isn't called, the policy will default to the datacenter of the first node
341337 * connected to. This will always be ok if all the contact points use at {@code Cluster}
342338 * creation are in the local data-center. Otherwise, you should provide the name yourself
@@ -347,24 +343,24 @@
347343 */
348344 public Builder withLocalDc(String localDc) {
349345 Preconditions.checkArgument(!Strings.isNullOrEmpty(localDc),
350- "localDc name can't be null or empty. If you want to let the policy autodetect the datacenter, don't call Builder.withLocalDC");
346+ "localDc name can't be null or empty. If you want to let the policy autodetect the datacenter, don't call Builder.withLocalDC");
351347 this.localDc = localDc;
352348 return this;
353349 }
354350
355351 /**
356352 * Sets the number of hosts per remote datacenter that the policy should consider.
357- * <p>
353+ * <p/>
358354 * The policy's {@code distance()} method will return a {@code HostDistance.REMOTE} distance for only {@code usedHostsPerRemoteDc}
359355 * hosts per remote datacenter. Other hosts of the remote datacenters will be ignored (and thus no connections to them will be
360356 * maintained).
361- * <p>
357+ * <p/>
362358 * If {@code usedHostsPerRemoteDc > 0}, then if for a query no host in the local datacenter can be reached and if the consistency
363359 * level of the query is not {@code LOCAL_ONE} or {@code LOCAL_QUORUM}, then up to {@code usedHostsPerRemoteDc} hosts per remote
364360 * datacenter will be tried by the policy as a fallback. By default, no remote host will be used for {@code LOCAL_ONE} and
365361 * {@code LOCAL_QUORUM}, since this would change the meaning of the consistency level, somewhat breaking the consistency contract
366362 * (this can be overridden with {@link #allowRemoteDCsForLocalConsistencyLevel()}).
367- * <p>
363+ * <p/>
368364 * If this method isn't called, the policy will default to 0.
369365 *
370366 * @param usedHostsPerRemoteDc the number.
@@ -372,7 +368,7 @@
372368 */
373369 public Builder withUsedHostsPerRemoteDc(int usedHostsPerRemoteDc) {
374370 Preconditions.checkArgument(usedHostsPerRemoteDc >= 0,
375- "usedHostsPerRemoteDc must be equal or greater than 0");
371+ "usedHostsPerRemoteDc must be equal or greater than 0");
376372 this.usedHostsPerRemoteDc = usedHostsPerRemoteDc;
377373 return this;
378374 }
@@ -380,7 +376,7 @@
380376 /**
381377 * Allows the policy to return remote hosts when building query plans for queries having consistency level {@code LOCAL_ONE}
382378 * or {@code LOCAL_QUORUM}.
383- * <p>
379+ * <p/>
384380 * When used in conjunction with {@link #withUsedHostsPerRemoteDc(int) usedHostsPerRemoteDc} > 0, this overrides the policy of
385381 * never using remote datacenter nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is however inadvisable to do
386382 * 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} types, 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 +17 −17
@@ -33,17 +33,17 @@
3333
3434 public Policies() {
3535 this(defaultLoadBalancingPolicy(), defaultReconnectionPolicy(), defaultRetryPolicy(),
36- defaultAddressTranslater(), defaultSpeculativeExecutionPolicy());
36+ defaultAddressTranslater(), defaultSpeculativeExecutionPolicy());
3737 }
3838
3939 /**
4040 * Creates a new {@code Policies} object using the provided policies.
41- * <p>
41+ * <p/>
4242 * This constructor use the default {@link IdentityTranslater}.
4343 *
4444 * @param loadBalancingPolicy the load balancing policy to use.
45- * @param reconnectionPolicy the reconnection policy to use.
46- * @param retryPolicy the retry policy to use.
45+ * @param reconnectionPolicy the reconnection policy to use.
46+ * @param retryPolicy the retry policy to use.
4747 */
4848 public Policies(LoadBalancingPolicy loadBalancingPolicy,
4949 ReconnectionPolicy reconnectionPolicy,
@@ -56,9 +56,9 @@
5656 * Creates a new {@code Policies} object using the provided policies.
5757 *
5858 * @param loadBalancingPolicy the load balancing policy to use.
59- * @param reconnectionPolicy the reconnection policy to use.
60- * @param retryPolicy the retry policy to use.
61- * @param addressTranslater the address translater to use.
59+ * @param reconnectionPolicy the reconnection policy to use.
60+ * @param retryPolicy the retry policy to use.
61+ * @param addressTranslater the address translater to use.
6262 */
6363 public Policies(LoadBalancingPolicy loadBalancingPolicy,
6464 ReconnectionPolicy reconnectionPolicy,
@@ -74,12 +74,12 @@
7474
7575 /**
7676 * The default load balancing policy.
77- * <p>
77+ * <p/>
7878 * The default load balancing policy is {@link DCAwareRoundRobinPolicy} with token
7979 * awareness (so {@code new TokenAwarePolicy(new DCAwareRoundRobinPolicy())}).
80- * <p>
80+ * <p/>
8181 * Note that this policy shuffles the replicas when token awareness is used, see
82- * {@link TokenAwarePolicy#TokenAwarePolicy(LoadBalancingPolicy,boolean)} for an
82+ * {@link TokenAwarePolicy#TokenAwarePolicy(LoadBalancingPolicy, boolean)} for an
8383 * explanation of the tradeoffs.
8484 *
8585 * @return the default load balancing policy.
@@ -92,7 +92,7 @@
9292
9393 /**
9494 * The default reconnection policy.
95- * <p>
95+ * <p/>
9696 * The default reconnection policy is an {@link ExponentialReconnectionPolicy}
9797 * where the base delay is 1 second and the max delay is 10 minutes;
9898 *
@@ -104,7 +104,7 @@
104104
105105 /**
106106 * The default retry policy.
107- * <p>
107+ * <p/>
108108 * The default retry policy is {@link DefaultRetryPolicy}.
109109 *
110110 * @return the default retry policy.
@@ -115,7 +115,7 @@
115115
116116 /**
117117 * The default address translater.
118- * <p>
118+ * <p/>
119119 * The default address translater is {@link IdentityTranslater}.
120120 *
121121 * @return the default address translater.
@@ -126,7 +126,7 @@
126126
127127 /**
128128 * The default speculative retry policy.
129- * <p>
129+ * <p/>
130130 * The default speculative retry policy is a {@link NoSpeculativeExecutionPolicy}.
131131 *
132132 * @return the default speculative retry policy.
@@ -137,7 +137,7 @@
137137
138138 /**
139139 * The load balancing policy in use.
140- * <p>
140+ * <p/>
141141 * The load balancing policy defines how Cassandra hosts are picked for queries.
142142 *
143143 * @return the load balancing policy in use.
@@ -148,7 +148,7 @@
148148
149149 /**
150150 * The reconnection policy in use.
151- * <p>
151+ * <p/>
152152 * The reconnection policy defines how often the driver tries to reconnect to a dead node.
153153 *
154154 * @return the reconnection policy in use.
@@ -159,7 +159,7 @@
159159
160160 /**
161161 * The retry policy in use.
162- * <p>
162+ * <p/>
163163 * The retry policy defines in which conditions a query should be
164164 * automatically retries by the driver.
165165 *
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
@@ -64,8 +64,8 @@
6464
6565 CounterAssignment(String name, Object value, boolean isIncr) {
6666 super(name);
67- if (!isIncr && value instanceof Long && ((Long)value) < 0) {
68- this.value = -((Long)value);
67+ if (!isIncr && value instanceof Long && ((Long) value) < 0) {
68+ this.value = -((Long) value);
6969 this.isIncr = true;
7070 } else {
7171 this.value = value;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +13 −19
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.RegularStatement;
19+
1820 import java.nio.ByteBuffer;
1921 import java.util.ArrayList;
20-import java.util.Collections;
2122 import java.util.List;
2223
23-import com.datastax.driver.core.RegularStatement;
24-
2524 /**
2625 * A built BATCH statement.
2726 */
@@ -36,10 +35,10 @@
3635 private int nonBuiltStatementValues;
3736
3837 Batch(RegularStatement[] statements, boolean logged) {
39- super((String)null);
38+ super((String) null);
4039 this.statements = statements.length == 0
41- ? new ArrayList<RegularStatement>()
42- : new ArrayList<RegularStatement>(statements.length);
40+ ? new ArrayList<RegularStatement>()
41+ : new ArrayList<RegularStatement>(statements.length);
4342 this.logged = logged;
4443 this.usings = new Options(this);
4544
@@ -52,8 +51,8 @@
5251 StringBuilder builder = new StringBuilder();
5352
5453 builder.append(isCounterOp()
55- ? "BEGIN COUNTER BATCH"
56- : (logged ? "BEGIN BATCH" : "BEGIN UNLOGGED BATCH"));
54+ ? "BEGIN COUNTER BATCH"
55+ : (logged ? "BEGIN BATCH" : "BEGIN UNLOGGED BATCH"));
5756
5857 if (!usings.usings.isEmpty()) {
5958 builder.append(" USING ");
@@ -64,7 +63,7 @@
6463 for (int i = 0; i < statements.size(); i++) {
6564 RegularStatement stmt = statements.get(i);
6665 if (stmt instanceof BuiltStatement) {
67- BuiltStatement bst = (BuiltStatement)stmt;
66+ BuiltStatement bst = (BuiltStatement) stmt;
6867 builder.append(maybeAddSemicolon(bst.buildQueryString(variables)));
6968
7069 } else {
@@ -87,9 +86,8 @@
8786 *
8887 * @param statement the new statement to add.
8988 * @return this batch.
90- *
9189 * @throws IllegalArgumentException if counter and non-counter operations
92- * are mixed.
90+ * are mixed.
9391 */
9492 public Batch add(RegularStatement statement) {
9593 boolean isCounterOp = statement instanceof BuiltStatement && ((BuiltStatement) statement).isCounterOp();
@@ -101,12 +99,9 @@
10199
102100 this.statements.add(statement);
103101
104- if (statement instanceof BuiltStatement)
105- {
106- this.hasBindMarkers |= ((BuiltStatement)statement).hasBindMarkers;
107- }
108- else
109- {
102+ if (statement instanceof BuiltStatement) {
103+ this.hasBindMarkers |= ((BuiltStatement) statement).hasBindMarkers;
104+ } else {
110105 // For non-BuiltStatement, we cannot know if it includes a bind makers and we assume it does. In practice,
111106 // this means we will always serialize values as strings when there is non-BuiltStatement
112107 this.hasBindMarkers = true;
@@ -134,8 +129,7 @@
134129
135130 ByteBuffer[] values = new ByteBuffer[nonBuiltStatementValues];
136131 int i = 0;
137- for (RegularStatement statement : statements)
138- {
132+ for (RegularStatement statement : statements) {
139133 if (statement instanceof BuiltStatement)
140134 continue;
141135
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 +11 −13
@@ -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) {
@@ -182,8 +181,8 @@
182181 return null;
183182
184183 return routingKey.length == 1
185- ? routingKey[0]
186- : compose(routingKey);
184+ ? routingKey[0]
185+ : compose(routingKey);
187186 }
188187
189188 @Override
@@ -217,7 +216,7 @@
217216
218217 /**
219218 * Allows to force this builder to not generate values (through its {@code getValues()} method).
220- * <p>
219+ * <p/>
221220 * By default (and unless the protocol version 1 is in use, see below) and
222221 * for performance reasons, the query builder will not serialize all values
223222 * provided to strings. This means that the {@link #getQueryString} may
@@ -230,13 +229,13 @@
230229 * return {@code null} and that the string returned by {@code
231230 * getQueryString()} will contain no other bind markers than the one
232231 * inputted by the user.
233- * <p>
232+ * <p/>
234233 * If the native protocol version 1 is in use, the driver will default
235234 * to not generating values since those are not supported by that version of
236235 * the protocol. In practice, the driver will automatically call this method
237236 * with {@code true} as argument prior to execution. Hence, calling this
238237 * method when the protocol version 1 is in use is basically a no-op.
239- * <p>
238+ * <p/>
240239 * Note that this method is mainly useful for debugging purpose. In general,
241240 * the default behavior should be the correct and most efficient one.
242241 *
@@ -256,8 +255,7 @@
256255 totalLength += 2 + bb.remaining() + 1;
257256
258257 ByteBuffer out = ByteBuffer.allocate(totalLength);
259- for (ByteBuffer buffer : buffers)
260- {
258+ for (ByteBuffer buffer : buffers) {
261259 ByteBuffer bb = buffer.duplicate();
262260 putShortLength(out, bb.remaining());
263261 out.put(bb);
@@ -280,7 +278,7 @@
280278 T statement;
281279
282280 ForwardingStatement(T statement) {
283- super((String)null);
281+ super((String) null);
284282 this.statement = statement;
285283 }
286284
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.
@@ -138,7 +138,7 @@
138138
139139 /**
140140 * Sets the 'IF EXISTS' option for this DELETE statement.
141- *
141+ * <p/>
142142 * <p>
143143 * A delete with that option will report whether the statement actually
144144 * resulted in data being deleted. The existence check and deletion are
@@ -174,8 +174,7 @@
174174 * @param clause the clause to add.
175175 * @return this WHERE clause.
176176 */
177- public Where and(Clause clause)
178- {
177+ public Where and(Clause clause) {
179178 clauses.add(clause);
180179 statement.maybeAddRoutingKey(clause.name(), clause.firstValue());
181180 checkForBindMarkers(clause);
@@ -195,7 +194,7 @@
195194 /**
196195 * Sets the 'IF EXISTS' option for the DELETE statement this WHERE clause
197196 * is part of.
198- *
197+ * <p/>
199198 * <p>
200199 * A delete with that option will report whether the statement actually
201200 * resulted in data being deleted. The existence check and deletion are
@@ -288,7 +287,7 @@
288287 * Adds the table to delete from.
289288 *
290289 * @param keyspace the name of the keyspace to delete from.
291- * @param table the name of the table to delete from.
290+ * @param table the name of the table to delete from.
292291 * @return a newly built DELETE statement that deletes from {@code keyspace.table}.
293292 */
294293 public Delete from(String keyspace, String table) {
@@ -315,7 +314,6 @@
315314 * Deletes all columns (i.e. "DELETE FROM ...")
316315 *
317316 * @return an in-build DELETE statement.
318- *
319317 * @throws IllegalStateException if some columns had already been selected for this builder.
320318 */
321319 public Builder all() {
@@ -340,7 +338,7 @@
340338 * Deletes the provided list element.
341339 *
342340 * @param columnName the name of the list column.
343- * @param idx the index of the element to delete.
341+ * @param idx the index of the element to delete.
344342 * @return this in-build DELETE Selection
345343 */
346344 public Selection listElt(String columnName, int idx) {
@@ -353,7 +351,7 @@
353351 * specified as a bind marker.
354352 *
355353 * @param columnName the name of the list column.
356- * @param idx the index of the element to delete.
354+ * @param idx the index of the element to delete.
357355 * @return this in-build DELETE Selection
358356 */
359357 public Selection listElt(String columnName, BindMarker idx) {
@@ -365,7 +363,7 @@
365363 * Deletes the provided set element.
366364 *
367365 * @param columnName the name of the set column.
368- * @param element the element to delete.
366+ * @param element the element to delete.
369367 * @return this in-build DELETE Selection
370368 */
371369 public Selection setElt(String columnName, Object element) {
@@ -378,7 +376,7 @@
378376 * specified as a bind marker.
379377 *
380378 * @param columnName the name of the set column.
381- * @param element the element to delete.
379+ * @param element the element to delete.
382380 * @return this in-build DELETE Selection
383381 */
384382 public Selection setElt(String columnName, BindMarker element) {
@@ -390,7 +388,7 @@
390388 * Deletes a map element given a key.
391389 *
392390 * @param columnName the name of the map column.
393- * @param key the key for the element to delete.
391+ * @param key the key for the element to delete.
394392 * @return this in-build DELETE Selection
395393 */
396394 public Selection mapElt(String columnName, Object key) {
@@ -478,7 +476,7 @@
478476
479477 /**
480478 * Adds the provided condition for the deletion.
481- * <p>
479+ * <p/>
482480 * Note that while the query builder accept any type of {@code Clause}
483481 * as conditions, Cassandra currently only allows equality ones.
484482 *
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +15 −17
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
18+import com.datastax.driver.core.TableMetadata;
19+
1920 import java.util.ArrayList;
2021 import java.util.Arrays;
2122 import java.util.List;
2223
23-import com.datastax.driver.core.TableMetadata;
24-
2524 /**
2625 * A built INSERT statement.
2726 */
@@ -72,7 +71,7 @@
7271 /**
7372 * Adds a column/value pair to the values inserted by this INSERT statement.
7473 *
75- * @param name the name of the column to insert/update.
74+ * @param name the name of the column to insert/update.
7675 * @param value the value to insert/update for {@code name}.
7776 * @return this INSERT statement.
7877 */
@@ -89,10 +88,10 @@
8988 /**
9089 * Adds multiple column/value pairs to the values inserted by this INSERT statement.
9190 *
92- * @param names a list of column names to insert/update.
91+ * @param names a list of column names to insert/update.
9392 * @param values a list of values to insert/update. The {@code i}th
94- * value in {@code values} will be inserted for the {@code i}th column
95- * in {@code names}.
93+ * value in {@code values} will be inserted for the {@code i}th column
94+ * in {@code names}.
9695 * @return this INSERT statement.
9796 * @throws IllegalArgumentException if {@code names.length != values.length}.
9897 */
@@ -103,10 +102,10 @@
103102 /**
104103 * Adds multiple column/value pairs to the values inserted by this INSERT statement.
105104 *
106- * @param names a list of column names to insert/update.
105+ * @param names a list of column names to insert/update.
107106 * @param values a list of values to insert/update. The {@code i}th
108- * value in {@code values} will be inserted for the {@code i}th column
109- * in {@code names}.
107+ * value in {@code values} will be inserted for the {@code i}th column
108+ * in {@code names}.
110109 * @return this INSERT statement.
111110 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
112111 */
@@ -137,13 +136,13 @@
137136
138137 /**
139138 * Sets the 'IF NOT EXISTS' option for this INSERT statement.
140- * <p>
139+ * <p/>
141140 * An insert with that option will not succeed unless the row does not
142141 * exist at the time the insertion is executed. The existence check and
143142 * insertions are done transactionally in the sense that if multiple
144143 * clients attempt to create a given row with this option, then at most one
145144 * may succeed.
146- * <p>
145+ * <p/>
147146 * Please keep in mind that using this option has a non negligible
148147 * performance impact and should be avoided when possible.
149148 *
@@ -180,7 +179,7 @@
180179 /**
181180 * Adds a column/value pair to the values inserted by this INSERT statement.
182181 *
183- * @param name the name of the column to insert/update.
182+ * @param name the name of the column to insert/update.
184183 * @param value the value to insert/update for {@code name}.
185184 * @return the INSERT statement those options are part of.
186185 */
@@ -191,12 +190,11 @@
191190 /**
192191 * Adds multiple column/value pairs to the values inserted by this INSERT statement.
193192 *
194- * @param names a list of column names to insert/update.
193+ * @param names a list of column names to insert/update.
195194 * @param values a list of values to insert/update. The {@code i}th
196- * value in {@code values} will be inserted for the {@code i}th column
197- * in {@code names}.
195+ * value in {@code values} will be inserted for the {@code i}th column
196+ * in {@code names}.
198197 * @return the INSERT statement those options are part of.
199- *
200198 * @throws IllegalArgumentException if {@code names.length != values.length}.
201199 */
202200 public Insert values(String[] names, Object[] values) {
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java +0 −1
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.List;
2019
2120 public class Ordering extends Utils.Appendeable {
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +101 −106
@@ -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 provider 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 "lesser than" where clause stating the provided column must be less than
301302 * the provided value.
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 */
@@ -310,16 +311,15 @@
310311
311312 /**
312313 * Creates a "lesser than" where clause for a group of clustering columns.
313- * <p>
314+ * <p/>
314315 * For instance, {@code lt(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
315316 * will generate the CQL WHERE clause {@code (a, b) &lt; (2, 'test') }.
316- * <p>
317+ * <p/>
317318 * Please note that this variant is only supported starting with Cassandra 2.0.6.
318319 *
319- * @param names the column names
320+ * @param names the column names
320321 * @param values the values
321322 * @return the corresponding where clause.
322- *
323323 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
324324 */
325325 public static Clause lt(List<String> names, List<?> values) {
@@ -333,7 +333,7 @@
333333 * Creates a "lesser than or equal" where clause stating the provided column must
334334 * be lesser than or equal to the provided value.
335335 *
336- * @param name the column name
336+ * @param name the column name
337337 * @param value the value
338338 * @return the corresponding where clause.
339339 */
@@ -343,16 +343,15 @@
343343
344344 /**
345345 * Creates a "lesser than or equal" where clause for a group of clustering columns.
346- * <p>
346+ * <p/>
347347 * For instance, {@code lte(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
348348 * will generate the CQL WHERE clause {@code (a, b) &lte; (2, 'test') }.
349- * <p>
349+ * <p/>
350350 * Please note that this variant is only supported starting with Cassandra 2.0.6.
351351 *
352- * @param names the column names
352+ * @param names the column names
353353 * @param values the values
354354 * @return the corresponding where clause.
355- *
356355 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
357356 */
358357 public static Clause lte(List<String> names, List<?> values) {
@@ -366,7 +365,7 @@
366365 * Creates a "greater than" where clause stating the provided column must
367366 * be greater to the provided value.
368367 *
369- * @param name the column name
368+ * @param name the column name
370369 * @param value the value
371370 * @return the corresponding where clause.
372371 */
@@ -376,16 +375,15 @@
376375
377376 /**
378377 * Creates a "greater than" where clause for a group of clustering columns.
379- * <p>
378+ * <p/>
380379 * For instance, {@code gt(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
381380 * will generate the CQL WHERE clause {@code (a, b) &gt; (2, 'test') }.
382- * <p>
381+ * <p/>
383382 * Please note that this variant is only supported starting with Cassandra 2.0.6.
384383 *
385- * @param names the column names
384+ * @param names the column names
386385 * @param values the values
387386 * @return the corresponding where clause.
388- *
389387 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
390388 */
391389 public static Clause gt(List<String> names, List<?> values) {
@@ -399,7 +397,7 @@
399397 * Creates a "greater than or equal" where clause stating the provided
400398 * column must be greater than or equal to the provided value.
401399 *
402- * @param name the column name
400+ * @param name the column name
403401 * @param value the value
404402 * @return the corresponding where clause.
405403 */
@@ -409,16 +407,15 @@
409407
410408 /**
411409 * Creates a "greater than or equal" where clause for a group of clustering columns.
412- * <p>
410+ * <p/>
413411 * For instance, {@code gte(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
414412 * will generate the CQL WHERE clause {@code (a, b) &gte; (2, 'test') }.
415- * <p>
413+ * <p/>
416414 * Please note that this variant is only supported starting with Cassandra 2.0.6.
417415 *
418- * @param names the column names
416+ * @param names the column names
419417 * @param values the values
420418 * @return the corresponding where clause.
421- *
422419 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
423420 */
424421 public static Clause gte(List<String> names, List<?> values) {
@@ -453,7 +450,6 @@
453450 *
454451 * @param timestamp the timestamp (in microseconds) to use.
455452 * @return the corresponding option
456- *
457453 * @throws IllegalArgumentException if {@code timestamp &gt; 0}.
458454 */
459455 public static Using timestamp(long timestamp) {
@@ -478,7 +474,6 @@
478474 *
479475 * @param ttl the ttl (in seconds) to use.
480476 * @return the corresponding option
481- *
482477 * @throws IllegalArgumentException if {@code ttl &gt; 0}.
483478 */
484479 public static Using ttl(int ttl) {
@@ -500,10 +495,10 @@
500495
501496 /**
502497 * Simple "set" assignment of a value to a column.
503- * <p>
498+ * <p/>
504499 * This will generate: {@code name = value}.
505500 *
506- * @param name the column name
501+ * @param name the column name
507502 * @param value the value to assign
508503 * @return the correspond assignment (to use in an update query)
509504 */
@@ -513,7 +508,7 @@
513508
514509 /**
515510 * Incrementation of a counter column.
516- * <p>
511+ * <p/>
517512 * This will generate: {@code name = name + 1}.
518513 *
519514 * @param name the column name to increment
@@ -525,10 +520,10 @@
525520
526521 /**
527522 * Incrementation of a counter column by a provided value.
528- * <p>
523+ * <p/>
529524 * This will generate: {@code name = name + value}.
530525 *
531- * @param name the column name to increment
526+ * @param name the column name to increment
532527 * @param value the value by which to increment
533528 * @return the correspond assignment (to use in an update query)
534529 */
@@ -538,10 +533,10 @@
538533
539534 /**
540535 * Incrementation of a counter column by a provided value.
541- * <p>
536+ * <p/>
542537 * This will generate: {@code name = name + value}.
543538 *
544- * @param name the column name to increment
539+ * @param name the column name to increment
545540 * @param value a bind marker representing the value by which to increment
546541 * @return the correspond assignment (to use in an update query)
547542 */
@@ -551,7 +546,7 @@
551546
552547 /**
553548 * Decrementation of a counter column.
554- * <p>
549+ * <p/>
555550 * This will generate: {@code name = name - 1}.
556551 *
557552 * @param name the column name to decrement
@@ -563,10 +558,10 @@
563558
564559 /**
565560 * Decrementation of a counter column by a provided value.
566- * <p>
561+ * <p/>
567562 * This will generate: {@code name = name - value}.
568563 *
569- * @param name the column name to decrement
564+ * @param name the column name to decrement
570565 * @param value the value by which to decrement
571566 * @return the correspond assignment (to use in an update query)
572567 */
@@ -576,10 +571,10 @@
576571
577572 /**
578573 * Decrementation of a counter column by a provided value.
579- * <p>
574+ * <p/>
580575 * This will generate: {@code name = name - value}.
581576 *
582- * @param name the column name to decrement
577+ * @param name the column name to decrement
583578 * @param value a bind marker representing the value by which to decrement
584579 * @return the correspond assignment (to use in an update query)
585580 */
@@ -589,10 +584,10 @@
589584
590585 /**
591586 * Prepend a value to a list column.
592- * <p>
587+ * <p/>
593588 * This will generate: {@code name = [ value ] + name}.
594589 *
595- * @param name the column name (must be of type list).
590+ * @param name the column name (must be of type list).
596591 * @param value the value to prepend. Using a BindMarker here is not supported.
597592 * To use a BindMarker use {@code QueryBuilder#prependAll} with a
598593 * singleton list.
@@ -607,7 +602,7 @@
607602
608603 /**
609604 * Prepend a list of values to a list column.
610- * <p>
605+ * <p/>
611606 * This will generate: {@code name = list + name}.
612607 *
613608 * @param name the column name (must be of type list).
@@ -620,7 +615,7 @@
620615
621616 /**
622617 * Prepend a list of values to a list column.
623- * <p>
618+ * <p/>
624619 * This will generate: {@code name = list + name}.
625620 *
626621 * @param name the column name (must be of type list).
@@ -633,10 +628,10 @@
633628
634629 /**
635630 * Append a value to a list column.
636- * <p>
631+ * <p/>
637632 * This will generate: {@code name = name + [value]}.
638633 *
639- * @param name the column name (must be of type list).
634+ * @param name the column name (must be of type list).
640635 * @param value the value to append. Using a BindMarker here is not supported.
641636 * To use a BindMarker use {@code QueryBuilder#appendAll} with a
642637 * singleton list.
@@ -651,7 +646,7 @@
651646
652647 /**
653648 * Append a list of values to a list column.
654- * <p>
649+ * <p/>
655650 * This will generate: {@code name = name + list}.
656651 *
657652 * @param name the column name (must be of type list).
@@ -664,7 +659,7 @@
664659
665660 /**
666661 * Append a list of values to a list column.
667- * <p>
662+ * <p/>
668663 * This will generate: {@code name = name + list}.
669664 *
670665 * @param name the column name (must be of type list).
@@ -677,10 +672,10 @@
677672
678673 /**
679674 * Discard a value from a list column.
680- * <p>
675+ * <p/>
681676 * This will generate: {@code name = name - [value]}.
682677 *
683- * @param name the column name (must be of type list).
678+ * @param name the column name (must be of type list).
684679 * @param value the value to discard. Using a BindMarker here is not supported.
685680 * To use a BindMarker use {@code QueryBuilder#discardAll} with a singleton list.
686681 * @return the correspond assignment (to use in an update query)
@@ -694,7 +689,7 @@
694689
695690 /**
696691 * Discard a list of values to a list column.
697- * <p>
692+ * <p/>
698693 * This will generate: {@code name = name - list}.
699694 *
700695 * @param name the column name (must be of type list).
@@ -707,7 +702,7 @@
707702
708703 /**
709704 * Discard a list of values to a list column.
710- * <p>
705+ * <p/>
711706 * This will generate: {@code name = name - list}.
712707 *
713708 * @param name the column name (must be of type list).
@@ -720,11 +715,11 @@
720715
721716 /**
722717 * Sets a list column value by index.
723- * <p>
718+ * <p/>
724719 * This will generate: {@code name[idx] = value}.
725720 *
726- * @param name the column name (must be of type list).
727- * @param idx the index to set
721+ * @param name the column name (must be of type list).
722+ * @param idx the index to set
728723 * @param value the value to set
729724 * @return the correspond assignment (to use in an update query)
730725 */
@@ -734,17 +729,17 @@
734729
735730 /**
736731 * Adds a value to a set column.
737- * <p>
732+ * <p/>
738733 * This will generate: {@code name = name + {value}}.
739734 *
740- * @param name the column name (must be of type set).
735+ * @param name the column name (must be of type set).
741736 * @param value the value to add. Using a BindMarker here is not supported.
742737 * To use a BindMarker use {@code QueryBuilder#addAll} with a
743738 * singleton set.
744739 * @return the correspond assignment (to use in an update query)
745740 */
746741 public static Assignment add(String name, Object value) {
747- if (value instanceof BindMarker){
742+ if (value instanceof BindMarker) {
748743 throw new InvalidQueryException("Binding a value in add() is not supported, use addAll() and bind a singleton list");
749744 }
750745 return addAll(name, Collections.singleton(value));
@@ -752,11 +747,11 @@
752747
753748 /**
754749 * Adds a set of values to a set column.
755- * <p>
750+ * <p/>
756751 * This will generate: {@code name = name + set}.
757752 *
758753 * @param name the column name (must be of type set).
759- * @param set the set of values to append
754+ * @param set the set of values to append
760755 * @return the correspond assignment (to use in an update query)
761756 */
762757 public static Assignment addAll(String name, Set<?> set) {
@@ -765,11 +760,11 @@
765760
766761 /**
767762 * Adds a set of values to a set column.
768- * <p>
763+ * <p/>
769764 * This will generate: {@code name = name + set}.
770765 *
771766 * @param name the column name (must be of type set).
772- * @param set a bind marker representing the set of values to append
767+ * @param set a bind marker representing the set of values to append
773768 * @return the correspond assignment (to use in an update query)
774769 */
775770 public static Assignment addAll(String name, BindMarker set) {
@@ -778,10 +773,10 @@
778773
779774 /**
780775 * Remove a value from a set column.
781- * <p>
776+ * <p/>
782777 * This will generate: {@code name = name - {value}}.
783778 *
784- * @param name the column name (must be of type set).
779+ * @param name the column name (must be of type set).
785780 * @param value the value to remove. Using a BindMarker here is not supported.
786781 * To use a BindMarker use {@code QueryBuilder#removeAll} with a singleton set.
787782 * @return the correspond assignment (to use in an update query)
@@ -795,11 +790,11 @@
795790
796791 /**
797792 * Remove a set of values from a set column.
798- * <p>
793+ * <p/>
799794 * This will generate: {@code name = name - set}.
800795 *
801796 * @param name the column name (must be of type set).
802- * @param set the set of values to remove
797+ * @param set the set of values to remove
803798 * @return the correspond assignment (to use in an update query)
804799 */
805800 public static Assignment removeAll(String name, Set<?> set) {
@@ -808,11 +803,11 @@
808803
809804 /**
810805 * Remove a set of values from a set column.
811- * <p>
806+ * <p/>
812807 * This will generate: {@code name = name - set}.
813808 *
814809 * @param name the column name (must be of type set).
815- * @param set a bind marker representing the set of values to remove
810+ * @param set a bind marker representing the set of values to remove
816811 * @return the correspond assignment (to use in an update query)
817812 */
818813 public static Assignment removeAll(String name, BindMarker set) {
@@ -821,11 +816,11 @@
821816
822817 /**
823818 * Puts a new key/value pair to a map column.
824- * <p>
819+ * <p/>
825820 * This will generate: {@code name[key] = value}.
826821 *
827- * @param name the column name (must be of type map).
828- * @param key the key to put
822+ * @param name the column name (must be of type map).
823+ * @param key the key to put
829824 * @param value the value to put
830825 * @return the correspond assignment (to use in an update query)
831826 */
@@ -835,11 +830,11 @@
835830
836831 /**
837832 * Puts a map of new key/value pairs to a map column.
838- * <p>
833+ * <p/>
839834 * This will generate: {@code name = name + map}.
840835 *
841836 * @param name the column name (must be of type map).
842- * @param map the map of key/value pairs to put
837+ * @param map the map of key/value pairs to put
843838 * @return the correspond assignment (to use in an update query)
844839 */
845840 public static Assignment putAll(String name, Map<?, ?> map) {
@@ -848,11 +843,11 @@
848843
849844 /**
850845 * Puts a map of new key/value pairs to a map column.
851- * <p>
846+ * <p/>
852847 * This will generate: {@code name = name + map}.
853848 *
854849 * @param name the column name (must be of type map).
855- * @param map a bind marker representing the map of key/value pairs to put
850+ * @param map a bind marker representing the map of key/value pairs to put
856851 * @return the correspond assignment (to use in an update query)
857852 */
858853 public static Assignment putAll(String name, BindMarker map) {
@@ -861,7 +856,7 @@
861856
862857 /**
863858 * An object representing an anonymous bind marker (a question mark).
864- * <p>
859+ * <p/>
865860 * This can be used wherever a value is expected. For instance, one can do:
866861 * <pre>
867862 * {@code
@@ -879,7 +874,7 @@
879874
880875 /**
881876 * An object representing a named bind marker.
882- * <p>
877+ * <p/>
883878 * This can be used wherever a value is expected. For instance, one can do:
884879 * <pre>
885880 * {@code
@@ -888,7 +883,7 @@
888883 * PreparedState p = session.prepare(i.toString());
889884 * }
890885 * </pre>
891- * <p>
886+ * <p/>
892887 * Please note that named bind makers are only supported starting with Cassandra 2.0.1.
893888 *
894889 * @param name the name for the bind marker.
@@ -900,19 +895,19 @@
900895
901896 /**
902897 * Protects a value from any interpretation by the query builder.
903- * <p>
898+ * <p/>
904899 * The following table exemplify the behavior of this function:
905900 * <table border=1>
906- * <caption>Examples of use</caption>
907- * <tr><th>Code</th><th>Resulting query string</th></tr>
908- * <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>
909- * <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>
910- * <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>
911- * <tr><td>{@code select().from("t").where(eq("c", "now()")); }</td><td>{@code "SELECT * FROM t WHERE c='now()';"}</td></tr>
912- * <tr><td>{@code select().from("t").where(eq("c", raw("now()"))); }</td><td>{@code "SELECT * FROM t WHERE c=now();"}</td></tr>
901+ * <caption>Examples of use</caption>
902+ * <tr><th>Code</th><th>Resulting query string</th></tr>
903+ * <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>
904+ * <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>
905+ * <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>
906+ * <tr><td>{@code select().from("t").where(eq("c", "now()")); }</td><td>{@code "SELECT * FROM t WHERE c='now()';"}</td></tr>
907+ * <tr><td>{@code select().from("t").where(eq("c", raw("now()"))); }</td><td>{@code "SELECT * FROM t WHERE c=now();"}</td></tr>
913908 * </table>
914909 * <i>Note: the 2nd and 3rd examples in this table are not a valid CQL3 queries.</i>
915- * <p>
910+ * <p/>
916911 * The use of that method is generally discouraged since it lead to security risks. However,
917912 * if you know what you are doing, it allows to escape the interpretations done by the
918913 * QueryBuilder.
@@ -927,7 +922,7 @@
927922 /**
928923 * Creates a function call.
929924 *
930- * @param name the name of the function to call.
925+ * @param name the name of the function to call.
931926 * @param parameters the parameters for the function.
932927 * @return the function call.
933928 */
@@ -955,7 +950,7 @@
955950
956951 /**
957952 * Declares that the name in argument should be treated as a column name.
958- * <p>
953+ * <p/>
959954 * This mainly meant for use with {@link Select.Selection#fcall} when a
960955 * function should apply to a column name, not a string value.
961956 *
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +29 −37
@@ -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 write time of provided column.
474- * <p>
466+ * <p/>
475467 * This is a shortcut for {@code fcall("writetime", QueryBuilder.column(name))}.
476468 *
477469 * @param name the name of the column to select the write time of.
@@ -483,7 +475,7 @@
483475
484476 /**
485477 * Selects the ttl of provided column.
486- * <p>
478+ * <p/>
487479 * This is a shortcut for {@code fcall("ttl", QueryBuilder.column(name))}.
488480 *
489481 * @param name the name of the column to select the ttl of.
@@ -495,13 +487,13 @@
495487
496488 /**
497489 * Creates a function call.
498- * <p>
490+ * <p/>
499491 * Please note that the parameters are interpreted as values, and so
500492 * {@code fcall("textToBlob", "foo")} will generate the string
501493 * {@code "textToBlob('foo')"}. If you want to generate
502494 * {@code "textToBlob(foo)"}, i.e. if the argument must be interpreted
503495 * as a column name (in a select clause), you will need to use the
504- * {@link QueryBuilder#column} method, and so
496+ * {@link QueryBuilder#column} method, and so
505497 * {@code fcall("textToBlob", QueryBuilder.column(foo)}.
506498 */
507499 public SelectionOrAlias fcall(String name, Object... parameters) {
@@ -512,7 +504,7 @@
512504 * Adds the table to select from.
513505 *
514506 * @param keyspace the name of the keyspace to select from.
515- * @param table the name of the table to select from.
507+ * @param table the name of the table to select from.
516508 * @return a newly built SELECT statement that selects from {@code keyspace.table}.
517509 */
518510 @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/Using.java +0 −1
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.List;
2019
2120 public abstract class Using extends Utils.Appendeable {
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +26 −24
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.DataType;
19+
1820 import java.math.BigDecimal;
1921 import java.math.BigInteger;
2022 import java.net.InetAddress;
@@ -24,8 +26,6 @@
2426
2527 import static com.google.common.base.Preconditions.checkNotNull;
2628
27-import com.datastax.driver.core.DataType;
28-
2929 // Static utilities private to the query builder
3030 abstract class Utils {
3131
@@ -133,9 +133,9 @@
133133 }
134134
135135 if (rawValue)
136- sb.append((String)value);
136+ sb.append((String) value);
137137 else
138- appendValueString((String)value, sb);
138+ appendValueString((String) value, sb);
139139 }
140140 }
141141
@@ -156,7 +156,7 @@
156156 sb.append(value);
157157 return true;
158158 } else if (value instanceof FCall) {
159- FCall fcall = (FCall)value;
159+ FCall fcall = (FCall) value;
160160 sb.append(fcall.name).append('(');
161161 for (int i = 0; i < fcall.parameters.length; i++) {
162162 if (i > 0)
@@ -166,7 +166,7 @@
166166 sb.append(')');
167167 return true;
168168 } else if (value instanceof CName) {
169- appendName(((CName)value).name, sb);
169+ appendName(((CName) value).name, sb);
170170 return true;
171171 } else if (value == null) {
172172 sb.append("null");
@@ -182,10 +182,10 @@
182182 appendList((List) value, sb, rawValue);
183183 return true;
184184 } else if (value instanceof Set) {
185- appendSet((Set)value, sb, rawValue);
185+ appendSet((Set) value, sb, rawValue);
186186 return true;
187187 } else if (value instanceof Map) {
188- appendMap((Map)value, sb, rawValue);
188+ appendMap((Map) value, sb, rawValue);
189189 return true;
190190 } else {
191191 return false;
@@ -218,7 +218,8 @@
218218 sb.append('{');
219219 boolean first = true;
220220 for (Object elt : s) {
221- if (first) first = false; else sb.append(',');
221+ if (first) first = false;
222+ else sb.append(',');
222223 appendFlatValue(elt, sb, rawValue);
223224 }
224225 sb.append('}');
@@ -248,7 +249,7 @@
248249 if (!(value instanceof FCall))
249250 return false;
250251
251- FCall fcall = (FCall)value;
252+ FCall fcall = (FCall) value;
252253 for (Object param : fcall.parameters)
253254 if (containsBindMarker(param))
254255 return true;
@@ -256,23 +257,23 @@
256257 }
257258
258259 static boolean isIdempotent(Object value) {
259- if(value == null) {
260+ if (value == null) {
260261 return true;
261262 } else if (value instanceof Assignment) {
262- Assignment assignment = (Assignment)value;
263+ Assignment assignment = (Assignment) value;
263264 return assignment.isIdempotent();
264265 } else if (value instanceof FCall) {
265266 return false;
266267 } else if (value instanceof RawString) {
267268 return false;
268- } else if(value instanceof Collection) {
269- for (Object elt : ((Collection)value)) {
270- if(!isIdempotent(elt))
269+ } else if (value instanceof Collection) {
270+ for (Object elt : ((Collection) value)) {
271+ if (!isIdempotent(elt))
271272 return false;
272273 }
273274 return true;
274275 } else if (value instanceof Map) {
275- for (Map.Entry<?, ?> entry : ((Map<?, ?>)value).entrySet()) {
276+ for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
276277 if (!isIdempotent(entry.getKey()) || !isIdempotent(entry.getValue()))
277278 return false;
278279 }
@@ -286,9 +287,9 @@
286287
287288 static boolean isRawValue(Object value) {
288289 return value != null
289- && !(value instanceof FCall)
290- && !(value instanceof CName)
291- && !(value instanceof BindMarker);
290+ && !(value instanceof FCall)
291+ && !(value instanceof CName)
292+ && !(value instanceof BindMarker);
292293 }
293294
294295 static String toRawString(Object value) {
@@ -307,11 +308,11 @@
307308
308309 static StringBuilder appendName(Object name, StringBuilder sb) {
309310 if (name instanceof String) {
310- appendName((String)name, sb);
311+ appendName((String) name, sb);
311312 } else if (name instanceof CName) {
312- appendName(((CName)name).name, sb);
313+ appendName(((CName) name).name, sb);
313314 } else if (name instanceof FCall) {
314- FCall fcall = (FCall)name;
315+ FCall fcall = (FCall) name;
315316 sb.append(fcall.name).append('(');
316317 for (int i = 0; i < fcall.parameters.length; i++) {
317318 if (i > 0)
@@ -320,7 +321,7 @@
320321 }
321322 sb.append(')');
322323 } else if (name instanceof Alias) {
323- Alias alias = (Alias)name;
324+ Alias alias = (Alias) name;
324325 appendName(alias.column, sb);
325326 sb.append(" AS ").append(alias.alias);
326327 } else {
@@ -331,6 +332,7 @@
331332
332333 static abstract class Appendeable {
333334 abstract void appendTo(StringBuilder sb, List<Object> values);
335+
334336 abstract boolean containsBindMarker();
335337 }
336338
@@ -343,7 +345,7 @@
343345 int nbMatch = 0;
344346 int start = -1;
345347 do {
346- start = text.indexOf(search, start+1);
348+ start = text.indexOf(search, start + 1);
347349 if (start != -1)
348350 ++nbMatch;
349351 } while (start != -1);
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/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 +1 −1
@@ -18,7 +18,7 @@
1818 /**
1919 * Augment AssertJ with custom assertions for the Java driver.
2020 */
21-public class Assertions extends org.assertj.core.api.Assertions{
21+public class Assertions extends org.assertj.core.api.Assertions {
2222 public static ClusterAssert assertThat(Cluster cluster) {
2323 return new ClusterAssert(cluster);
2424 }
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/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 +59 −45
@@ -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
@@ -429,25 +431,25 @@
429431 erroredOut = true;
430432 }
431433
432- @BeforeClass(groups = { "isolated", "short", "long" })
434+ @BeforeClass(groups = {"isolated", "short", "long"})
433435 public void beforeClass() {
434436 maybeInitCluster();
435437 initKeyspace();
436438 }
437439
438- @AfterClass(groups = { "isolated", "short", "long" })
440+ @AfterClass(groups = {"isolated", "short", "long"})
439441 public void afterClass() {
440442 try {
441443 clearSimpleKeyspace();
442444 } finally {
443- if(cluster != null) {
445+ if (cluster != null) {
444446 cluster.close();
445447 }
446448 }
447449 }
448450
449- private void maybeInitCluster(){
450- if (!clusterInitialized){
451+ private void maybeInitCluster() {
452+ if (!clusterInitialized) {
451453 try {
452454 //launch ccm cluster
453455 ccmBridge = CCMBridge.builder("test-class").withoutNodes().notStarted().build();
@@ -481,8 +483,8 @@
481483 builder = configure(builder);
482484
483485 cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress))
484- .withNettyOptions(TestUtils.nonQuietClusterCloseOptions)
485- .build();
486+ .withNettyOptions(TestUtils.nonQuietClusterCloseOptions)
487+ .build();
486488 session = cluster.connect();
487489 keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet();
488490 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
@@ -509,7 +511,7 @@
509511 }
510512
511513 private void clearSimpleKeyspace() {
512- if(keyspace != null) {
514+ if (keyspace != null) {
513515 logger.debug("Removing keyspace {}.", keyspace);
514516 // Temporarily extend read timeout to 1 minute to accommodate dropping keyspaces and
515517 // tables being slow, particularly in a CI environment.
@@ -520,7 +522,7 @@
520522 if (ksm != null) {
521523 // drop each table individually as this seems to be more dependable than dropping
522524 // the entire keyspace at once if it has many tables.
523- if(ksm.getTables().size() > 10) {
525+ if (ksm.getTables().size() > 10) {
524526 for (TableMetadata table : ksm.getTables()) {
525527 logger.debug("Dropping table {}.{}.", keyspace, table.getName());
526528 session.execute("DROP TABLE " + keyspace + "." + table.getName());
@@ -607,10 +609,12 @@
607609 }
608610 }
609611
610- /** use {@link #builder(String)} to get an instance */
612+ /**
613+ * use {@link #builder(String)} to get an instance
614+ */
611615 public static class Builder {
612616 private final String clusterName;
613- private Integer[] nodes = { 1 };
617+ private Integer[] nodes = {1};
614618 private boolean start = true;
615619 private String cassandraInstallArgs = CASSANDRA_INSTALL_ARGS;
616620 private String[] startOptions = new String[0];
@@ -621,7 +625,9 @@
621625 this.clusterName = clusterName;
622626 }
623627
624- /** Number of nodes for each DC. Defaults to [1] (1 DC with 1 node) */
628+ /**
629+ * Number of nodes for each DC. Defaults to [1] (1 DC with 1 node)
630+ */
625631 public Builder withNodes(Integer... nodes) {
626632 this.nodes = nodes;
627633 return this;
@@ -644,25 +650,33 @@
644650 return this;
645651 }
646652
647- /** Whether to start the cluster immediately (defaults to true if this is never called) */
653+ /**
654+ * Whether to start the cluster immediately (defaults to true if this is never called)
655+ */
648656 public Builder notStarted() {
649657 this.start = false;
650658 return this;
651659 }
652660
653- /** Defaults to system property cassandra.version */
661+ /**
662+ * Defaults to system property cassandra.version
663+ */
654664 public Builder withCassandraVersion(String cassandraVersion) {
655665 this.cassandraInstallArgs = "-v " + cassandraVersion;
656666 return this;
657667 }
658668
659- /** Free-form options that will be added at the end of the start command */
669+ /**
670+ * Free-form options that will be added at the end of the start command
671+ */
660672 public Builder withStartOptions(String... options) {
661673 this.startOptions = options;
662674 return this;
663675 }
664676
665- /** Customizes entries in cassandra.yaml (can be called multiple times) */
677+ /**
678+ * Customizes entries in cassandra.yaml (can be called multiple times)
679+ */
666680 public Builder withCassandraConfiguration(String key, String value) {
667681 this.cassandraConfiguration.put(key, value);
668682 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 +3 −2
@@ -15,9 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.Test;
19+
1820 import java.util.Arrays;
1921
20-import org.testng.annotations.Test;
2122 import static org.testng.Assert.*;
2223
2324 public class CassandraTypeParserTest {
@@ -42,7 +43,7 @@
4243 public void parseWithCompositeTest() {
4344
4445 String s = "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type, org.apache.cassandra.db.marshal.UTF8Type,";
45- s += "org.apache.cassandra.db.marshal.ColumnToCollectionType(6162:org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))";
46+ s += "org.apache.cassandra.db.marshal.ColumnToCollectionType(6162:org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))";
4647 CassandraTypeParser.ParseResult r1 = CassandraTypeParser.parseWithComposite(s);
4748 assertTrue(r1.isComposite);
4849 assertEquals(r1.types, Arrays.asList(DataType.cint(), DataType.text()));
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 +48 −53
@@ -15,15 +15,8 @@
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;
@@ -35,13 +28,14 @@
3528 import org.slf4j.LoggerFactory;
3629 import org.testng.annotations.Test;
3730
38-import static org.mockito.Mockito.atLeast;
39-import static org.mockito.Mockito.atMost;
40-import static org.mockito.Mockito.spy;
41-import static org.mockito.Mockito.verify;
42-
43-import com.datastax.driver.core.exceptions.NoHostAvailableException;
44-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
31+import java.net.InetAddress;
32+import java.net.InetSocketAddress;
33+import java.net.UnknownHostException;
34+import java.util.Collections;
35+import java.util.List;
36+import java.util.Map;
37+import java.util.concurrent.TimeUnit;
38+import java.util.concurrent.TimeoutException;
4539
4640 import static com.datastax.driver.core.Assertions.assertThat;
4741 import static com.datastax.driver.core.Assertions.fail;
@@ -49,6 +43,7 @@
4943 import static com.datastax.driver.core.HostDistance.LOCAL;
5044 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
5145 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
46+import static org.mockito.Mockito.*;
5247
5348 public class ClusterInitTest {
5449 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
@@ -99,19 +94,19 @@
9994 PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(LOCAL, 1, 1);
10095
10196 cluster = Cluster.builder()
102- .withPort(scassandra.getBinaryPort())
103- .addContactPoints(
104- realHostAddress,
105- failingHosts.get(0).address, failingHosts.get(1).address,
106- failingHosts.get(2).address, failingHosts.get(3).address,
107- missingHostAddress
108- )
109- .withSocketOptions(socketOptions)
110- .withReconnectionPolicy(reconnectionPolicy)
111- .withPoolingOptions(poolingOptions)
112- .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
113- .withQueryOptions(nonDebouncingQueryOptions())
114- .build();
97+ .withPort(scassandra.getBinaryPort())
98+ .addContactPoints(
99+ realHostAddress,
100+ failingHosts.get(0).address, failingHosts.get(1).address,
101+ failingHosts.get(2).address, failingHosts.get(3).address,
102+ missingHostAddress
103+ )
104+ .withSocketOptions(socketOptions)
105+ .withReconnectionPolicy(reconnectionPolicy)
106+ .withPoolingOptions(poolingOptions)
107+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
108+ .withQueryOptions(nonDebouncingQueryOptions())
109+ .build();
115110 cluster.connect();
116111
117112 // For information only:
@@ -137,7 +132,7 @@
137132 // There is a possible race here in that the host is marked down in a separate Executor in onDown
138133 // and then starts a periodic reconnection attempt shortly after. Since setDown is called before
139134 // startPeriodicReconnectionAttempt, we add a slight delay here if the future isn't set yet.
140- if(host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone()) {
135+ if (host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone()) {
141136 logger.warn("Periodic Reconnection Attempt hasn't started yet for {}, waiting 1 second and then checking.", host);
142137 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
143138 }
@@ -163,19 +158,19 @@
163158 * @jira_ticket JAVA-954
164159 * @expected_result No reconnection scheduled.
165160 */
166- @Test(groups="short", expectedExceptions = NoHostAvailableException.class)
161+ @Test(groups = "short", expectedExceptions = NoHostAvailableException.class)
167162 public void should_not_schedule_reconnections_before_init_complete() {
168163 // Both contact points time out so we're sure we'll try both of them and init will never complete.
169164 List<FakeHost> hosts = Lists.newArrayList(
170- new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS),
171- new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS));
165+ new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS),
166+ new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS));
172167 // Use a low reconnection interval and keep the default connect timeout (5 seconds). So if a reconnection was scheduled,
173168 // we would see a call to the reconnection policy.
174169 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(100));
175170 Cluster cluster = Cluster.builder()
176- .addContactPoints(hosts.get(0).address, hosts.get(1).address)
177- .withReconnectionPolicy(reconnectionPolicy)
178- .build();
171+ .addContactPoints(hosts.get(0).address, hosts.get(1).address)
172+ .withReconnectionPolicy(reconnectionPolicy)
173+ .build();
179174 try {
180175 cluster.init();
181176 } finally {
@@ -200,9 +195,9 @@
200195 @Test(groups = "short")
201196 public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
202197 Cluster cluster = Cluster.builder()
203- .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
204- .withNettyOptions(nonQuietClusterCloseOptions)
205- .build();
198+ .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
199+ .withNettyOptions(nonQuietClusterCloseOptions)
200+ .build();
206201 try {
207202 cluster.connect();
208203 fail("Should not have been able to connect.");
@@ -218,8 +213,8 @@
218213
219214 private void primePeerRows(Scassandra scassandra, List<FakeHost> otherHosts) throws UnknownHostException {
220215 PrimingClient primingClient = PrimingClient.builder()
221- .withHost("localhost").withPort(scassandra.getAdminPort())
222- .build();
216+ .withHost("localhost").withPort(scassandra.getAdminPort())
217+ .build();
223218
224219 List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(5);
225220
@@ -227,20 +222,20 @@
227222 for (FakeHost otherHost : otherHosts) {
228223 InetAddress address = InetAddress.getByName(otherHost.address);
229224 rows.add(ImmutableMap.<String, Object>builder()
230- .put("peer", address)
231- .put("rpc_address", address)
232- .put("data_center", "datacenter1")
233- .put("rack", "rack1")
234- .put("release_version", "2.0.1")
235- .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++)))
236- .build());
225+ .put("peer", address)
226+ .put("rpc_address", address)
227+ .put("data_center", "datacenter1")
228+ .put("rack", "rack1")
229+ .put("release_version", "2.0.1")
230+ .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++)))
231+ .build());
237232 }
238233
239234 primingClient.prime(
240- PrimingRequest.queryBuilder()
241- .withQuery("SELECT * FROM system.peers")
242- .withColumnTypes(ScassandraCluster.SELECT_PEERS)
243- .withRows(rows)
244- .build());
235+ PrimingRequest.queryBuilder()
236+ .withQuery("SELECT * FROM system.peers")
237+ .withColumnTypes(ScassandraCluster.SELECT_PEERS)
238+ .withRows(rows)
239+ .build());
245240 }
246241 }
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();
@@ -92,7 +92,7 @@
9292
9393 final Session session = cluster.connect("ks");
9494 // Consume all stream ids except one.
95- for(int i = 0; i < StreamIdGenerator.MAX_STREAM_PER_CONNECTION-1; i++)
95+ for (int i = 0; i < StreamIdGenerator.MAX_STREAM_PER_CONNECTION - 1; i++)
9696 mockFutures.add(session.executeAsync("mock query"));
9797
9898
@@ -114,15 +114,15 @@
114114 try {
115115 ResultSet result = future.get(waitTimeInMs, TimeUnit.MILLISECONDS);
116116 assertThat(result.one().getString("n")).isEqualTo("world");
117- } catch (TimeoutException e) {
117+ } catch (TimeoutException e) {
118118 fail("Future timed out after " + waitTimeInMs + "ms. " +
119119 "There is a strong possibility connection is not being released.");
120120 }
121121 } finally {
122122 // Cancel all pending requests.
123- for(ResultSetFuture future : mockFutures)
123+ for (ResultSetFuture future : mockFutures)
124124 future.cancel(true);
125- if(cluster != null)
125+ if (cluster != null)
126126 cluster.close();
127127 }
128128 }
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 +27 −30
@@ -15,31 +15,28 @@
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;
2522 import com.google.common.base.Function;
2623 import com.google.common.collect.HashMultiset;
27-import com.google.common.collect.Iterables;
2824 import com.google.common.collect.Maps;
2925 import org.slf4j.Logger;
3026 import org.slf4j.LoggerFactory;
3127 import org.testng.annotations.Test;
3228
33-import static com.google.common.collect.Lists.newArrayList;
29+import java.net.InetAddress;
30+import java.util.Collection;
31+import java.util.Iterator;
32+import java.util.Map;
33+import java.util.concurrent.TimeUnit;
34+import java.util.concurrent.atomic.AtomicInteger;
3435
3536 import static com.datastax.driver.core.Assertions.assertThat;
3637 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3738 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;
39+import static com.google.common.collect.Lists.newArrayList;
4340
4441 public class ControlConnectionTest {
4542
@@ -74,10 +71,10 @@
7471 ccm = CCMBridge.builder("test").withNodes(2).build();
7572 // We pass only the first host as contact point, so we know the control connection will be on this host
7673 cluster = Cluster.builder()
77- .addContactPoint(CCMBridge.ipOfNode(1))
78- .withReconnectionPolicy(reconnectionPolicy)
79- .withLoadBalancingPolicy(loadBalancingPolicy)
80- .build();
74+ .addContactPoint(CCMBridge.ipOfNode(1))
75+ .withReconnectionPolicy(reconnectionPolicy)
76+ .withLoadBalancingPolicy(loadBalancingPolicy)
77+ .build();
8178 cluster.init();
8279
8380 // Kill the control connection host, there should be exactly one reconnection attempt
@@ -101,10 +98,10 @@
10198 * Ensures that if the host that the Control Connection is connected to is removed/decommissioned that the
10299 * Control Connection is reestablished to another host.
103100 *
104- * @since 2.0.9
105101 * @jira_ticket JAVA-597
106102 * @expected_result Control Connection is reestablished to another host.
107103 * @test_category control_connection
104+ * @since 2.0.9
108105 */
109106 @Test(groups = "long")
110107 public void should_reestablish_if_control_node_decommissioned() throws InterruptedException {
@@ -148,7 +145,7 @@
148145 *
149146 * @jira_ticket JAVA-618
150147 * @expected_result All 5 hosts were chosen within 100 attempts. There is a very small possibility
151- * that this may not be the case and this is not actually an error.
148+ * that this may not be the case and this is not actually an error.
152149 * @test_category control_connection
153150 * @since 2.0.11, 2.1.8, 2.2.0
154151 */
@@ -161,15 +158,15 @@
161158
162159 try {
163160 Collection<String> contactPoints = newArrayList();
164- for(int i = 1; i <= hostCount; i++) {
161+ for (int i = 1; i <= hostCount; i++) {
165162 contactPoints.add(scassandras.address(i));
166163 }
167164 final HashMultiset<InetAddress> occurrencesByHost = HashMultiset.create(hostCount);
168- for(int i = 0; i < iterations; i++) {
165+ for (int i = 0; i < iterations; i++) {
169166 Cluster cluster = Cluster.builder()
170- .addContactPoints(contactPoints.toArray(new String[hostCount]))
171- .withNettyOptions(nonQuietClusterCloseOptions)
172- .build();
167+ .addContactPoints(contactPoints.toArray(new String[hostCount]))
168+ .withNettyOptions(nonQuietClusterCloseOptions)
169+ .build();
173170
174171 try {
175172 cluster.init();
@@ -178,7 +175,7 @@
178175 cluster.close();
179176 }
180177 }
181- if(logger.isDebugEnabled()) {
178+ if (logger.isDebugEnabled()) {
182179 Map<InetAddress, Integer> hostCounts = Maps.toMap(occurrencesByHost.elementSet(), new Function<InetAddress, Integer>() {
183180 @Override
184181 public Integer apply(InetAddress input) {
@@ -190,10 +187,10 @@
190187 // There is an incredibly low chance that a host may not be used based on randomness.
191188 // This probability is very low however.
192189 assertThat(occurrencesByHost.elementSet().size())
193- .as("Not all hosts were used as contact points. There is a very small chance"
194- + " of this happening based on randomness, investigate whether or not this"
195- + " is a bug.")
196- .isEqualTo(hostCount);
190+ .as("Not all hosts were used as contact points. There is a very small chance"
191+ + " of this happening based on randomness, investigate whether or not this"
192+ + " is a bug.")
193+ .isEqualTo(hostCount);
197194 } finally {
198195 scassandras.stop();
199196 }
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/DataTypeIntegrationTest.java +20 −16
@@ -15,22 +15,26 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-import java.util.concurrent.atomic.AtomicInteger;
20-
21-import com.google.common.collect.*;
18+import com.datastax.driver.core.utils.CassandraVersion;
19+import com.google.common.collect.ImmutableList;
20+import com.google.common.collect.ImmutableMap;
21+import com.google.common.collect.Lists;
22+import com.google.common.collect.Sets;
2223 import org.slf4j.Logger;
2324 import org.slf4j.LoggerFactory;
2425 import org.testng.annotations.Test;
2526
27+import java.util.Collection;
28+import java.util.List;
29+import java.util.Map;
30+import java.util.concurrent.atomic.AtomicInteger;
31+
2632 import static org.assertj.core.api.Assertions.assertThat;
2733 import static org.assertj.core.api.Assertions.fail;
2834
29-import com.datastax.driver.core.utils.CassandraVersion;
30-
3135 /**
3236 * The goal of this test is to cover the serialization and deserialization of datatypes.
33- *
37+ * <p/>
3438 * It creates a table with a column of a given type, inserts a value and then tries to retrieve it.
3539 * There are 3 variants for the insert query: a raw string, a simple statement with a parameter
3640 * (protocol > v2 only) and a prepared statement.
@@ -53,7 +57,7 @@
5357 for (TestTable table : tables) {
5458 if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
5559 logger.debug("Skipping table because it uses a feature not supported by Cassandra {}: {}",
56- cassandraVersion, table.createStatement);
60+ cassandraVersion, table.createStatement);
5761 else
5862 statements.add(table.createStatement);
5963 }
@@ -101,12 +105,12 @@
101105 Object queriedValue = table.testColumnType.deserialize(row.getBytesUnsafe("v"));
102106
103107 assertThat(queriedValue)
104- .as("Test failure on %s statement with table:%n%s;%n" +
105- "insert statement:%n%s;%n",
106- statementType,
107- table.createStatement,
108- table.insertStatement)
109- .isEqualTo(table.sampleValue);
108+ .as("Test failure on %s statement with table:%n%s;%n" +
109+ "insert statement:%n%s;%n",
110+ statementType,
111+ table.createStatement,
112+ table.insertStatement)
113+ .isEqualTo(table.sampleValue);
110114
111115 session.execute(table.truncateStatement);
112116 }
@@ -187,8 +191,8 @@
187191 Object valueSample = valueEntry.getValue();
188192
189193 tables.add(new TestTable(DataType.map(keyType, valueType),
190- ImmutableMap.builder().put(keySample, valueSample).build(),
191- "1.2.0"));
194+ ImmutableMap.builder().put(keySample, valueSample).build(),
195+ "1.2.0"));
192196 }
193197 }
194198 return tables;
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +3 −4
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import org.testng.annotations.Test;
20+
1821 import java.nio.ByteBuffer;
1922 import java.util.Arrays;
2023 import java.util.List;
2124
22-import org.testng.annotations.Test;
23-
2425 import static org.testng.Assert.assertEquals;
2526 import static org.testng.Assert.fail;
2627
27-import com.datastax.driver.core.exceptions.InvalidTypeException;
28-
2928 public class DataTypeTest {
3029
3130 @Test(groups = "unit")
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;
@@ -86,8 +83,8 @@
8683 */
8784 private void completeRequests(int count, List<MockRequest> requests) {
8885 Iterator<MockRequest> requestIt = requests.iterator();
89- for(int i = 0; i < count; i++) {
90- if(requestIt.hasNext()) {
86+ for (int i = 0; i < count; i++) {
87+ if (requestIt.hasNext()) {
9188 MockRequest request = requestIt.next();
9289 request.simulateSuccessResponse();
9390 requestIt.remove();
@@ -101,7 +98,7 @@
10198 * Completes all requests by simulating a successful response.
10299 */
103100 private void completeRequests(List<MockRequest> requests) {
104- for(MockRequest request : requests) {
101+ for (MockRequest request : requests) {
105102 request.simulateSuccessResponse();
106103 }
107104 }
@@ -110,9 +107,9 @@
110107 * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
111108 * of creating a new connection.
112109 *
113- * @since 2.0.10, 2.1.6
114110 * @jira_ticket JAVA-419
115111 * @test_category connection:connection_pool
112+ * @since 2.0.10, 2.1.6
116113 */
117114 @Test(groups = "short")
118115 public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException, BusyConnectionException {
@@ -139,9 +136,9 @@
139136 * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
140137 * timeout instead of creating a new connection.
141138 *
142- * @since 2.0.10, 2.1.6
143139 * @jira_ticket JAVA-419
144140 * @test_category connection:connection_pool
141+ * @since 2.0.10, 2.1.6
145142 */
146143 @Test(groups = "short")
147144 public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception {
@@ -187,9 +184,9 @@
187184 /**
188185 * Ensures that if the core connection pool is full that borrowConnection will create and use a new connection.
189186 *
190- * @since 2.0.10, 2.1.6
191187 * @jira_ticket JAVA-419
192188 * @test_category connection:connection_pool
189+ * @since 2.0.10, 2.1.6
193190 */
194191 @Test(groups = "short")
195192 public void should_add_extra_connection_when_core_full() throws Exception {
@@ -217,9 +214,9 @@
217214 * Ensures that a trashed connection that has not been timed out should be resurrected into the connection pool if
218215 * borrowConnection is called and a new connection is needed.
219216 *
220- * @since 2.0.10, 2.1.6
221217 * @jira_ticket JAVA-419
222218 * @test_category connection:connection_pool
219+ * @since 2.0.10, 2.1.6
223220 */
224221 @Test(groups = "long")
225222 public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception {
@@ -277,9 +274,9 @@
277274 * Ensures that a trashed connection that has been timed out should not be resurrected into the connection pool if
278275 * borrowConnection is called and a new connection is needed.
279276 *
280- * @since 2.0.10, 2.1.6
281277 * @jira_ticket JAVA-419
282278 * @test_category connection:connection_pool
279+ * @since 2.0.10, 2.1.6
283280 */
284281 @Test(groups = "long")
285282 public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception {
@@ -331,8 +328,8 @@
331328 MockRequest request = MockRequest.send(pool);
332329 requests.add(request);
333330 assertThat(request.connection)
334- .isNotEqualTo(connection2) // should not be the full connection
335- .isNotEqualTo(connection1); // should not be the previously trashed one
331+ .isNotEqualTo(connection2) // should not be the full connection
332+ .isNotEqualTo(connection1); // should not be the previously trashed one
336333 } finally {
337334 completeRequests(requests);
338335 cluster.close();
@@ -342,9 +339,9 @@
342339 /**
343340 * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
344341 *
345- * @since 2.0.10, 2.1.6
346342 * @jira_ticket JAVA-419
347343 * @test_category connection:connection_pool
344+ * @since 2.0.10, 2.1.6
348345 */
349346 @Test(groups = "long")
350347 public void should_not_close_trashed_connection_until_no_in_flight() throws Exception {
@@ -394,9 +391,9 @@
394391 * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
395392 * the connection is put in the trash.
396393 *
397- * @since 2.0.10, 2.1.6
398394 * @jira_ticket JAVA-419
399395 * @test_category connection:connection_pool
396+ * @since 2.0.10, 2.1.6
400397 */
401398 @Test(groups = "short")
402399 public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception {
@@ -444,7 +441,7 @@
444441 * @test_category connection:connection_pool
445442 * @since 2.0.11
446443 */
447- @Test(groups="short")
444+ @Test(groups = "short")
448445 public void should_keep_host_up_when_one_connection_lost() throws Exception {
449446 Cluster cluster = createClusterBuilder().build();
450447 try {
@@ -454,7 +451,7 @@
454451
455452 // Drop a connection and ensure the host stays up.
456453 currentClient.disableListener();
457- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
454+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
458455 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
459456
460457 // connection 0 should be down, while connection 1 and the Host should remain up.
@@ -478,22 +475,22 @@
478475 * @test_category connection:connection_pool
479476 * @since 2.0.11
480477 */
481- @Test(groups="short")
478+ @Test(groups = "short")
482479 public void should_mark_host_down_when_no_connections_remaining() throws Exception {
483480 int readTimeout = 1000;
484481 int reconnectInterval = 1000;
485482 Cluster cluster = this.createClusterBuilder()
486- .withSocketOptions(new SocketOptions()
487- .setConnectTimeoutMillis(readTimeout)
488- .setReadTimeoutMillis(reconnectInterval))
489- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
483+ .withSocketOptions(new SocketOptions()
484+ .setConnectTimeoutMillis(readTimeout)
485+ .setReadTimeoutMillis(reconnectInterval))
486+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
490487 try {
491488 cluster.init();
492489
493490 Connection.Factory factory = spy(cluster.manager.connectionFactory);
494491 cluster.manager.connectionFactory = factory;
495492
496- HostConnectionPool pool = createPool(cluster, 8,8);
493+ HostConnectionPool pool = createPool(cluster, 8, 8);
497494 // copy list to track these connections.
498495 List<Connection> connections = newArrayList(pool.connections);
499496
@@ -508,13 +505,13 @@
508505 assertThat(cluster).hasClosedControlConnection();
509506
510507 // Ensure all connections are closed.
511- for(Connection connection : connections) {
508+ for (Connection connection : connections) {
512509 assertThat(connection.isClosed()).isTrue();
513510 }
514511
515512 // Expect a reconnect attempt on host after reconnect interval
516513 // on behalf of the control connection.
517- verify(factory, timeout(reconnectInterval*2).atLeastOnce()).open(host);
514+ verify(factory, timeout(reconnectInterval * 2).atLeastOnce()).open(host);
518515
519516 // Sleep for a bit to allow reconnect to fail.
520517 Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS);
@@ -528,9 +525,9 @@
528525 // Reconnect attempt should have been connected for control connection
529526 // and pool.
530527 // 2 attempts for connection.open (reconnect control connection and initial connection for host state).
531- verify(factory, after(reconnectInterval*2).atLeast(2)).open(host);
528+ verify(factory, after(reconnectInterval * 2).atLeast(2)).open(host);
532529 // 7 attempts for core connections after first initial connection.
533- verify(factory, timeout(reconnectInterval*2)).newConnections(any(HostConnectionPool.class), eq(7));
530+ verify(factory, timeout(reconnectInterval * 2)).newConnections(any(HostConnectionPool.class), eq(7));
534531
535532 // Wait some reasonable amount of time for connection to reestablish.
536533 Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
@@ -553,15 +550,15 @@
553550 * @test_category connection:connection_pool
554551 * @since 2.0.11
555552 */
556- @Test(groups="short")
553+ @Test(groups = "short")
557554 public void should_create_new_connections_when_connection_lost_and_under_core_connections() throws Exception {
558555 int readTimeout = 1000;
559556 int reconnectInterval = 1000;
560557 Cluster cluster = this.createClusterBuilder()
561- .withSocketOptions(new SocketOptions()
562- .setConnectTimeoutMillis(readTimeout)
563- .setReadTimeoutMillis(reconnectInterval))
564- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
558+ .withSocketOptions(new SocketOptions()
559+ .setConnectTimeoutMillis(readTimeout)
560+ .setReadTimeoutMillis(reconnectInterval))
561+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
565562 List<MockRequest> requests = newArrayList();
566563 try {
567564 cluster.init();
@@ -577,8 +574,8 @@
577574 // Drop two core connections.
578575 // Disable new connections initially and we'll eventually reenable it.
579576 currentClient.disableListener();
580- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
581- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core2.channel.localAddress()));
577+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
578+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core2.channel.localAddress()));
582579 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
583580
584581 // Since we have a connection left the host should remain up.
@@ -646,10 +643,10 @@
646643 int readTimeout = 1000;
647644 int reconnectInterval = 1000;
648645 Cluster cluster = this.createClusterBuilder()
649- .withSocketOptions(new SocketOptions()
650- .setConnectTimeoutMillis(readTimeout)
651- .setReadTimeoutMillis(reconnectInterval))
652- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
646+ .withSocketOptions(new SocketOptions()
647+ .setConnectTimeoutMillis(readTimeout)
648+ .setReadTimeoutMillis(reconnectInterval))
649+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
653650 List<MockRequest> requests = newArrayList();
654651 try {
655652 cluster.init();
@@ -679,12 +676,12 @@
679676 Connection extra1 = pool.connections.get(1);
680677
681678 // Drop a connection and disable listening.
682- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
679+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
683680 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
684681 currentClient.disableListener();
685682
686683 // Since core0 was closed, all of it's requests should have errored.
687- for(MockRequest request : core0requests) {
684+ for (MockRequest request : core0requests) {
688685 verify(request, times(1)).onException(any(Connection.class), any(Exception.class), anyLong(), anyInt());
689686 }
690687
@@ -744,15 +741,15 @@
744741 * @test_category connection:connection_pool
745742 * @since 2.0.11
746743 */
747- @Test(groups="short")
744+ @Test(groups = "short")
748745 public void should_not_mark_host_down_if_some_connections_fail_on_init() throws Exception {
749746 int readTimeout = 1000;
750747 int reconnectInterval = 1000;
751748 Cluster cluster = this.createClusterBuilder()
752- .withSocketOptions(new SocketOptions()
753- .setConnectTimeoutMillis(readTimeout)
754- .setReadTimeoutMillis(reconnectInterval))
755- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
749+ .withSocketOptions(new SocketOptions()
750+ .setConnectTimeoutMillis(readTimeout)
751+ .setReadTimeoutMillis(reconnectInterval))
752+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
756753 List<MockRequest> requests = newArrayList();
757754 try {
758755 cluster.init();
@@ -810,10 +807,10 @@
810807 int readTimeout = 1000;
811808 int reconnectInterval = 1000;
812809 Cluster cluster = this.createClusterBuilder()
813- .withSocketOptions(new SocketOptions()
814- .setConnectTimeoutMillis(readTimeout)
815- .setReadTimeoutMillis(reconnectInterval))
816- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
810+ .withSocketOptions(new SocketOptions()
811+ .setConnectTimeoutMillis(readTimeout)
812+ .setReadTimeoutMillis(reconnectInterval))
813+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
817814 try {
818815 // Init cluster so control connection is created.
819816 cluster.init();
@@ -851,15 +848,15 @@
851848 * @test_category connection:connection_pool
852849 * @since 2.0.11
853850 */
854- @Test(groups="short")
851+ @Test(groups = "short")
855852 public void should_wait_on_connection_if_not_convicted_and_no_connections_available() throws Exception {
856853 int readTimeout = 1000;
857854 int reconnectInterval = 1000;
858855 Cluster cluster = this.createClusterBuilder()
859- .withSocketOptions(new SocketOptions()
860- .setConnectTimeoutMillis(readTimeout)
861- .setReadTimeoutMillis(reconnectInterval))
862- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
856+ .withSocketOptions(new SocketOptions()
857+ .setConnectTimeoutMillis(readTimeout)
858+ .setReadTimeoutMillis(reconnectInterval))
859+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
863860 try {
864861 // Init cluster so control connection is created.
865862 cluster.init();
@@ -906,15 +903,15 @@
906903 * @test_category connection:connection_pool
907904 * @since 2.0.11
908905 */
909- @Test(groups="short")
906+ @Test(groups = "short")
910907 public void should_wait_on_connection_if_zero_core_connections() throws Exception {
911908 int readTimeout = 1000;
912909 int reconnectInterval = 1000;
913910 Cluster cluster = this.createClusterBuilder()
914- .withSocketOptions(new SocketOptions()
915- .setConnectTimeoutMillis(readTimeout)
916- .setReadTimeoutMillis(reconnectInterval))
917- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
911+ .withSocketOptions(new SocketOptions()
912+ .setConnectTimeoutMillis(readTimeout)
913+ .setReadTimeoutMillis(reconnectInterval))
914+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
918915 try {
919916 // Init cluster so control connection is created.
920917 cluster.init();
@@ -942,26 +939,26 @@
942939
943940 private HostConnectionPool createPool(Cluster cluster, int coreConnections, int maxConnections) {
944941 cluster.getConfiguration().getPoolingOptions()
945- .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections)
946- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections);
942+ .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections)
943+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections);
947944 Session session = cluster.connect();
948945 Host host = TestUtils.findHost(cluster, 1);
949946
950947 // Replace the existing pool with a spy pool and return it.
951- SessionManager sm = ((SessionManager)session);
948+ SessionManager sm = ((SessionManager) session);
952949 return sm.pools.get(host);
953950 }
954951
955952 /**
956- * <p>
953+ * <p/>
957954 * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
958955 * insertions are being executed, the number of opened connection is monitored.
959956 * <p/>
960957 * If at anytime, the number of opened connections is negative, this test will fail.
961958 *
962- * @since 2.0.6, 2.1.1
963959 * @jira_ticket JAVA-349
964960 * @test_category connection:connection_pool
961+ * @since 2.0.6, 2.1.1
965962 */
966963 @Test(groups = "long", enabled = false /* this test causes timeouts on Jenkins */)
967964 public void open_connections_metric_should_always_be_positive() throws InterruptedException {
@@ -1021,17 +1018,19 @@
10211018 sb.append(");");
10221019
10231020 PrimingRequest preparedStatementPrime = PrimingRequest.preparedStatementBuilder()
1024- .withQuery(sb.toString())
1025- .withThen(then().withVariableTypes(PrimitiveType.INT))
1026- .build();
1021+ .withQuery(sb.toString())
1022+ .withThen(then().withVariableTypes(PrimitiveType.INT))
1023+ .build();
10271024 primingClient.prime(preparedStatementPrime);
10281025 return sb.toString();
10291026 }
10301027
1031- /** Mock ResponseCallback that simulates the behavior of SpeculativeExecution (in terms of borrowing/releasing connections). */
1028+ /**
1029+ * Mock ResponseCallback that simulates the behavior of SpeculativeExecution (in terms of borrowing/releasing connections).
1030+ */
10321031 static class MockRequest implements Connection.ResponseCallback {
10331032
1034- enum State { START, COMPLETED, FAILED, TIMED_OUT }
1033+ enum State {START, COMPLETED, FAILED, TIMED_OUT}
10351034
10361035 final Connection connection;
10371036 private Connection.ResponseHandler responseHandler;
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 −13
@@ -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;
@@ -25,24 +23,23 @@
2523 import io.netty.channel.socket.SocketChannel;
2624 import io.netty.util.HashedWheelTimer;
2725 import io.netty.util.Timer;
28-import org.mockito.ArgumentCaptor;
2926 import org.mockito.invocation.InvocationOnMock;
3027 import org.mockito.stubbing.Answer;
3128 import org.testng.annotations.DataProvider;
3229 import org.testng.annotations.Test;
3330
31+import java.util.concurrent.ThreadFactory;
32+
33+import static com.datastax.driver.core.CCMBridge.ipOfNode;
3434 import static org.mockito.Answers.CALLS_REAL_METHODS;
3535 import static org.mockito.Matchers.any;
3636 import static org.mockito.Mockito.*;
3737
38-import static com.datastax.driver.core.Assertions.assertThat;
39-import static com.datastax.driver.core.CCMBridge.ipOfNode;
40-
4138 public class NettyOptionsTest {
4239
4340 @DataProvider(name = "NettyOptionsTest")
4441 public static Object[][] parameters() {
45- Object[][] params = new Object[][] { {1,1}, {3,4} };
42+ Object[][] params = new Object[][]{{1, 1}, {3, 4}};
4643 return params;
4744 }
4845
@@ -68,12 +65,12 @@
6865 }
6966 }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
7067 cluster = Cluster.builder()
71- .addContactPoint(ipOfNode(1))
72- .withPoolingOptions(new PoolingOptions()
73- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
74- )
75- .withNettyOptions(nettyOptions)
76- .build();
68+ .addContactPoint(ipOfNode(1))
69+ .withPoolingOptions(new PoolingOptions()
70+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
71+ )
72+ .withNettyOptions(nettyOptions)
73+ .build();
7774 // when
7875 cluster.connect();// force session creation to populate pools
7976 cluster.close();
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +263 −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));
@@ -109,6 +109,7 @@
109109
110110 private static final List<Token> largeRing = Lists.newArrayList();
111111 private static final Map<Token, Host> largeRingTokenToPrimary = Maps.newHashMap();
112+
112113 static {
113114 for (int i = 0; i < 100; i++) {
114115 InetSocketAddress address = socketAddress("127.0.0." + i);
@@ -121,46 +122,46 @@
121122 }
122123
123124 private static final List<Token> exampleRing = ImmutableList.<Token>builder()
124- .add(TOKEN01)
125- .add(TOKEN02)
126- .add(TOKEN03)
127- .add(TOKEN04)
128- .add(TOKEN05)
129- .add(TOKEN06)
130- .add(TOKEN07)
131- .add(TOKEN08)
132- .add(TOKEN09)
133- .add(TOKEN10)
134- .add(TOKEN11)
135- .add(TOKEN12)
136- .add(TOKEN13)
137- .add(TOKEN14)
138- .add(TOKEN15)
139- .add(TOKEN16)
140- .add(TOKEN17)
141- .add(TOKEN18)
142- .build();
125+ .add(TOKEN01)
126+ .add(TOKEN02)
127+ .add(TOKEN03)
128+ .add(TOKEN04)
129+ .add(TOKEN05)
130+ .add(TOKEN06)
131+ .add(TOKEN07)
132+ .add(TOKEN08)
133+ .add(TOKEN09)
134+ .add(TOKEN10)
135+ .add(TOKEN11)
136+ .add(TOKEN12)
137+ .add(TOKEN13)
138+ .add(TOKEN14)
139+ .add(TOKEN15)
140+ .add(TOKEN16)
141+ .add(TOKEN17)
142+ .add(TOKEN18)
143+ .build();
143144
144145 private static final Map<Token, Host> exampleTokenToPrimary = ImmutableMap.<Token, Host>builder()
145- .put(TOKEN01, host(IP1, DC1, RACK11))
146- .put(TOKEN02, host(IP1, DC1, RACK11))
147- .put(TOKEN03, host(IP5, DC1, RACK12))
148- .put(TOKEN04, host(IP3, DC1, RACK11))
149- .put(TOKEN05, host(IP1, DC1, RACK11))
150- .put(TOKEN06, host(IP5, DC1, RACK12))
151- .put(TOKEN07, host(IP2, DC2, RACK21))
152- .put(TOKEN08, host(IP6, DC2, RACK22))
153- .put(TOKEN09, host(IP3, DC1, RACK11))
154- .put(TOKEN10, host(IP4, DC2, RACK21))
155- .put(TOKEN11, host(IP5, DC1, RACK12))
156- .put(TOKEN12, host(IP4, DC2, RACK21))
157- .put(TOKEN13, host(IP4, DC2, RACK21))
158- .put(TOKEN14, host(IP2, DC2, RACK21))
159- .put(TOKEN15, host(IP6, DC2, RACK22))
160- .put(TOKEN16, host(IP3, DC1, RACK11))
161- .put(TOKEN17, host(IP2, DC2, RACK21))
162- .put(TOKEN18, host(IP6, DC2, RACK22))
163- .build();
146+ .put(TOKEN01, host(IP1, DC1, RACK11))
147+ .put(TOKEN02, host(IP1, DC1, RACK11))
148+ .put(TOKEN03, host(IP5, DC1, RACK12))
149+ .put(TOKEN04, host(IP3, DC1, RACK11))
150+ .put(TOKEN05, host(IP1, DC1, RACK11))
151+ .put(TOKEN06, host(IP5, DC1, RACK12))
152+ .put(TOKEN07, host(IP2, DC2, RACK21))
153+ .put(TOKEN08, host(IP6, DC2, RACK22))
154+ .put(TOKEN09, host(IP3, DC1, RACK11))
155+ .put(TOKEN10, host(IP4, DC2, RACK21))
156+ .put(TOKEN11, host(IP5, DC1, RACK12))
157+ .put(TOKEN12, host(IP4, DC2, RACK21))
158+ .put(TOKEN13, host(IP4, DC2, RACK21))
159+ .put(TOKEN14, host(IP2, DC2, RACK21))
160+ .put(TOKEN15, host(IP6, DC2, RACK22))
161+ .put(TOKEN16, host(IP3, DC1, RACK11))
162+ .put(TOKEN17, host(IP2, DC2, RACK21))
163+ .put(TOKEN18, host(IP6, DC2, RACK22))
164+ .build();
164165
165166 /*
166167 * --------------
@@ -171,18 +172,18 @@
171172 @Test(groups = "unit")
172173 public void networkTopologyWithSimpleDCLayoutTest1() {
173174 List<Token> ring = ImmutableList.<Token>builder()
174- .add(TOKEN01)
175- .add(TOKEN04)
176- .add(TOKEN14)
177- .add(TOKEN19)
178- .build();
175+ .add(TOKEN01)
176+ .add(TOKEN04)
177+ .add(TOKEN14)
178+ .add(TOKEN19)
179+ .build();
179180
180181 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
181- .put(TOKEN01, host(IP1, DC1, RACK11))
182- .put(TOKEN04, host(IP2, DC2, RACK21))
183- .put(TOKEN14, host(IP1, DC1, RACK11))
184- .put(TOKEN19, host(IP2, DC2, RACK21))
185- .build();
182+ .put(TOKEN01, host(IP1, DC1, RACK11))
183+ .put(TOKEN04, host(IP2, DC2, RACK21))
184+ .put(TOKEN14, host(IP1, DC1, RACK11))
185+ .put(TOKEN19, host(IP2, DC2, RACK21))
186+ .build();
186187
187188 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 1), rf(DC2, 1));
188189
@@ -197,26 +198,26 @@
197198 @Test(groups = "unit")
198199 public void networkTopologyWithSimpleDCLayoutTest2() {
199200 List<Token> ring = ImmutableList.<Token>builder()
200- .add(TOKEN01)
201- .add(TOKEN03)
202- .add(TOKEN05)
203- .add(TOKEN07)
204- .add(TOKEN13)
205- .add(TOKEN15)
206- .add(TOKEN17)
207- .add(TOKEN19)
208- .build();
201+ .add(TOKEN01)
202+ .add(TOKEN03)
203+ .add(TOKEN05)
204+ .add(TOKEN07)
205+ .add(TOKEN13)
206+ .add(TOKEN15)
207+ .add(TOKEN17)
208+ .add(TOKEN19)
209+ .build();
209210
210211 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
211- .put(TOKEN01, host(IP1, DC1, RACK11))
212- .put(TOKEN03, host(IP2, DC2, RACK21))
213- .put(TOKEN05, host(IP3, DC1, RACK11))
214- .put(TOKEN07, host(IP4, DC2, RACK21))
215- .put(TOKEN13, host(IP1, DC1, RACK11))
216- .put(TOKEN15, host(IP2, DC2, RACK21))
217- .put(TOKEN17, host(IP3, DC1, RACK11))
218- .put(TOKEN19, host(IP4, DC2, RACK21))
219- .build();
212+ .put(TOKEN01, host(IP1, DC1, RACK11))
213+ .put(TOKEN03, host(IP2, DC2, RACK21))
214+ .put(TOKEN05, host(IP3, DC1, RACK11))
215+ .put(TOKEN07, host(IP4, DC2, RACK21))
216+ .put(TOKEN13, host(IP1, DC1, RACK11))
217+ .put(TOKEN15, host(IP2, DC2, RACK21))
218+ .put(TOKEN17, host(IP3, DC1, RACK11))
219+ .put(TOKEN19, host(IP4, DC2, RACK21))
220+ .build();
220221
221222 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 1), rf(DC2, 1));
222223
@@ -235,22 +236,22 @@
235236 @Test(groups = "unit")
236237 public void networkTopologyWithSimple3DCLayoutTest() {
237238 List<Token> ring = ImmutableList.<Token>builder()
238- .add(TOKEN01)
239- .add(TOKEN05)
240- .add(TOKEN09)
241- .add(TOKEN11)
242- .add(TOKEN15)
243- .add(TOKEN19)
244- .build();
239+ .add(TOKEN01)
240+ .add(TOKEN05)
241+ .add(TOKEN09)
242+ .add(TOKEN11)
243+ .add(TOKEN15)
244+ .add(TOKEN19)
245+ .build();
245246
246247 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
247- .put(TOKEN01, host(IP1, DC1, RACK11))
248- .put(TOKEN05, host(IP2, DC2, RACK21))
249- .put(TOKEN09, host(IP3, DC3, RACK31))
250- .put(TOKEN11, host(IP1, DC1, RACK11))
251- .put(TOKEN15, host(IP2, DC2, RACK21))
252- .put(TOKEN19, host(IP3, DC3, RACK31))
253- .build();
248+ .put(TOKEN01, host(IP1, DC1, RACK11))
249+ .put(TOKEN05, host(IP2, DC2, RACK21))
250+ .put(TOKEN09, host(IP3, DC3, RACK31))
251+ .put(TOKEN11, host(IP1, DC1, RACK11))
252+ .put(TOKEN15, host(IP2, DC2, RACK21))
253+ .put(TOKEN19, host(IP3, DC3, RACK31))
254+ .build();
254255
255256 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 1), rf(DC2, 1), rf(DC3, 1));
256257
@@ -267,30 +268,30 @@
267268 @Test(groups = "unit")
268269 public void networkTopologyWithUnbalancedRingTest() {
269270 List<Token> ring = ImmutableList.<Token>builder()
270- .add(TOKEN01)
271- .add(TOKEN03)
272- .add(TOKEN05)
273- .add(TOKEN07)
274- .add(TOKEN09)
275- .add(TOKEN11)
276- .add(TOKEN13)
277- .add(TOKEN15)
278- .add(TOKEN17)
279- .add(TOKEN19)
280- .build();
271+ .add(TOKEN01)
272+ .add(TOKEN03)
273+ .add(TOKEN05)
274+ .add(TOKEN07)
275+ .add(TOKEN09)
276+ .add(TOKEN11)
277+ .add(TOKEN13)
278+ .add(TOKEN15)
279+ .add(TOKEN17)
280+ .add(TOKEN19)
281+ .build();
281282
282283 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
283- .put(TOKEN01, host(IP1, DC1, RACK11))
284- .put(TOKEN03, host(IP1, DC1, RACK11))
285- .put(TOKEN05, host(IP2, DC2, RACK21))
286- .put(TOKEN07, host(IP3, DC1, RACK11))
287- .put(TOKEN09, host(IP4, DC2, RACK21))
288- .put(TOKEN11, host(IP1, DC1, RACK11))
289- .put(TOKEN13, host(IP1, DC1, RACK11))
290- .put(TOKEN15, host(IP2, DC2, RACK21))
291- .put(TOKEN17, host(IP3, DC1, RACK11))
292- .put(TOKEN19, host(IP4, DC2, RACK21))
293- .build();
284+ .put(TOKEN01, host(IP1, DC1, RACK11))
285+ .put(TOKEN03, host(IP1, DC1, RACK11))
286+ .put(TOKEN05, host(IP2, DC2, RACK21))
287+ .put(TOKEN07, host(IP3, DC1, RACK11))
288+ .put(TOKEN09, host(IP4, DC2, RACK21))
289+ .put(TOKEN11, host(IP1, DC1, RACK11))
290+ .put(TOKEN13, host(IP1, DC1, RACK11))
291+ .put(TOKEN15, host(IP2, DC2, RACK21))
292+ .put(TOKEN17, host(IP3, DC1, RACK11))
293+ .put(TOKEN19, host(IP4, DC2, RACK21))
294+ .build();
294295
295296 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2));
296297
@@ -311,42 +312,42 @@
311312 @Test(groups = "unit")
312313 public void networkTopologyWithDCMultirackLayoutTest() {
313314 List<Token> ring = ImmutableList.<Token>builder()
314- .add(TOKEN01)
315- .add(TOKEN02)
316- .add(TOKEN03)
317- .add(TOKEN04)
318- .add(TOKEN05)
319- .add(TOKEN06)
320- .add(TOKEN07)
321- .add(TOKEN08)
322- .add(TOKEN12)
323- .add(TOKEN13)
324- .add(TOKEN14)
325- .add(TOKEN15)
326- .add(TOKEN16)
327- .add(TOKEN17)
328- .add(TOKEN18)
329- .add(TOKEN19)
330- .build();
315+ .add(TOKEN01)
316+ .add(TOKEN02)
317+ .add(TOKEN03)
318+ .add(TOKEN04)
319+ .add(TOKEN05)
320+ .add(TOKEN06)
321+ .add(TOKEN07)
322+ .add(TOKEN08)
323+ .add(TOKEN12)
324+ .add(TOKEN13)
325+ .add(TOKEN14)
326+ .add(TOKEN15)
327+ .add(TOKEN16)
328+ .add(TOKEN17)
329+ .add(TOKEN18)
330+ .add(TOKEN19)
331+ .build();
331332
332333 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
333- .put(TOKEN01, host(IP1, DC1, RACK11))
334- .put(TOKEN02, host(IP2, DC2, RACK21))
335- .put(TOKEN03, host(IP3, DC1, RACK12))
336- .put(TOKEN04, host(IP4, DC2, RACK22))
337- .put(TOKEN05, host(IP5, DC1, RACK11))
338- .put(TOKEN06, host(IP6, DC2, RACK21))
339- .put(TOKEN07, host(IP7, DC1, RACK12))
340- .put(TOKEN08, host(IP8, DC2, RACK22))
341- .put(TOKEN12, host(IP1, DC1, RACK11))
342- .put(TOKEN13, host(IP2, DC2, RACK21))
343- .put(TOKEN14, host(IP3, DC1, RACK12))
344- .put(TOKEN15, host(IP4, DC2, RACK22))
345- .put(TOKEN16, host(IP5, DC1, RACK11))
346- .put(TOKEN17, host(IP6, DC2, RACK21))
347- .put(TOKEN18, host(IP7, DC1, RACK12))
348- .put(TOKEN19, host(IP8, DC2, RACK22))
349- .build();
334+ .put(TOKEN01, host(IP1, DC1, RACK11))
335+ .put(TOKEN02, host(IP2, DC2, RACK21))
336+ .put(TOKEN03, host(IP3, DC1, RACK12))
337+ .put(TOKEN04, host(IP4, DC2, RACK22))
338+ .put(TOKEN05, host(IP5, DC1, RACK11))
339+ .put(TOKEN06, host(IP6, DC2, RACK21))
340+ .put(TOKEN07, host(IP7, DC1, RACK12))
341+ .put(TOKEN08, host(IP8, DC2, RACK22))
342+ .put(TOKEN12, host(IP1, DC1, RACK11))
343+ .put(TOKEN13, host(IP2, DC2, RACK21))
344+ .put(TOKEN14, host(IP3, DC1, RACK12))
345+ .put(TOKEN15, host(IP4, DC2, RACK22))
346+ .put(TOKEN16, host(IP5, DC1, RACK11))
347+ .put(TOKEN17, host(IP6, DC2, RACK21))
348+ .put(TOKEN18, host(IP7, DC1, RACK12))
349+ .put(TOKEN19, host(IP8, DC2, RACK22))
350+ .build();
350351
351352 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2));
352353
@@ -373,44 +374,44 @@
373374 @Test(groups = "unit")
374375 public void networkTopologyWithMultirackHostSkippingTest1() {
375376 List<Token> ring = ImmutableList.<Token>builder()
376- .add(TOKEN01)
377- .add(TOKEN02)
378- .add(TOKEN03)
379- .add(TOKEN04)
380- .add(TOKEN05)
381- .add(TOKEN06)
382- .add(TOKEN07)
383- .add(TOKEN08)
384- .add(TOKEN12)
385- .add(TOKEN13)
386- .add(TOKEN14)
387- .add(TOKEN15)
388- .add(TOKEN16)
389- .add(TOKEN17)
390- .add(TOKEN18)
391- .add(TOKEN19)
392- .build();
377+ .add(TOKEN01)
378+ .add(TOKEN02)
379+ .add(TOKEN03)
380+ .add(TOKEN04)
381+ .add(TOKEN05)
382+ .add(TOKEN06)
383+ .add(TOKEN07)
384+ .add(TOKEN08)
385+ .add(TOKEN12)
386+ .add(TOKEN13)
387+ .add(TOKEN14)
388+ .add(TOKEN15)
389+ .add(TOKEN16)
390+ .add(TOKEN17)
391+ .add(TOKEN18)
392+ .add(TOKEN19)
393+ .build();
393394
394395 //this is to simulate when we hit the same rack in a DC first as a second replica
395396 //so that'll get skipped and re-added later as a third
396397 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
397- .put(TOKEN01, host(IP1, DC1, RACK11))
398- .put(TOKEN02, host(IP2, DC2, RACK21))
399- .put(TOKEN03, host(IP3, DC1, RACK11))
400- .put(TOKEN04, host(IP4, DC2, RACK21))
401- .put(TOKEN05, host(IP5, DC1, RACK12))
402- .put(TOKEN06, host(IP6, DC2, RACK22))
403- .put(TOKEN07, host(IP7, DC1, RACK12))
404- .put(TOKEN08, host(IP8, DC2, RACK22))
405- .put(TOKEN12, host(IP1, DC1, RACK11))
406- .put(TOKEN13, host(IP2, DC2, RACK21))
407- .put(TOKEN14, host(IP3, DC1, RACK11))
408- .put(TOKEN15, host(IP4, DC2, RACK21))
409- .put(TOKEN16, host(IP5, DC1, RACK12))
410- .put(TOKEN17, host(IP6, DC2, RACK22))
411- .put(TOKEN18, host(IP7, DC1, RACK12))
412- .put(TOKEN19, host(IP8, DC2, RACK22))
413- .build();
398+ .put(TOKEN01, host(IP1, DC1, RACK11))
399+ .put(TOKEN02, host(IP2, DC2, RACK21))
400+ .put(TOKEN03, host(IP3, DC1, RACK11))
401+ .put(TOKEN04, host(IP4, DC2, RACK21))
402+ .put(TOKEN05, host(IP5, DC1, RACK12))
403+ .put(TOKEN06, host(IP6, DC2, RACK22))
404+ .put(TOKEN07, host(IP7, DC1, RACK12))
405+ .put(TOKEN08, host(IP8, DC2, RACK22))
406+ .put(TOKEN12, host(IP1, DC1, RACK11))
407+ .put(TOKEN13, host(IP2, DC2, RACK21))
408+ .put(TOKEN14, host(IP3, DC1, RACK11))
409+ .put(TOKEN15, host(IP4, DC2, RACK21))
410+ .put(TOKEN16, host(IP5, DC1, RACK12))
411+ .put(TOKEN17, host(IP6, DC2, RACK22))
412+ .put(TOKEN18, host(IP7, DC1, RACK12))
413+ .put(TOKEN19, host(IP8, DC2, RACK22))
414+ .build();
414415
415416 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 3), rf(DC2, 3));
416417
@@ -438,42 +439,42 @@
438439 @Test(groups = "unit")
439440 public void networkTopologyWithMultirackHostSkippingTest2() {
440441 List<Token> ring = ImmutableList.<Token>builder()
441- .add(TOKEN01)
442- .add(TOKEN02)
443- .add(TOKEN03)
444- .add(TOKEN04)
445- .add(TOKEN05)
446- .add(TOKEN06)
447- .add(TOKEN07)
448- .add(TOKEN08)
449- .add(TOKEN12)
450- .add(TOKEN13)
451- .add(TOKEN14)
452- .add(TOKEN15)
453- .add(TOKEN16)
454- .add(TOKEN17)
455- .add(TOKEN18)
456- .add(TOKEN19)
457- .build();
442+ .add(TOKEN01)
443+ .add(TOKEN02)
444+ .add(TOKEN03)
445+ .add(TOKEN04)
446+ .add(TOKEN05)
447+ .add(TOKEN06)
448+ .add(TOKEN07)
449+ .add(TOKEN08)
450+ .add(TOKEN12)
451+ .add(TOKEN13)
452+ .add(TOKEN14)
453+ .add(TOKEN15)
454+ .add(TOKEN16)
455+ .add(TOKEN17)
456+ .add(TOKEN18)
457+ .add(TOKEN19)
458+ .build();
458459
459460 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
460- .put(TOKEN01, host(IP1, DC1, RACK11))
461- .put(TOKEN02, host(IP1, DC1, RACK11))
462- .put(TOKEN03, host(IP3, DC1, RACK11))
463- .put(TOKEN04, host(IP3, DC1, RACK11))
464- .put(TOKEN05, host(IP5, DC1, RACK12))
465- .put(TOKEN06, host(IP5, DC1, RACK12))
466- .put(TOKEN07, host(IP7, DC1, RACK12))
467- .put(TOKEN08, host(IP7, DC1, RACK12))
468- .put(TOKEN12, host(IP2, DC2, RACK21))
469- .put(TOKEN13, host(IP2, DC2, RACK21))
470- .put(TOKEN14, host(IP4, DC2, RACK21))
471- .put(TOKEN15, host(IP4, DC2, RACK21))
472- .put(TOKEN16, host(IP6, DC2, RACK22))
473- .put(TOKEN17, host(IP6, DC2, RACK22))
474- .put(TOKEN18, host(IP8, DC2, RACK22))
475- .put(TOKEN19, host(IP8, DC2, RACK22))
476- .build();
461+ .put(TOKEN01, host(IP1, DC1, RACK11))
462+ .put(TOKEN02, host(IP1, DC1, RACK11))
463+ .put(TOKEN03, host(IP3, DC1, RACK11))
464+ .put(TOKEN04, host(IP3, DC1, RACK11))
465+ .put(TOKEN05, host(IP5, DC1, RACK12))
466+ .put(TOKEN06, host(IP5, DC1, RACK12))
467+ .put(TOKEN07, host(IP7, DC1, RACK12))
468+ .put(TOKEN08, host(IP7, DC1, RACK12))
469+ .put(TOKEN12, host(IP2, DC2, RACK21))
470+ .put(TOKEN13, host(IP2, DC2, RACK21))
471+ .put(TOKEN14, host(IP4, DC2, RACK21))
472+ .put(TOKEN15, host(IP4, DC2, RACK21))
473+ .put(TOKEN16, host(IP6, DC2, RACK22))
474+ .put(TOKEN17, host(IP6, DC2, RACK22))
475+ .put(TOKEN18, host(IP8, DC2, RACK22))
476+ .put(TOKEN19, host(IP8, DC2, RACK22))
477+ .build();
477478
478479 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 3), rf(DC2, 3));
479480
@@ -501,42 +502,42 @@
501502 public void networkTopologyWithMultirackHostSkippingTest3() {
502503 //this is the same topology as in the previous test, but with different rfs
503504 List<Token> ring = ImmutableList.<Token>builder()
504- .add(TOKEN01)
505- .add(TOKEN02)
506- .add(TOKEN03)
507- .add(TOKEN04)
508- .add(TOKEN05)
509- .add(TOKEN06)
510- .add(TOKEN07)
511- .add(TOKEN08)
512- .add(TOKEN12)
513- .add(TOKEN13)
514- .add(TOKEN14)
515- .add(TOKEN15)
516- .add(TOKEN16)
517- .add(TOKEN17)
518- .add(TOKEN18)
519- .add(TOKEN19)
520- .build();
505+ .add(TOKEN01)
506+ .add(TOKEN02)
507+ .add(TOKEN03)
508+ .add(TOKEN04)
509+ .add(TOKEN05)
510+ .add(TOKEN06)
511+ .add(TOKEN07)
512+ .add(TOKEN08)
513+ .add(TOKEN12)
514+ .add(TOKEN13)
515+ .add(TOKEN14)
516+ .add(TOKEN15)
517+ .add(TOKEN16)
518+ .add(TOKEN17)
519+ .add(TOKEN18)
520+ .add(TOKEN19)
521+ .build();
521522
522523 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
523- .put(TOKEN01, host(IP1, DC1, RACK11))
524- .put(TOKEN02, host(IP1, DC1, RACK11))
525- .put(TOKEN03, host(IP3, DC1, RACK11))
526- .put(TOKEN04, host(IP3, DC1, RACK11))
527- .put(TOKEN05, host(IP5, DC1, RACK12))
528- .put(TOKEN06, host(IP5, DC1, RACK12))
529- .put(TOKEN07, host(IP7, DC1, RACK12))
530- .put(TOKEN08, host(IP7, DC1, RACK12))
531- .put(TOKEN12, host(IP2, DC2, RACK21))
532- .put(TOKEN13, host(IP2, DC2, RACK21))
533- .put(TOKEN14, host(IP4, DC2, RACK21))
534- .put(TOKEN15, host(IP4, DC2, RACK21))
535- .put(TOKEN16, host(IP6, DC2, RACK22))
536- .put(TOKEN17, host(IP6, DC2, RACK22))
537- .put(TOKEN18, host(IP8, DC2, RACK22))
538- .put(TOKEN19, host(IP8, DC2, RACK22))
539- .build();
524+ .put(TOKEN01, host(IP1, DC1, RACK11))
525+ .put(TOKEN02, host(IP1, DC1, RACK11))
526+ .put(TOKEN03, host(IP3, DC1, RACK11))
527+ .put(TOKEN04, host(IP3, DC1, RACK11))
528+ .put(TOKEN05, host(IP5, DC1, RACK12))
529+ .put(TOKEN06, host(IP5, DC1, RACK12))
530+ .put(TOKEN07, host(IP7, DC1, RACK12))
531+ .put(TOKEN08, host(IP7, DC1, RACK12))
532+ .put(TOKEN12, host(IP2, DC2, RACK21))
533+ .put(TOKEN13, host(IP2, DC2, RACK21))
534+ .put(TOKEN14, host(IP4, DC2, RACK21))
535+ .put(TOKEN15, host(IP4, DC2, RACK21))
536+ .put(TOKEN16, host(IP6, DC2, RACK22))
537+ .put(TOKEN17, host(IP6, DC2, RACK22))
538+ .put(TOKEN18, host(IP8, DC2, RACK22))
539+ .put(TOKEN19, host(IP8, DC2, RACK22))
540+ .build();
540541
541542 //all nodes will contain all data, question is the replica order
542543 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 4), rf(DC2, 4));
@@ -589,24 +590,24 @@
589590 @Test(groups = "unit")
590591 public void networkTopologyStrategyNoNodesInDCTest() {
591592 long t1 = System.currentTimeMillis();
592- Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2))
593+ Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2))
593594 .computeTokenToReplicaMap(largeRingTokenToPrimary, largeRing);
594595 assertThat(System.currentTimeMillis() - t1).isLessThan(10000);
595596
596597 InetSocketAddress currNode = null;
597598 InetSocketAddress nextNode;
598599 for (int node = 0; node < 99; node++) { // 100th wraps so doesn't match this, check after
599- if(currNode == null) {
600+ if (currNode == null) {
600601 currNode = socketAddress("127.0.0." + node);
601602 }
602- nextNode = socketAddress("127.0.0." + (node+1));
603+ nextNode = socketAddress("127.0.0." + (node + 1));
603604 for (int vnodes = 0; vnodes < 256; vnodes++) {
604605 Token token = token("" + ((node * 256) + vnodes));
605606 assertReplicaPlacement(replicaMap, token, currNode, nextNode);
606607 }
607608 currNode = nextNode;
608609 }
609- assertReplicaPlacement(replicaMap, token(""+ 99 * 256), currNode, socketAddress("127.0.0.0"));
610+ assertReplicaPlacement(replicaMap, token("" + 99 * 256), currNode, socketAddress("127.0.0.0"));
610611 }
611612
612613
@@ -642,30 +643,30 @@
642643 logger.addAppender(logs);
643644
644645 List<Token> ring = ImmutableList.<Token>builder()
645- .add(TOKEN01)
646- .add(TOKEN02)
647- .add(TOKEN03)
648- .add(TOKEN04)
649- .build();
646+ .add(TOKEN01)
647+ .add(TOKEN02)
648+ .add(TOKEN03)
649+ .add(TOKEN04)
650+ .build();
650651
651652 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
652- .put(TOKEN01, host(IP1, DC1, RACK11))
653- .put(TOKEN02, host(IP2, DC1, RACK12))
654- .put(TOKEN03, host(IP3, DC2, RACK21))
655- .put(TOKEN04, host(IP4, DC2, RACK22))
656- .build();
653+ .put(TOKEN01, host(IP1, DC1, RACK11))
654+ .put(TOKEN02, host(IP2, DC1, RACK12))
655+ .put(TOKEN03, host(IP3, DC2, RACK21))
656+ .put(TOKEN04, host(IP4, DC2, RACK22))
657+ .build();
657658
658659 // Wrong configuration: impossible replication factor for DC2
659660 networkTopologyStrategy(rf(DC1, 2), rf(DC2, 3))
660- .computeTokenToReplicaMap(tokenToPrimary, ring);
661+ .computeTokenToReplicaMap(tokenToPrimary, ring);
661662 assertThat(logs.getNext())
662- .contains("Error while computing token map for datacenter DC2");
663+ .contains("Error while computing token map for datacenter DC2");
663664
664665 // Wrong configuration: non-existing datacenter
665666 networkTopologyStrategy(rf(DC1, 2), rf("does_not_exist", 2))
666- .computeTokenToReplicaMap(tokenToPrimary, ring);
667+ .computeTokenToReplicaMap(tokenToPrimary, ring);
667668 assertThat(logs.getNext())
668- .contains("Error while computing token map for datacenter does_not_exist");
669+ .contains("Error while computing token map for datacenter does_not_exist");
669670
670671 logger.setLevel(null);
671672 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 +15 −17
@@ -15,15 +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 com.google.common.collect.Lists;
23-import org.testng.annotations.Test;
24-
2524 import static org.assertj.core.api.Assertions.assertThat;
26-import static org.testng.Assert.fail;
2725
2826 public class OPPTokenFactoryTest {
2927 private static final Token.Factory factory = Token.OPPToken.FACTORY;
@@ -34,8 +32,8 @@
3432 public void should_split_range() {
3533 List<Token> splits = factory.split(token('a'), token('d'), 3);
3634 assertThat(splits).containsExactly(
37- token('b'),
38- token('c')
35+ token('b'),
36+ token('c')
3937 );
4038 }
4139
@@ -47,38 +45,38 @@
4745 // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring)
4846 List<Token> splits = factory.split(minToken, zero, 3);
4947 assertThat(splits).containsExactly(
50- zero,
51- zero
48+ zero,
49+ zero
5250 );
5351 }
5452
5553 @Test(groups = "unit")
5654 public void should_strip_trailing_0_bytes() {
57- Token with0Bytes = factory.deserialize(ByteBuffer.wrap(new byte[]{4,0,0,0}));
55+ Token with0Bytes = factory.deserialize(ByteBuffer.wrap(new byte[]{4, 0, 0, 0}));
5856 Token without0Bytes = factory.deserialize(ByteBuffer.wrap(new byte[]{4}));
5957 Token fromStringWith0Bytes = factory.fromString("040000");
6058
6159 assertThat(with0Bytes)
62- .isEqualTo(without0Bytes)
63- .isEqualTo(fromStringWith0Bytes);
60+ .isEqualTo(without0Bytes)
61+ .isEqualTo(fromStringWith0Bytes);
6462
6563 Token withMixed0Bytes = factory.fromString("0004000400");
6664 Token withoutMixed0Bytes = factory.fromString("00040004");
6765
6866 assertThat(withMixed0Bytes)
69- .isEqualTo(withoutMixed0Bytes);
67+ .isEqualTo(withoutMixed0Bytes);
7068 }
7169
7270 @Test(groups = "unit")
7371 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++) {
72+ for (int start = 1; start < 128; start++) {
73+ for (int end = start; end < start; end++) {
7674 // Take the midpoint of the ring and offset by the midpoint of start+end.
7775 long expected = 0x81 + ((start + end) / 2);
7876 TokenRange tr = new TokenRange(token(start), token(end), factory);
7977 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));
78+ .as("Expected 0x%X for start: %d, end: %d", expected, start, end)
79+ .containsExactly(token(expected));
8280 }
8381 }
8482 }
@@ -89,7 +87,7 @@
8987 }
9088
9189 private Token token(char c) {
92- return new Token.OPPToken(ByteBuffer.wrap(new byte[]{ (byte)c }));
90+ return new Token.OPPToken(ByteBuffer.wrap(new byte[]{(byte) c}));
9391 }
9492
9593 private 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/PoolingOptionsTest.java +3 −1
@@ -19,7 +19,9 @@
1919
2020 import java.util.Collection;
2121 import java.util.Collections;
22-import java.util.concurrent.*;
22+import java.util.concurrent.LinkedBlockingQueue;
23+import java.util.concurrent.ThreadPoolExecutor;
24+import java.util.concurrent.TimeUnit;
2325
2426 import static org.assertj.core.api.Assertions.assertThat;
2527 import static org.mockito.Matchers.any;
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +30 −27
@@ -15,25 +15,22 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.util.*;
20-
18+import com.datastax.driver.core.exceptions.InvalidQueryException;
19+import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
2120 import com.google.common.collect.ImmutableList;
2221 import org.testng.annotations.Test;
2322
23+import java.net.InetAddress;
24+import java.util.*;
25+
26+import static com.datastax.driver.core.TestUtils.*;
2427 import static org.assertj.core.api.Assertions.assertThat;
2528 import static org.testng.Assert.assertEquals;
2629 import static org.testng.Assert.assertTrue;
2730
28-import com.datastax.driver.core.exceptions.InvalidQueryException;
29-import com.datastax.driver.core.exceptions.NoHostAvailableException;
30-import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
31-
32-import static com.datastax.driver.core.TestUtils.*;
33-
3431 /**
3532 * Prepared statement tests.
36- *
33+ * <p/>
3734 * Note: this class also happens to test all the get methods from Row.
3835 */
3936 public class PreparedStatementTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -163,7 +160,8 @@
163160
164161 String name = "c_list_" + rawType;
165162 DataType type = DataType.list(rawType);
166- List<Object> value = (List<Object>)getFixedValue(type);;
163+ List<Object> value = (List<Object>) getFixedValue(type);
164+ ;
167165 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
168166 BoundStatement bs = ps.bind();
169167 session.execute(setBoundValue(bs, name, type, value));
@@ -187,7 +185,8 @@
187185
188186 String name = "c_list_" + rawType;
189187 DataType type = DataType.list(rawType);
190- List<Object> value = (List<Object>)getFixedValue2(type);;
188+ List<Object> value = (List<Object>) getFixedValue2(type);
189+ ;
191190 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
192191 BoundStatement bs = ps.bind();
193192 session.execute(setBoundValue(bs, name, type, value));
@@ -208,7 +207,8 @@
208207
209208 String name = "c_set_" + rawType;
210209 DataType type = DataType.set(rawType);
211- Set<Object> value = (Set<Object>)getFixedValue(type);;
210+ Set<Object> value = (Set<Object>) getFixedValue(type);
211+ ;
212212 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
213213 BoundStatement bs = ps.bind();
214214 session.execute(setBoundValue(bs, name, type, value));
@@ -232,7 +232,8 @@
232232
233233 String name = "c_set_" + rawType;
234234 DataType type = DataType.set(rawType);
235- Set<Object> value = (Set<Object>)getFixedValue2(type);;
235+ Set<Object> value = (Set<Object>) getFixedValue2(type);
236+ ;
236237 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
237238 BoundStatement bs = ps.bind();
238239 session.execute(setBoundValue(bs, name, type, value));
@@ -258,7 +259,8 @@
258259
259260 String name = "c_map_" + rawKeyType + '_' + rawValueType;
260261 DataType type = DataType.map(rawKeyType, rawValueType);
261- Map<Object, Object> value = (Map<Object, Object>)getFixedValue(type);;
262+ Map<Object, Object> value = (Map<Object, Object>) getFixedValue(type);
263+ ;
262264 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
263265 BoundStatement bs = ps.bind();
264266 session.execute(setBoundValue(bs, name, type, value));
@@ -288,7 +290,8 @@
288290
289291 String name = "c_map_" + rawKeyType + '_' + rawValueType;
290292 DataType type = DataType.map(rawKeyType, rawValueType);
291- Map<Object, Object> value = (Map<Object, Object>)getFixedValue2(type);;
293+ Map<Object, Object> value = (Map<Object, Object>) getFixedValue2(type);
294+ ;
292295 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
293296 BoundStatement bs = ps.bind();
294297 session.execute(setBoundValue(bs, name, type, value));
@@ -341,7 +344,7 @@
341344 * Prints the table definitions that will be used in testing
342345 * (for exporting purposes)
343346 */
344- @Test(groups = { "docs" })
347+ @Test(groups = {"docs"})
345348 public void printTableDefinitions() {
346349 for (String definition : getTableDefinitions()) {
347350 System.out.println(definition);
@@ -379,21 +382,21 @@
379382 }
380383 }
381384
382- @Test(groups="short")
385+ @Test(groups = "short")
383386 public void should_set_routing_key_on_case_insensitive_keyspace_and_table() {
384- session.execute(String.format("CREATE TABLE %s.foo (i int PRIMARY KEY)",keyspace));
387+ session.execute(String.format("CREATE TABLE %s.foo (i int PRIMARY KEY)", keyspace));
385388
386- PreparedStatement ps = session.prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)",keyspace));
389+ PreparedStatement ps = session.prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)", keyspace));
387390 BoundStatement bs = ps.bind(1);
388391 assertThat(bs.getRoutingKey()).isNotNull();
389392 }
390393
391- @Test(groups="short")
394+ @Test(groups = "short")
392395 public void should_set_routing_key_on_case_sensitive_keyspace_and_table() {
393396 session.execute("CREATE KEYSPACE \"Test\" WITH replication = { "
394- + " 'class': 'SimpleStrategy',"
395- + " 'replication_factor': '1'"
396- + "}");
397+ + " 'class': 'SimpleStrategy',"
398+ + " 'replication_factor': '1'"
399+ + "}");
397400 session.execute("CREATE TABLE \"Test\".\"Foo\" (i int PRIMARY KEY)");
398401
399402 PreparedStatement ps = session.prepare("INSERT INTO \"Test\".\"Foo\" (i) VALUES (?)");
@@ -401,11 +404,11 @@
401404 assertThat(bs.getRoutingKey()).isNotNull();
402405 }
403406
404- @Test(groups="short", expectedExceptions = InvalidQueryException.class)
407+ @Test(groups = "short", expectedExceptions = InvalidQueryException.class)
405408 public void should_fail_when_prepared_on_another_cluster() throws Exception {
406409 Cluster otherCluster = Cluster.builder()
407- .addContactPointsWithPorts(ImmutableList.of(hostAddress))
408- .build();
410+ .addContactPointsWithPorts(ImmutableList.of(hostAddress))
411+ .build();
409412 try {
410413 PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
411414 BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost"));
modified driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java +23 −24
@@ -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,29 +42,29 @@
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.varchar(), "text")
57- .put(DataType.timestamp(), new Date(872835240000L))
58- .put(DataType.timeuuid(), UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"))
59- .put(DataType.uuid(), UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"))
60- .put(DataType.varint(), new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000"))
61- .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.varchar(), "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();
6261
6362 // Check that we cover all types (except counter)
6463 List<DataType> tmp = Lists.newArrayList(DataType.allPrimitiveTypes());
6564 tmp.removeAll(result.keySet());
6665 assertThat(tmp)
67- .as("new datatype not covered in test")
68- .containsOnly(DataType.counter());
66+ .as("new datatype not covered in test")
67+ .containsOnly(DataType.counter());
6968
7069 return result;
7170 } 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/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();
@@ -285,7 +282,7 @@
285282 // Reset the spy and count the number of connections attempts for 1 reconnect
286283 reset(socketOptions);
287284 host1.tryReconnectOnce();
288- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
285+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
289286 // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4
290287 // but the one from the reconnection attempt gets reused).
291288 verify(socketOptions, times(4)).getKeepAlive();
@@ -297,7 +294,9 @@
297294 }
298295 }
299296
300- /** Extends the plain text auth provider to track how many times the credentials have been requested */
297+ /**
298+ * Extends the plain text auth provider to track how many times the credentials have been requested
299+ */
301300 static class CountingAuthProvider extends PlainTextAuthProvider {
302301 final AtomicInteger count = new AtomicInteger();
303302
@@ -330,8 +329,8 @@
330329 public HostDistance distance(Host host) {
331330 HostDistance distance = distances.get(host);
332331 return (distance != null)
333- ? distance
334- : super.distance(host);
332+ ? distance
333+ : super.distance(host);
335334 }
336335
337336 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 +167 −174
@@ -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.google.common.collect.ImmutableList;
2520 import com.google.common.collect.ImmutableMap;
@@ -31,20 +26,18 @@
3126 import org.slf4j.Logger;
3227 import org.slf4j.LoggerFactory;
3328
29+import java.util.List;
30+import java.util.Map;
31+import java.util.TreeSet;
32+import java.util.concurrent.TimeUnit;
33+
34+import static com.datastax.driver.core.Assertions.assertThat;
3435 import static org.scassandra.cql.MapType.map;
35-import static org.scassandra.cql.PrimitiveType.BIG_INT;
36-import static org.scassandra.cql.PrimitiveType.BOOLEAN;
37-import static org.scassandra.cql.PrimitiveType.DOUBLE;
38-import static org.scassandra.cql.PrimitiveType.INET;
39-import static org.scassandra.cql.PrimitiveType.INT;
40-import static org.scassandra.cql.PrimitiveType.TEXT;
41-import static org.scassandra.cql.PrimitiveType.UUID;
36+import static org.scassandra.cql.PrimitiveType.*;
4237 import static org.scassandra.cql.SetType.set;
4338 import static org.scassandra.http.client.PrimingRequest.then;
4439 import static org.scassandra.http.client.types.ColumnMetadata.column;
4540
46-import static com.datastax.driver.core.Assertions.assertThat;
47-
4841 public class ScassandraCluster {
4942
5043 private static final Logger logger = LoggerFactory.getLogger(ScassandraCluster.class);
@@ -53,25 +46,25 @@
5346
5447 private final List<Scassandra> instances;
5548
56- private final Map<Integer,List<Scassandra>> dcNodeMap;
49+ private final Map<Integer, List<Scassandra>> dcNodeMap;
5750
58- private final List<Map<String,? extends Object>> keyspaceRows;
51+ private final List<Map<String, ? extends Object>> keyspaceRows;
5952
60- ScassandraCluster(Integer[] nodes, String ipPrefix, int binaryPort, int adminPort, List<Map<String,? extends Object>> keyspaceRows) {
53+ ScassandraCluster(Integer[] nodes, String ipPrefix, int binaryPort, int adminPort, List<Map<String, ? extends Object>> keyspaceRows) {
6154 this.ipPrefix = ipPrefix;
6255
6356 int node = 1;
6457 ImmutableList.Builder<Scassandra> instanceListBuilder = ImmutableList.builder();
65- ImmutableMap.Builder<Integer, List<Scassandra>> dcNodeMapBuilder = ImmutableMap.builder();
66- for(int dc=0; dc < nodes.length; dc++) {
58+ ImmutableMap.Builder<Integer, List<Scassandra>> dcNodeMapBuilder = ImmutableMap.builder();
59+ for (int dc = 0; dc < nodes.length; dc++) {
6760 ImmutableList.Builder<Scassandra> dcNodeListBuilder = ImmutableList.builder();
68- for(int n=0; n < nodes[dc]; n++) {
61+ for (int n = 0; n < nodes[dc]; n++) {
6962 String ip = ipPrefix + node++;
7063 Scassandra instance = ScassandraFactory.createServer(ip, binaryPort, ip, adminPort);
7164 instanceListBuilder = instanceListBuilder.add(instance);
7265 dcNodeListBuilder = dcNodeListBuilder.add(instance);
7366 }
74- dcNodeMapBuilder.put(dc+1, dcNodeListBuilder.build());
67+ dcNodeMapBuilder.put(dc + 1, dcNodeListBuilder.build());
7568 }
7669 instances = instanceListBuilder.build();
7770 dcNodeMap = dcNodeMapBuilder.build();
@@ -79,7 +72,7 @@
7972 }
8073
8174 public Scassandra node(int node) {
82- return instances.get(node-1);
75+ return instances.get(node - 1);
8376 }
8477
8578 public List<Scassandra> nodes() {
@@ -101,11 +94,11 @@
10194 public int ipSuffix(int dc, int node) {
10295 // TODO: Scassandra should be updated to include address to avoid O(n) lookup.
10396 int nodeCount = 0;
104- for(Integer dcNum : new TreeSet<Integer>(dcNodeMap.keySet())) {
97+ for (Integer dcNum : new TreeSet<Integer>(dcNodeMap.keySet())) {
10598 List<Scassandra> nodesInDc = dcNodeMap.get(dc);
106- for(int n = 0; n < nodesInDc.size(); n++) {
99+ for (int n = 0; n < nodesInDc.size(); n++) {
107100 nodeCount++;
108- if(dcNum == dc && n+1 == node) {
101+ if (dcNum == dc && n + 1 == node) {
109102 return nodeCount;
110103 }
111104 }
@@ -116,13 +109,13 @@
116109 public String address(int dc, int node) {
117110 // TODO: Scassandra should be updated to include address to avoid O(n) lookup.
118111 int ipSuffix = ipSuffix(dc, node);
119- return ipSuffix == -1 ? null : ipPrefix + ipSuffix;
112+ return ipSuffix == -1 ? null : ipPrefix + ipSuffix;
120113 }
121114
122115 public Host host(Cluster cluster, int dc, int node) {
123116 String address = address(dc, node);
124- for(Host host : cluster.getMetadata().getAllHosts()) {
125- if(host.getAddress().getHostAddress().equals(address)) {
117+ for (Host host : cluster.getMetadata().getAllHosts()) {
118+ if (host.getAddress().getHostAddress().equals(address)) {
126119 return host;
127120 }
128121 }
@@ -134,8 +127,8 @@
134127 }
135128
136129 public void init() {
137- for(Map.Entry<Integer, List<Scassandra>> dc : dcNodeMap.entrySet()) {
138- for(Scassandra node : dc.getValue()) {
130+ for (Map.Entry<Integer, List<Scassandra>> dc : dcNodeMap.entrySet()) {
131+ for (Scassandra node : dc.getValue()) {
139132 node.start();
140133 primeMetadata(node);
141134 }
@@ -144,7 +137,7 @@
144137
145138 public void stop() {
146139 logger.debug("Stopping ScassandraCluster.");
147- for(Scassandra node : instances) {
140+ for (Scassandra node : instances) {
148141 node.stop();
149142 }
150143 }
@@ -152,18 +145,18 @@
152145 /**
153146 * First stops each node in {@code dc} and then asserts that each node's {@link Host}
154147 * is marked down for the given {@link Cluster} instance within 10 seconds.
155- *
148+ * <p/>
156149 * If any of the nodes are the control host, this node is stopped last, to reduce
157150 * likelihood of control connection choosing a host that will be shut down.
158151 *
159152 * @param cluster cluster to wait for down statuses on.
160- * @param dc DC to stop.
153+ * @param dc DC to stop.
161154 */
162155 public void stopDC(Cluster cluster, int dc) {
163156 logger.debug("Stopping all nodes in {}.", datacenter(dc));
164157 // If any node is the control host, stop it last.
165158 int controlHost = -1;
166- for(int i = 1; i <= nodes(dc).size(); i++) {
159+ for (int i = 1; i <= nodes(dc).size(); i++) {
167160 int id = ipSuffix(dc, i);
168161 Host host = TestUtils.findHost(cluster, id);
169162 if (cluster.manager.controlConnection.connectedHost() == host) {
@@ -174,7 +167,7 @@
174167 stop(cluster, id);
175168 }
176169
177- if(controlHost != -1) {
170+ if (controlHost != -1) {
178171 stop(cluster, controlHost);
179172 }
180173 }
@@ -184,7 +177,7 @@
184177 * for the given {@link Cluster} instance within 10 seconds.
185178 *
186179 * @param cluster cluster to wait for down status on.
187- * @param node Node to stop.
180+ * @param node Node to stop.
188181 */
189182 public void stop(Cluster cluster, int node) {
190183 logger.debug("Stopping node {}.", node);
@@ -198,8 +191,8 @@
198191 * for the given {@link Cluster} instance within 10 seconds.
199192 *
200193 * @param cluster cluster to wait for down status on.
201- * @param dc Data center node is in.
202- * @param node Node to stop.
194+ * @param dc Data center node is in.
195+ * @param node Node to stop.
203196 */
204197 public void stop(Cluster cluster, int dc, int node) {
205198 logger.debug("Stopping node {} in {}.", node, datacenter(dc));
@@ -211,11 +204,11 @@
211204 * is marked up for the given {@link Cluster} instance within 10 seconds.
212205 *
213206 * @param cluster cluster to wait for up statuses on.
214- * @param dc DC to start.
207+ * @param dc DC to start.
215208 */
216209 public void startDC(Cluster cluster, int dc) {
217210 logger.debug("Starting all nodes in {}.", datacenter(dc));
218- for(int i = 1; i <= nodes(dc).size(); i++) {
211+ for (int i = 1; i <= nodes(dc).size(); i++) {
219212 int id = ipSuffix(dc, i);
220213 start(cluster, id);
221214 }
@@ -226,7 +219,7 @@
226219 * for the given {@link Cluster} instance within 10 seconds.
227220 *
228221 * @param cluster cluster to wait for up status on.
229- * @param node Node to start.
222+ * @param node Node to start.
230223 */
231224 public void start(Cluster cluster, int node) {
232225 logger.debug("Starting node {}.", node);
@@ -240,8 +233,8 @@
240233 * for the given {@link Cluster} instance within 10 seconds.
241234 *
242235 * @param cluster cluster to wait for up status on.
243- * @param dc Data center node is in.
244- * @param node Node to start.
236+ * @param dc Data center node is in.
237+ * @param node Node to start.
245238 */
246239 public void start(Cluster cluster, int dc, int node) {
247240 logger.debug("Starting node {} in {}.", node, datacenter(dc));
@@ -250,11 +243,11 @@
250243
251244 private List<Long> getTokensForDC(int dc) {
252245 // Offset DCs by dc * 100 to ensure unique tokens.
253- int offset = (dc-1) * 100;
246+ int offset = (dc - 1) * 100;
254247 int dcNodeCount = nodes(dc).size();
255248 List<Long> tokens = Lists.newArrayList(dcNodeCount);
256- for(int i = 0; i < dcNodeCount; i++) {
257- tokens.add((i * ((long)Math.pow(2, 64)/dcNodeCount) + offset));
249+ for (int i = 0; i < dcNodeCount; i++) {
250+ tokens.add((i * ((long) Math.pow(2, 64) / dcNodeCount) + offset));
258251 }
259252 return tokens;
260253 }
@@ -263,163 +256,163 @@
263256 PrimingClient client = node.primingClient();
264257 int nodeCount = 0;
265258
266- ImmutableList.Builder<Map<String,?>> rows = ImmutableList.builder();
267- for(Integer dc : new TreeSet<Integer>(dcNodeMap.keySet())) {
259+ ImmutableList.Builder<Map<String, ?>> rows = ImmutableList.builder();
260+ for (Integer dc : new TreeSet<Integer>(dcNodeMap.keySet())) {
268261 List<Scassandra> nodesInDc = dcNodeMap.get(dc);
269262 List<Long> tokens = getTokensForDC(dc);
270- for(int n = 0; n < nodesInDc.size(); n++) {
263+ for (int n = 0; n < nodesInDc.size(); n++) {
271264 String address = ipPrefix + ++nodeCount;
272265 Scassandra peer = nodesInDc.get(n);
273266 String query;
274- Map<String,Object> row;
267+ Map<String, Object> row;
275268 org.scassandra.http.client.types.ColumnMetadata[] metadata;
276- if(node == peer) { // prime system.local.
269+ if (node == peer) { // prime system.local.
277270 metadata = SELECT_LOCAL;
278271 query = "SELECT * FROM system.local WHERE key='local'";
279272 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", "2.1.8")
290- .put("tokens", ImmutableSet.of(tokens.get(n)))
291- .build();
273+ .put("key", "local")
274+ .put("bootstrapped", "COMPLETED")
275+ .put("broadcast_address", address)
276+ .put("cluster_name", "scassandra")
277+ .put("cql_version", "3.2.0")
278+ .put("data_center", datacenter(dc))
279+ .put("listen_address", address)
280+ .put("partitioner", "org.apache.cassandra.dht.Murmur3Partitioner")
281+ .put("rack", "rack1")
282+ .put("release_version", "2.1.8")
283+ .put("tokens", ImmutableSet.of(tokens.get(n)))
284+ .build();
292285 } else { // prime system.peers.
293286 query = "SELECT * FROM system.peers WHERE peer='" + address + "'";
294287 metadata = SELECT_PEERS;
295288 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", "2.1.8")
301- .put("tokens", ImmutableSet.of(Long.toString(tokens.get(n))))
302- .build();
289+ .put("peer", address)
290+ .put("rpc_address", address)
291+ .put("data_center", datacenter(dc))
292+ .put("rack", "rack1")
293+ .put("release_version", "2.1.8")
294+ .put("tokens", ImmutableSet.of(Long.toString(tokens.get(n))))
295+ .build();
303296 rows.add(row);
304297 }
305298 client.prime(PrimingRequest.queryBuilder()
306- .withQuery(query)
307- .withThen(then()
308- .withColumnTypes(metadata)
309- .withRows(row)
310- .build())
311- .build());
299+ .withQuery(query)
300+ .withThen(then()
301+ .withColumnTypes(metadata)
302+ .withRows(row)
303+ .build())
304+ .build());
312305 }
313306 }
314307
315308 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());
309+ .withQuery("SELECT * FROM system.peers")
310+ .withThen(then()
311+ .withColumnTypes(SELECT_PEERS)
312+ .withRows(rows.build())
313+ .build())
314+ .build());
322315
323316 // Needed to ensure cluster_name matches what we expect on connection.
324- Map<String,Object> clusterNameRow = ImmutableMap.<String,Object>builder()
325- .put("cluster_name", "scassandra")
326- .build();
317+ Map<String, Object> clusterNameRow = ImmutableMap.<String, Object>builder()
318+ .put("cluster_name", "scassandra")
319+ .build();
327320 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());
321+ .withQuery("select cluster_name from system.local")
322+ .withThen(then()
323+ .withColumnTypes(SELECT_CLUSTER_NAME)
324+ .withRows(clusterNameRow)
325+ .build())
326+ .build());
334327
335328
336329 // Prime keyspaces
337330 client.prime(PrimingRequest.queryBuilder()
338- .withQuery("SELECT * FROM system.schema_keyspaces")
339- .withThen(then()
340- .withColumnTypes(SELECT_SCHEMA_KEYSPACES)
341- .withRows(keyspaceRows)
342- .build())
343- .build());
331+ .withQuery("SELECT * FROM system.schema_keyspaces")
332+ .withThen(then()
333+ .withColumnTypes(SELECT_SCHEMA_KEYSPACES)
334+ .withRows(keyspaceRows)
335+ .build())
336+ .build());
344337 }
345338
346339 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_PEERS = {
347- column("peer", INET),
348- column("rpc_address", INET),
349- column("data_center", TEXT),
350- column("rack", TEXT),
351- column("release_version", TEXT),
352- column("tokens", set(TEXT))
340+ column("peer", INET),
341+ column("rpc_address", INET),
342+ column("data_center", TEXT),
343+ column("rack", TEXT),
344+ column("release_version", TEXT),
345+ column("tokens", set(TEXT))
353346 };
354347
355348 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_LOCAL = {
356- column("key", TEXT),
357- column("bootstrapped", TEXT),
358- column("broadcast_address", INET),
359- column("cluster_name", TEXT),
360- column("cql_version", TEXT),
361- column("data_center", TEXT),
362- column("listen_address", INET),
363- column("partitioner", TEXT),
364- column("rack", TEXT),
365- column("release_version", TEXT),
366- column("tokens", set(TEXT)),
349+ column("key", TEXT),
350+ column("bootstrapped", TEXT),
351+ column("broadcast_address", INET),
352+ column("cluster_name", TEXT),
353+ column("cql_version", TEXT),
354+ column("data_center", TEXT),
355+ column("listen_address", INET),
356+ column("partitioner", TEXT),
357+ column("rack", TEXT),
358+ column("release_version", TEXT),
359+ column("tokens", set(TEXT)),
367360 };
368361
369362 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_CLUSTER_NAME = {
370- column("cluster_name", TEXT)
363+ column("cluster_name", TEXT)
371364 };
372365
373366 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_KEYSPACES = {
374- column("durable_writes", BOOLEAN),
375- column("keyspace_name", TEXT),
376- column("strategy_class", TEXT),
377- column("strategy_options", TEXT)
367+ column("durable_writes", BOOLEAN),
368+ column("keyspace_name", TEXT),
369+ column("strategy_class", TEXT),
370+ column("strategy_options", TEXT)
378371 };
379372
380373 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_COLUMN_FAMILIES = {
381- column("bloom_filter_fp_chance", DOUBLE),
382- column("caching", TEXT),
383- column("cf_id", UUID),
384- column("column_aliases", TEXT),
385- column("columnfamily_name", TEXT),
386- column("comment", TEXT),
387- column("compaction_strategy_class", TEXT),
388- column("compaction_strategy_options", TEXT),
389- column("comparator", TEXT),
390- column("compression_parameters", TEXT),
391- column("default_time_to_live", INT),
392- column("default_validator", TEXT),
393- column("dropped_columns", map(TEXT, BIG_INT)),
394- column("gc_grace_seconds", INT),
395- column("index_interval", INT),
396- column("is_dense", BOOLEAN),
397- column("key_aliases", TEXT),
398- column("key_validator", TEXT),
399- column("keyspace_name", TEXT),
400- column("local_read_repair_chance", DOUBLE),
401- column("max_compaction_threshold", INT),
402- column("max_index_interval", INT),
403- column("memtable_flush_period_in_ms", INT),
404- column("min_compaction_threshold", INT),
405- column("min_index_interval", INT),
406- column("read_repair_chance", DOUBLE),
407- column("speculative_retry", TEXT),
408- column("subcomparator", TEXT),
409- column("type", TEXT),
410- column("value_alias", TEXT)
374+ column("bloom_filter_fp_chance", DOUBLE),
375+ column("caching", TEXT),
376+ column("cf_id", UUID),
377+ column("column_aliases", TEXT),
378+ column("columnfamily_name", TEXT),
379+ column("comment", TEXT),
380+ column("compaction_strategy_class", TEXT),
381+ column("compaction_strategy_options", TEXT),
382+ column("comparator", TEXT),
383+ column("compression_parameters", TEXT),
384+ column("default_time_to_live", INT),
385+ column("default_validator", TEXT),
386+ column("dropped_columns", map(TEXT, BIG_INT)),
387+ column("gc_grace_seconds", INT),
388+ column("index_interval", INT),
389+ column("is_dense", BOOLEAN),
390+ column("key_aliases", TEXT),
391+ column("key_validator", TEXT),
392+ column("keyspace_name", TEXT),
393+ column("local_read_repair_chance", DOUBLE),
394+ column("max_compaction_threshold", INT),
395+ column("max_index_interval", INT),
396+ column("memtable_flush_period_in_ms", INT),
397+ column("min_compaction_threshold", INT),
398+ column("min_index_interval", INT),
399+ column("read_repair_chance", DOUBLE),
400+ column("speculative_retry", TEXT),
401+ column("subcomparator", TEXT),
402+ column("type", TEXT),
403+ column("value_alias", TEXT)
411404 };
412405
413406 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_COLUMNS = {
414- column("column_name", TEXT),
415- column("columnfamily_name", TEXT),
416- column("component_index", INT),
417- column("index_name", TEXT),
418- column("index_options", TEXT),
419- column("index_type", TEXT),
420- column("keyspace_name", TEXT),
421- column("type", TEXT),
422- column("validator", TEXT),
407+ column("column_name", TEXT),
408+ column("columnfamily_name", TEXT),
409+ column("component_index", INT),
410+ column("index_name", TEXT),
411+ column("index_options", TEXT),
412+ column("index_type", TEXT),
413+ column("keyspace_name", TEXT),
414+ column("type", TEXT),
415+ column("validator", TEXT),
423416 };
424417
425418 public static ScassandraClusterBuilder builder() {
@@ -430,10 +423,10 @@
430423
431424 private Integer nodes[] = {1};
432425 private String ipPrefix = CCMBridge.IP_PREFIX;
433- private final List<Map<String,? extends Object>> keyspaceRows = Lists.newArrayList();
426+ private final List<Map<String, ? extends Object>> keyspaceRows = Lists.newArrayList();
434427
435428
436- public ScassandraClusterBuilder withNodes(Integer ... nodes) {
429+ public ScassandraClusterBuilder withNodes(Integer... nodes) {
437430 this.nodes = nodes;
438431 return this;
439432 }
@@ -444,20 +437,20 @@
444437 }
445438
446439 public ScassandraClusterBuilder withSimpleKeyspace(String name, int replicationFactor) {
447- Map<String,Object> simpleKeyspaceRow = ImmutableMap.<String,Object>builder()
448- .put("durable_writes", false)
449- .put("keyspace_name", name)
450- .put("strategy_class", "SimpleStrategy")
451- .put("strategy_options", "{\"replication_factor\":\"" + replicationFactor + "\"}")
452- .build();
440+ Map<String, Object> simpleKeyspaceRow = ImmutableMap.<String, Object>builder()
441+ .put("durable_writes", false)
442+ .put("keyspace_name", name)
443+ .put("strategy_class", "SimpleStrategy")
444+ .put("strategy_options", "{\"replication_factor\":\"" + replicationFactor + "\"}")
445+ .build();
453446
454447 keyspaceRows.add(simpleKeyspaceRow);
455448 return this;
456449 }
457450
458- public ScassandraClusterBuilder withNetworkTopologyKeyspace(String name, Map<Integer,Integer> replicationFactors) {
451+ public ScassandraClusterBuilder withNetworkTopologyKeyspace(String name, Map<Integer, Integer> replicationFactors) {
459452 StringBuilder strategyOptionsBuilder = new StringBuilder("{");
460- for(Map.Entry<Integer,Integer> dc : replicationFactors.entrySet()) {
453+ for (Map.Entry<Integer, Integer> dc : replicationFactors.entrySet()) {
461454 strategyOptionsBuilder.append("\"");
462455 strategyOptionsBuilder.append(datacenter(dc.getKey()));
463456 strategyOptionsBuilder.append("\":\"");
@@ -467,12 +460,12 @@
467460
468461 String strategyOptions = strategyOptionsBuilder.substring(0, strategyOptionsBuilder.length() - 1) + "}";
469462
470- Map<String,Object> ntsKeyspaceRow = ImmutableMap.<String,Object>builder()
471- .put("durable_writes", false)
472- .put("keyspace_name", name)
473- .put("strategy_class", "NetworkTopologyStrategy")
474- .put("strategy_options", strategyOptions)
475- .build();
463+ Map<String, Object> ntsKeyspaceRow = ImmutableMap.<String, Object>builder()
464+ .put("durable_writes", false)
465+ .put("keyspace_name", name)
466+ .put("strategy_class", "NetworkTopologyStrategy")
467+ .put("strategy_options", strategyOptions)
468+ .build();
476469
477470 keyspaceRows.add(ntsKeyspaceRow);
478471 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 +48 −48
@@ -15,24 +15,22 @@
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;
2219 import com.google.common.collect.Lists;
2320 import com.google.common.util.concurrent.Futures;
2421 import com.google.common.util.concurrent.ListenableFuture;
2522 import org.mockito.ArgumentCaptor;
2623 import org.testng.annotations.*;
2724
28-import static org.mockito.Matchers.any;
29-import static org.mockito.Mockito.*;
30-
31-import com.datastax.driver.core.utils.Bytes;
25+import java.util.Collection;
26+import java.util.Collections;
27+import java.util.List;
3228
3329 import static com.datastax.driver.core.Assertions.assertThat;
3430 import static com.datastax.driver.core.Metadata.handleId;
3531 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
32+import static org.mockito.Matchers.any;
33+import static org.mockito.Mockito.*;
3634
3735 public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster {
3836
@@ -44,7 +42,9 @@
4442 private static final String ALTER_TABLE = "ALTER TABLE %s.table1 ADD j int";
4543 private static final String DROP_TABLE = "DROP TABLE %s.table1";
4644
47- /** The maximum time that the test will wait to check that listeners have been notified */
45+ /**
46+ * The maximum time that the test will wait to check that listeners have been notified
47+ */
4848 private static final int NOTIF_TIMEOUT_MS = 5000;
4949
5050 Cluster cluster1;
@@ -74,16 +74,16 @@
7474 @BeforeClass(groups = "short")
7575 public void setup() throws InterruptedException {
7676 Cluster.Builder builder = configure(Cluster.builder())
77- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
78- .withQueryOptions(nonDebouncingQueryOptions());
77+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
78+ .withQueryOptions(nonDebouncingQueryOptions());
7979 cluster1 = builder.build();
8080 cluster2 = builder.build();
8181 schemaDisabledCluster = spy(configure(Cluster.builder())
82- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
83- .withClusterName("schema-disabled")
84- .withQueryOptions(nonDebouncingQueryOptions()
85- .setMetadataEnabled(false)
86- ).build());
82+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
83+ .withClusterName("schema-disabled")
84+ .withQueryOptions(nonDebouncingQueryOptions()
85+ .setMetadataEnabled(false)
86+ ).build());
8787
8888 schemaDisabledSession = schemaDisabledCluster.connect();
8989
@@ -117,12 +117,12 @@
117117
118118 @DataProvider(name = "existingKeyspaceName")
119119 public static Object[][] existingKeyspaceName() {
120- return new Object[][]{ { "lowercase" }, { "\"CaseSensitive\"" } };
120+ return new Object[][]{{"lowercase"}, {"\"CaseSensitive\""}};
121121 }
122122
123123 @DataProvider(name = "newKeyspaceName")
124124 public static Object[][] newKeyspaceName() {
125- return new Object[][]{ { "lowercase2" }, { "\"CaseSensitive2\"" } };
125+ return new Object[][]{{"lowercase2"}, {"\"CaseSensitive2\""}};
126126 }
127127
128128 @BeforeMethod(groups = "short")
@@ -152,8 +152,8 @@
152152 ArgumentCaptor<TableMetadata> added = ArgumentCaptor.forClass(TableMetadata.class);
153153 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
154154 assertThat(added.getValue())
155- .isInKeyspace(handleId(keyspace))
156- .hasName("table1");
155+ .isInKeyspace(handleId(keyspace))
156+ .hasName("table1");
157157 }
158158
159159 for (Metadata m : metadatas)
@@ -170,8 +170,8 @@
170170 added = ArgumentCaptor.forClass(TableMetadata.class);
171171 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
172172 assertThat(added.getValue())
173- .isInKeyspace(handleId(keyspace))
174- .hasName("table1");
173+ .isInKeyspace(handleId(keyspace))
174+ .hasName("table1");
175175 }
176176 execute(ALTER_TABLE, keyspace);
177177 for (SchemaChangeListener listener : listeners) {
@@ -179,12 +179,12 @@
179179 ArgumentCaptor<TableMetadata> previous = ArgumentCaptor.forClass(TableMetadata.class);
180180 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableChanged(current.capture(), previous.capture());
181181 assertThat(previous.getValue())
182- .isEqualTo(added.getValue())
183- .hasNoColumn("j");
182+ .isEqualTo(added.getValue())
183+ .hasNoColumn("j");
184184 assertThat(current.getValue())
185- .isInKeyspace(handleId(keyspace))
186- .hasName("table1")
187- .hasColumn("j");
185+ .isInKeyspace(handleId(keyspace))
186+ .hasName("table1")
187+ .hasColumn("j");
188188 }
189189 for (Metadata m : metadatas)
190190 assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j");
@@ -197,8 +197,8 @@
197197 ArgumentCaptor<TableMetadata> added = ArgumentCaptor.forClass(TableMetadata.class);
198198 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
199199 assertThat(added.getValue())
200- .hasName("table1")
201- .isInKeyspace(handleId(keyspace));
200+ .hasName("table1")
201+ .isInKeyspace(handleId(keyspace));
202202 }
203203 execute(DROP_TABLE, keyspace);
204204 for (Metadata m : metadatas)
@@ -239,11 +239,11 @@
239239 ArgumentCaptor<KeyspaceMetadata> previous = ArgumentCaptor.forClass(KeyspaceMetadata.class);
240240 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(current.capture(), previous.capture());
241241 assertThat(previous.getValue())
242- .isEqualTo(added.getValue())
243- .isDurableWrites();
242+ .isEqualTo(added.getValue())
243+ .isDurableWrites();
244244 assertThat(current.getValue())
245- .hasName(handleId(keyspace))
246- .isNotDurableWrites();
245+ .hasName(handleId(keyspace))
246+ .isNotDurableWrites();
247247 }
248248 for (Metadata m : metadatas)
249249 assertThat(m.getKeyspace(keyspace)).isNotDurableWrites();
@@ -260,13 +260,13 @@
260260 ArgumentCaptor<TableMetadata> table = ArgumentCaptor.forClass(TableMetadata.class);
261261 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(table.capture());
262262 assertThat(table.getValue())
263- .hasName("table1")
264- .isInKeyspace(handleId(keyspace));
263+ .hasName("table1")
264+ .isInKeyspace(handleId(keyspace));
265265
266266 ArgumentCaptor<KeyspaceMetadata> ks = ArgumentCaptor.forClass(KeyspaceMetadata.class);
267267 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(ks.capture());
268268 assertThat(ks.getValue())
269- .hasName(handleId(keyspace));
269+ .hasName(handleId(keyspace));
270270 }
271271 for (Metadata m : metadatas) {
272272 assertThat(m.getKeyspace(keyspace)).isNull();
@@ -285,10 +285,10 @@
285285 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
286286 public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() {
287287 Cluster cluster = configure(Cluster.builder())
288- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
289- .withQueryOptions(nonDebouncingQueryOptions()
290- .setMetadataEnabled(false)
291- ).build();
288+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
289+ .withQueryOptions(nonDebouncingQueryOptions()
290+ .setMetadataEnabled(false)
291+ ).build();
292292
293293 try {
294294 cluster.init();
@@ -309,10 +309,10 @@
309309 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
310310 public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() {
311311 Cluster cluster = configure(Cluster.builder())
312- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
313- .withQueryOptions(nonDebouncingQueryOptions()
314- .setMetadataEnabled(false)
315- ).build();
312+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
313+ .withQueryOptions(nonDebouncingQueryOptions()
314+ .setMetadataEnabled(false)
315+ ).build();
316316
317317 try {
318318 cluster.init();
@@ -383,10 +383,10 @@
383383 @AfterMethod(groups = "short")
384384 public void cleanup() throws InterruptedException {
385385 ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList(
386- session1.executeAsync("DROP TABLE lowercase.table1"),
387- session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
388- session1.executeAsync("DROP KEYSPACE lowercase2"),
389- session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
386+ session1.executeAsync("DROP TABLE lowercase.table1"),
387+ session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
388+ session1.executeAsync("DROP KEYSPACE lowercase2"),
389+ session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
390390 ));
391391 Futures.getUnchecked(f);
392392 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +26 −27
@@ -15,21 +15,20 @@
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.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
3228 import static com.datastax.driver.core.TestUtils.CREATE_TABLE_SIMPLE_FORMAT;
29+import static com.google.common.collect.Lists.newArrayList;
30+import static org.mockito.ArgumentCaptor.forClass;
31+import static org.mockito.Mockito.*;
3332
3433 public class SchemaRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
3534
@@ -61,9 +60,9 @@
6160 queryOptions.setMaxPendingRefreshSchemaRequests(5);
6261 // Create a separate cluster that will receive the schema events on its control connection.
6362 cluster2 = this.configure(Cluster.builder())
64- .addContactPointsWithPorts(newArrayList(hostAddress))
65- .withQueryOptions(queryOptions)
66- .build();
63+ .addContactPointsWithPorts(newArrayList(hostAddress))
64+ .withQueryOptions(queryOptions)
65+ .build();
6766 session2 = cluster2.connect();
6867
6968 // Create a spy of the Cluster's control connection and replace it with the spy.
@@ -88,7 +87,7 @@
8887 public void teardown() {
8988 cluster2.close();
9089 // drop all keyspaces
91- for(String keyspace : keyspaces) {
90+ for (String keyspace : keyspaces) {
9291 session.execute("DROP KEYSPACE " + keyspace);
9392 }
9493 }
@@ -180,7 +179,7 @@
180179 reset(listener);
181180
182181 int tableCount = 3;
183- for(int i =0 ; i < tableCount; i++) {
182+ for (int i = 0; i < tableCount; i++) {
184183 session.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + "tbl" + i));
185184 }
186185
@@ -193,7 +192,7 @@
193192 KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
194193 assertThat(ksm).isNotNull();
195194 // metadata is present for each table.
196- for(int i = 0; i < tableCount; i++) {
195+ for (int i = 0; i < tableCount; i++) {
197196 String table = "tbl" + i;
198197 // Should have never been a refreshSchema on the table.
199198 verify(controlConnection, never()).refreshSchema(keyspace, table);
@@ -231,16 +230,16 @@
231230 ArgumentCaptor<TableMetadata> captor = forClass(TableMetadata.class);
232231 verify(listener, timeout(DEBOUNCE_TIME * 2).only()).onTableChanged(captor.capture(), original.capture());
233232 assertThat(captor.getValue())
234- .hasName(table)
235- .isInKeyspace(keyspace)
236- .hasColumn(columnName)
237- .hasComment(comment);
233+ .hasName(table)
234+ .isInKeyspace(keyspace)
235+ .hasColumn(columnName)
236+ .hasComment(comment);
238237
239238 assertThat(original.getValue())
240- .hasName(table)
241- .isInKeyspace(keyspace)
242- .hasNoColumn(columnName)
243- .doesNotHaveComment(comment);
239+ .hasName(table)
240+ .isInKeyspace(keyspace)
241+ .hasNoColumn(columnName)
242+ .doesNotHaveComment(comment);
244243
245244 // Verify a refresh of the table was executed, but only once.
246245 verify(controlConnection, times(1)).refreshSchema(keyspace, table);
@@ -249,10 +248,10 @@
249248 assertThat(ksm).isNotNull();
250249 TableMetadata tm = ksm.getTable(table);
251250 assertThat(tm)
252- .hasName(table)
253- .isInKeyspace(keyspace)
254- .hasColumn(columnName)
255- .hasComment(comment);
251+ .hasName(table)
252+ .isInKeyspace(keyspace)
253+ .hasColumn(columnName)
254+ .hasComment(comment);
256255 }
257256
258257 /**
@@ -268,7 +267,7 @@
268267 @Test(groups = "short")
269268 public void should_debounce_and_coalesce_multiple_keyspace_creates_into_refresh_entire_schema() throws Exception {
270269 String prefix = "sdacmkc";
271- for(int i = 0; i < 3; i++) {
270+ for (int i = 0; i < 3; i++) {
272271 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
273272 keyspaces.add(prefix + i);
274273 }
@@ -277,7 +276,7 @@
277276 // Verify a complete schema refresh was executed, but only once.
278277 verify(controlConnection, times(1)).refreshSchema(null, null);
279278
280- for(int i = 0; i < 3; i++) {
279+ for (int i = 0; i < 3; i++) {
281280 KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i);
282281 assertThat(ksm).isNotNull().hasName(prefix + i);
283282 }
@@ -295,7 +294,7 @@
295294 @Test(groups = "short")
296295 public void should_refresh_when_max_pending_requests_reached() throws Exception {
297296 String prefix = "srwmprr";
298- for(int i = 0; i < 5; i++) {
297+ for (int i = 0; i < 5; i++) {
299298 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
300299 keyspaces.add(prefix + i);
301300 }
@@ -305,7 +304,7 @@
305304 // Verify a complete schema refresh was executed, but only once.
306305 verify(controlConnection, times(1)).refreshSchema(null, null);
307306
308- for(int i = 0; i < 5; i++) {
307+ for (int i = 0; i < 5; i++) {
309308 KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i);
310309 assertThat(ksm).isNotNull().hasName(prefix + i);
311310 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +60 −59
@@ -15,11 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
2018 import org.slf4j.Logger;
2119 import org.slf4j.LoggerFactory;
2220 import org.testng.annotations.Test;
21+
22+import java.util.*;
23+
2324 import static org.testng.Assert.assertEquals;
2425
2526 /**
@@ -36,9 +37,9 @@
3637 @Override
3738 protected Cluster.Builder configure(Cluster.Builder builder) {
3839 return builder.withQueryOptions(new QueryOptions()
39- .setRefreshNodeIntervalMillis(0)
40- .setRefreshNodeListIntervalMillis(0)
41- .setRefreshSchemaIntervalMillis(0)
40+ .setRefreshNodeIntervalMillis(0)
41+ .setRefreshNodeListIntervalMillis(0)
42+ .setRefreshSchemaIntervalMillis(0)
4243 );
4344 }
4445
@@ -46,51 +47,51 @@
4647 protected Collection<String> getTableDefinitions() {
4748
4849 String sparse = String.format("CREATE TABLE %s.sparse (\n"
49- + " k text,\n"
50- + " c1 int,\n"
51- + " c2 float,\n"
52- + " l list<text>,\n"
53- + " v int,\n"
54- + " PRIMARY KEY (k, c1, c2)\n"
55- + ");", 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);
5657
5758 String st = String.format("CREATE TABLE %s.static (\n"
58- + " k text,\n"
59- + " i int,\n"
60- + " m map<text, timeuuid>,\n"
61- + " v int,\n"
62- + " PRIMARY KEY (k)\n"
63- + ");", 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);
6465
6566 String counters = String.format("CREATE TABLE %s.counters (\n"
66- + " k text,\n"
67- + " c counter,\n"
68- + " PRIMARY KEY (k)\n"
69- + ");", keyspace);
67+ + " k text,\n"
68+ + " c counter,\n"
69+ + " PRIMARY KEY (k)\n"
70+ + ");", keyspace);
7071
7172 String compactStatic = String.format("CREATE TABLE %s.compact_static (\n"
72- + " k text,\n"
73- + " i int,\n"
74- + " t timeuuid,\n"
75- + " v int,\n"
76- + " PRIMARY KEY (k)\n"
77- + ") 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);
7879
7980 String compactDynamic = String.format("CREATE TABLE %s.compact_dynamic (\n"
80- + " k text,\n"
81- + " c int,\n"
82- + " v timeuuid,\n"
83- + " PRIMARY KEY (k, c)\n"
84- + ") 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);
8586
8687 String compactComposite = String.format("CREATE TABLE %s.compact_composite (\n"
87- + " k text,\n"
88- + " c1 int,\n"
89- + " c2 float,\n"
90- + " c3 double,\n"
91- + " v timeuuid,\n"
92- + " PRIMARY KEY (k, c1, c2, c3)\n"
93- + ") 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);
9495
9596 cql3.put("sparse", sparse);
9697 cql3.put("static", st);
@@ -102,7 +103,7 @@
102103 Properties properties = System.getProperties();
103104 String vmVersion = properties.getProperty("java.vm.specification.version");
104105 double javaVersion = 1.6;
105- if(vmVersion != null) {
106+ if (vmVersion != null) {
106107 try {
107108 javaVersion = Double.parseDouble(vmVersion);
108109 } catch (NumberFormatException e) {
@@ -112,27 +113,27 @@
112113
113114 // Ordering of compaction options will be dependent on JDK. See schemaOptionsTest comments for explanation of why this is needed.
114115 String compactionOptions;
115- if(javaVersion >= 1.8)
116+ if (javaVersion >= 1.8)
116117 compactionOptions = " AND compaction = { 'sstable_size_in_mb' : 15, 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy' }\n";
117118 else
118119 compactionOptions = " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n";
119120
120121 withOptions = String.format("CREATE TABLE %s.with_options (\n"
121- + " k text,\n"
122- + " v1 int,\n"
123- + " v2 int,\n"
124- + " i int,\n"
125- + " PRIMARY KEY (k, v1, v2)\n"
126- + ") WITH CLUSTERING ORDER BY (v1 DESC, v2 ASC)\n"
127- + " AND read_repair_chance = 0.5\n"
128- + " AND dclocal_read_repair_chance = 0.6\n"
129- + " AND replicate_on_write = true\n"
130- + " AND gc_grace_seconds = 42\n"
131- + " AND bloom_filter_fp_chance = 0.01\n"
132- + " AND caching = 'ALL'\n"
133- + " AND comment = 'My awesome table'\n"
134- + compactionOptions
135- + " 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);
136137
137138 List<String> allDefs = new ArrayList<String>();
138139 allDefs.addAll(cql3.values());
@@ -182,8 +183,8 @@
182183 // Strip the last ';'
183184 withOpts = withOpts.substring(0, withOpts.length() - 1) + '\n';
184185 withOpts += " AND default_time_to_live = 0\n"
185- + " AND speculative_retry = '99.0PERCENTILE'\n"
186- + " AND index_interval = 128;";
186+ + " AND speculative_retry = '99.0PERCENTILE'\n"
187+ + " AND index_interval = 128;";
187188 }
188189 assertEquals(metadata.exportAsString(), withOpts);
189190 }
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 +9 −13
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidQueryException;
1819 import com.datastax.driver.core.utils.SocketChannelMonitor;
1920 import com.google.common.collect.Lists;
2021 import org.testng.annotations.Test;
@@ -24,15 +25,10 @@
2425 import java.util.List;
2526 import java.util.concurrent.TimeUnit;
2627
27-import static org.testng.Assert.assertEquals;
28-import static java.util.concurrent.TimeUnit.MINUTES;
29-
30-import static org.assertj.core.api.Assertions.fail;
31-
32-import com.datastax.driver.core.exceptions.InvalidQueryException;
33-
3428 import static com.datastax.driver.core.Assertions.assertThat;
3529 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;
3632
3733 public class SessionLeakTest {
3834
@@ -94,7 +90,7 @@
9490 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
9591 assertOpenConnections(1);
9692 } finally {
97- if(cluster != null){
93+ if (cluster != null) {
9894 cluster.close();
9995 }
10096 if (ccmBridge != null) {
@@ -116,9 +112,9 @@
116112 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
117113 try {
118114 cluster = Cluster.builder()
119- .addContactPointsWithPorts(Collections.singletonList(
120- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
121- .withNettyOptions(channelMonitor.nettyOptions()).build();
115+ .addContactPointsWithPorts(Collections.singletonList(
116+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
117+ .withNettyOptions(channelMonitor.nettyOptions()).build();
122118
123119 cluster.init();
124120
@@ -132,7 +128,7 @@
132128
133129 fail("Should not have connected to a wrong keyspace");
134130
135- } catch(InvalidQueryException e) {
131+ } catch (InvalidQueryException e) {
136132
137133 // ok
138134
@@ -140,7 +136,7 @@
140136
141137 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
142138
143- if(cluster != null){
139+ if (cluster != null) {
144140 cluster.close();
145141 }
146142 if (ccmBridge != null) {
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 +15 −19
@@ -15,25 +15,21 @@
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;
2619 import com.datastax.driver.core.utils.SocketChannelMonitor;
27-import io.netty.channel.socket.SocketChannel;
2820 import org.slf4j.Logger;
2921 import org.slf4j.LoggerFactory;
3022 import org.testng.annotations.Test;
3123
32-import static org.testng.Assert.assertEquals;
33-import static org.testng.Assert.assertTrue;
34-import static org.testng.Assert.fail;
24+import java.net.InetSocketAddress;
25+import java.util.*;
26+import java.util.concurrent.CountDownLatch;
27+import java.util.concurrent.ExecutorService;
28+import java.util.concurrent.Executors;
29+import java.util.concurrent.TimeUnit;
3530
3631 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
32+import static org.testng.Assert.*;
3733
3834 /**
3935 * Simple test of the Sessions methods against a one node cluster.
@@ -50,9 +46,9 @@
5046 @Override
5147 protected Collection<String> getTableDefinitions() {
5248 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));
49+ String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE2),
50+ String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE3),
51+ String.format("CREATE TABLE %s (k text PRIMARY KEY, c counter)", COUNTER_TABLE));
5652 }
5753
5854 @Test(groups = "short")
@@ -134,7 +130,7 @@
134130 * @expected_result session established and queries made successfully using it.
135131 */
136132 @Test(groups = "short")
137- @CassandraVersion(major=2.0)
133+ @CassandraVersion(major = 2.0)
138134 public void session_should_function_with_lz4_compression() throws Exception {
139135 compressionTest(ProtocolOptions.Compression.LZ4);
140136 }
@@ -206,7 +202,7 @@
206202 // ensure sessions.size() returns to 0 with only 1 active connection
207203 session.close();
208204 assertEquals(cluster.manager.sessions.size(), 0);
209- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
205+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
210206 assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
211207
212208 // give the driver time to close sessions
@@ -252,9 +248,9 @@
252248 // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster
253249 // (note the use of newSession below)
254250 final Cluster cluster = Cluster.builder()
255- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
256- .withNettyOptions(nonQuietClusterCloseOptions)
257- .build();
251+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
252+ .withNettyOptions(nonQuietClusterCloseOptions)
253+ .build();
258254 final Session session = cluster.newSession();
259255
260256 // 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 /*
118118 * --------------
@@ -123,18 +123,18 @@
123123 @Test(groups = "unit")
124124 public void simpleStrategySimpleTopologyTest() {
125125 List<Token> ring = ImmutableList.<Token>builder()
126- .add(TOKEN01)
127- .add(TOKEN06)
128- .add(TOKEN14)
129- .add(TOKEN19)
130- .build();
126+ .add(TOKEN01)
127+ .add(TOKEN06)
128+ .add(TOKEN14)
129+ .add(TOKEN19)
130+ .build();
131131
132132 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
133- .put(TOKEN01, host(IP1))
134- .put(TOKEN06, host(IP2))
135- .put(TOKEN14, host(IP1))
136- .put(TOKEN19, host(IP2))
137- .build();
133+ .put(TOKEN01, host(IP1))
134+ .put(TOKEN06, host(IP2))
135+ .put(TOKEN14, host(IP1))
136+ .put(TOKEN19, host(IP2))
137+ .build();
138138
139139 ReplicationStrategy strategy = simpleStrategy(2);
140140
@@ -149,18 +149,18 @@
149149 @Test(groups = "unit")
150150 public void simpleStrategyConsecutiveRingSectionsTest() {
151151 List<Token> ring = ImmutableList.<Token>builder()
152- .add(TOKEN01)
153- .add(TOKEN06)
154- .add(TOKEN14)
155- .add(TOKEN19)
156- .build();
152+ .add(TOKEN01)
153+ .add(TOKEN06)
154+ .add(TOKEN14)
155+ .add(TOKEN19)
156+ .build();
157157
158158 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
159- .put(TOKEN01, host(IP1))
160- .put(TOKEN06, host(IP1))
161- .put(TOKEN14, host(IP2))
162- .put(TOKEN19, host(IP2))
163- .build();
159+ .put(TOKEN01, host(IP1))
160+ .put(TOKEN06, host(IP1))
161+ .put(TOKEN14, host(IP2))
162+ .put(TOKEN19, host(IP2))
163+ .build();
164164
165165 ReplicationStrategy strategy = simpleStrategy(2);
166166
@@ -175,18 +175,18 @@
175175 @Test(groups = "unit")
176176 public void simpleStrategyUnbalancedRingTest() {
177177 List<Token> ring = ImmutableList.<Token>builder()
178- .add(TOKEN01)
179- .add(TOKEN06)
180- .add(TOKEN14)
181- .add(TOKEN19)
182- .build();
178+ .add(TOKEN01)
179+ .add(TOKEN06)
180+ .add(TOKEN14)
181+ .add(TOKEN19)
182+ .build();
183183
184184 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
185- .put(TOKEN01, host(IP1))
186- .put(TOKEN06, host(IP1))
187- .put(TOKEN14, host(IP2))
188- .put(TOKEN19, host(IP1))
189- .build();
185+ .put(TOKEN01, host(IP1))
186+ .put(TOKEN06, host(IP1))
187+ .put(TOKEN14, host(IP2))
188+ .put(TOKEN19, host(IP1))
189+ .build();
190190
191191 ReplicationStrategy strategy = simpleStrategy(2);
192192
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/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 +74 −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
@@ -455,6 +472,7 @@
455472 Configuration configuration = cluster.getConfiguration();
456473 return configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL);
457474 }
475+
458476 /**
459477 * @return A Scassandra instance with an arbitrarily chosen binary port from 8042-8142 and admin port from
460478 * 8052-8152.
@@ -492,7 +510,7 @@
492510 String version = System.getProperty("cassandra.version");
493511 String[] versionArray = version.split("\\.|-");
494512 double major = Double.parseDouble(versionArray[0] + "." + versionArray[1]);
495- if(major < 2.0) {
513+ if (major < 2.0) {
496514 return 1;
497515 } else {
498516 return 2;
@@ -506,9 +524,9 @@
506524 Host controlHost = cluster.manager.controlConnection.connectedHost();
507525 List<InetSocketAddress> singleAddress = Collections.singletonList(controlHost.getSocketAddress());
508526 return Cluster.builder()
509- .addContactPointsWithPorts(singleAddress)
510- .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
511- .build();
527+ .addContactPointsWithPorts(singleAddress)
528+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
529+ .build();
512530 }
513531
514532 /**
@@ -516,8 +534,8 @@
516534 */
517535 public static QueryOptions nonDebouncingQueryOptions() {
518536 return new QueryOptions().setRefreshNodeIntervalMillis(0)
519- .setRefreshNodeListIntervalMillis(0)
520- .setRefreshSchemaIntervalMillis(0);
537+ .setRefreshNodeListIntervalMillis(0)
538+ .setRefreshSchemaIntervalMillis(0);
521539 }
522540
523541 /**
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().setCoreConnectionsPerHost(HostDistance.LOCAL, 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
@@ -164,7 +164,7 @@
164164
165165 // Ensure that we don't exceed maximum connections. Log as warning as there will be a bit of a timing
166166 // factor between retrieving open connections and checking the reaper.
167- if(openChannels.size() > maxConnections) {
167+ if (openChannels.size() > maxConnections) {
168168 logger.warn("{} of open channels: {} exceeds maximum expected: {}. " +
169169 "This could be because there are connections to be cleaned up in the reaper.",
170170 openChannels.size(), maxConnections, openChannels);
@@ -180,7 +180,7 @@
180180 .setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
181181
182182 logger.debug("Sleeping 20 seconds to allow connection reaper to clean up connections " +
183- "and for the pools to recover.");
183+ "and for the pools to recover.");
184184 Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
185185
186186 Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
@@ -250,7 +250,7 @@
250250 @Override
251251 public void run() {
252252
253- while(!stopped.get()) {
253+ while (!stopped.get()) {
254254 try {
255255 concurrentQueries.acquire();
256256 ResultSetFuture future = session.executeAsync(statement.bind("0"));
@@ -259,21 +259,21 @@
259259 @Override
260260 public void onSuccess(ResultSet result) {
261261 concurrentQueries.release();
262- if(executedQueries.incrementAndGet() % 1000 == 0)
262+ if (executedQueries.incrementAndGet() % 1000 == 0)
263263 logger.debug("Successfully executed {}. rows: {}", executedQueries.get(), result.getAvailableWithoutFetching());
264264 }
265265
266266 @Override
267267 public void onFailure(Throwable t) {
268268 concurrentQueries.release();
269- if(t instanceof NoHostAvailableException) {
269+ if (t instanceof NoHostAvailableException) {
270270 //logger.error("NHAE: {}", t.getMessage());
271271 } else {
272272 //logger.error("Exception", t);
273273 }
274274 }
275275 });
276- } catch(Exception e) {
276+ } catch (Exception e) {
277277 logger.error("Failure while submitting query.", e);
278278 }
279279 }
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/TypeCodecTest.java +6 −7
@@ -15,14 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collections;
19-import java.util.List;
20-
21-import org.testng.collections.Lists;
22-
2318 import com.google.common.base.Strings;
2419 import org.testng.Assert;
2520 import org.testng.annotations.Test;
21+import org.testng.collections.Lists;
22+
23+import java.util.Collections;
24+import java.util.List;
2625
2726 import static com.datastax.driver.core.DataType.text;
2827
@@ -54,7 +53,7 @@
5453 Assert.assertNotNull(mapType);
5554 }
5655
57- @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
56+ @Test(groups = "unit", expectedExceptions = {IllegalArgumentException.class})
5857 public void collectionTooLargeTest() throws Exception {
5958 TypeCodec<List<Integer>> listType = TypeCodec.listOf(DataType.cint());
6059 List<Integer> list = Collections.nCopies(65536, 1);
@@ -62,7 +61,7 @@
6261 listType.serialize(list);
6362 }
6463
65- @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
64+ @Test(groups = "unit", expectedExceptions = {IllegalArgumentException.class})
6665 public void collectionElementTooLargeTest() throws Exception {
6766 TypeCodec<List<String>> listType = TypeCodec.listOf(DataType.text());
6867 List<String> list = Lists.newArrayList(Strings.repeat("a", 65536));
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 +61 −76
@@ -15,33 +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.nonQuietClusterCloseOptions;
29+import static com.datastax.driver.core.TestUtils.*;
4530
4631 public class TokenAwarePolicyTest {
4732
@@ -52,12 +37,12 @@
5237 queryTracker = new QueryTracker();
5338 }
5439
55- @DataProvider(name="shuffleProvider")
56- public Object[][] shuffleProvider () {
57- return new Object[][] {
58- { true },
59- { false },
60- { null }
40+ @DataProvider(name = "shuffleProvider")
41+ public Object[][] shuffleProvider() {
42+ return new Object[][]{
43+ {true},
44+ {false},
45+ {null}
6146 };
6247 }
6348
@@ -68,16 +53,16 @@
6853 *
6954 * @test_category load_balancing:token_aware
7055 */
71- @Test(groups="short", dataProvider="shuffleProvider")
56+ @Test(groups = "short", dataProvider = "shuffleProvider")
7257 public void should_shuffle_replicas_based_on_configuration(Boolean shuffleReplicas) {
7358 // given: an 8 node cluster using TokenAwarePolicy and some shuffle replica configuration with a keyspace with replication factor of 3.
7459 ScassandraCluster sCluster = ScassandraCluster.builder()
75- .withNodes(8)
76- .withSimpleKeyspace("keyspace", 3)
77- .build();
60+ .withNodes(8)
61+ .withSimpleKeyspace("keyspace", 3)
62+ .build();
7863
7964 LoadBalancingPolicy loadBalancingPolicy;
80- if(shuffleReplicas == null) {
65+ if (shuffleReplicas == null) {
8166 loadBalancingPolicy = new TokenAwarePolicy(new RoundRobinPolicy());
8267 shuffleReplicas = true;
8368 } else {
@@ -85,9 +70,9 @@
8570 }
8671
8772 Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
88- .withNettyOptions(nonQuietClusterCloseOptions)
89- .withLoadBalancingPolicy(loadBalancingPolicy)
90- .build();
73+ .withNettyOptions(nonQuietClusterCloseOptions)
74+ .withLoadBalancingPolicy(loadBalancingPolicy)
75+ .build();
9176
9277 try {
9378 sCluster.init();
@@ -100,9 +85,9 @@
10085 // then: The replicas resolved from the cluster metadata must match node 6 and its replicas.
10186 List<Host> replicas = Lists.newArrayList(cluster.getMetadata().getReplicas("keyspace", routingKey));
10287 assertThat(replicas).containsExactly(
103- sCluster.host(cluster, 1, 6),
104- sCluster.host(cluster, 1, 7),
105- sCluster.host(cluster, 1, 8));
88+ sCluster.host(cluster, 1, 6),
89+ sCluster.host(cluster, 1, 7),
90+ sCluster.host(cluster, 1, 8));
10691
10792 // then: generating a query plan on a statement using that routing key should properly prioritize node 6 and its replicas.
10893 SimpleStatement statement = new SimpleStatement("select * from table where k=5");
@@ -110,16 +95,16 @@
11095 statement.setKeyspace("keyspace");
11196
11297 boolean shuffledAtLeastOnce = false;
113- for(int i = 0; i < 1024; i++) {
98+ for (int i = 0; i < 1024; i++) {
11499 List<Host> queryPlan = Lists.newArrayList(loadBalancingPolicy.newQueryPlan(null, statement));
115100 assertThat(queryPlan).containsOnlyElementsOf(cluster.getMetadata().getAllHosts());
116101
117102 List<Host> firstThree = queryPlan.subList(0, 3);
118103 // then: if shuffle replicas was used or using default, the first three hosts returned should be 6,7,8 in any order.
119104 // if shuffle replicas was not used, the first three hosts returned should be 6,7,8 in that order.
120- if(shuffleReplicas) {
105+ if (shuffleReplicas) {
121106 assertThat(firstThree).containsOnlyElementsOf(replicas);
122- if(!firstThree.equals(replicas)) {
107+ if (!firstThree.equals(replicas)) {
123108 shuffledAtLeastOnce = true;
124109 }
125110 } else {
@@ -142,17 +127,17 @@
142127 *
143128 * @test_category load_balancing:token_aware
144129 */
145- @Test(groups="short")
130+ @Test(groups = "short")
146131 public void should_choose_proper_host_based_on_routing_key() {
147132 // given: A 3 node cluster using TokenAwarePolicy with a replication factor of 1.
148133 ScassandraCluster sCluster = ScassandraCluster.builder()
149- .withNodes(3)
150- .withSimpleKeyspace("keyspace", 1)
151- .build();
134+ .withNodes(3)
135+ .withSimpleKeyspace("keyspace", 1)
136+ .build();
152137 Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
153- .withNettyOptions(nonQuietClusterCloseOptions)
154- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
155- .build();
138+ .withNettyOptions(nonQuietClusterCloseOptions)
139+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
140+ .build();
156141
157142 // when: A query is made with a routing key
158143 try {
@@ -163,8 +148,8 @@
163148 // Encodes into murmur hash '4557949199137838892' which should belong be owned by node 3.
164149 ByteBuffer routingKey = DataType.text().serialize("should_choose_proper_host_based_on_routing_key");
165150 SimpleStatement statement = new SimpleStatement("select * from table where k=5")
166- .setRoutingKey(routingKey)
167- .setKeyspace("keyspace");
151+ .setRoutingKey(routingKey)
152+ .setKeyspace("keyspace");
168153
169154 queryTracker.query(session, 10, statement);
170155
@@ -185,20 +170,20 @@
185170 *
186171 * @test_category load_balancing:token_aware
187172 */
188- @Test(groups="short")
173+ @Test(groups = "short")
189174 public void should_choose_host_in_local_dc_when_using_network_topology_strategy_and_dc_aware() {
190175 // given: A 6 node, 2 DC cluster with RF 1:1, using TokenAwarePolicy wrapping DCAwareRoundRobinPolicy with remote hosts.
191176 ScassandraCluster sCluster = ScassandraCluster.builder()
192- .withNodes(3, 3)
193- .withNetworkTopologyKeyspace("keyspace", ImmutableMap.of(1, 1, 2, 1))
194- .build();
195- Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2,1))
196- .withNettyOptions(nonQuietClusterCloseOptions)
197- .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder()
198- .withLocalDc(ScassandraCluster.datacenter(2))
199- .withUsedHostsPerRemoteDc(3)
200- .build()))
201- .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();
202187
203188 // when: A query is made with a routing key
204189 try {
@@ -209,8 +194,8 @@
209194 // Encodes into murmur hash '-8124212968526248339' which should belong to 1:1 in DC1 and 2:1 in DC2.
210195 ByteBuffer routingKey = DataType.text().serialize("should_choose_host_in_local_dc_when_using_network_topology_strategy_and_dc_aware");
211196 SimpleStatement statement = new SimpleStatement("select * from table where k=5")
212- .setRoutingKey(routingKey)
213- .setKeyspace("keyspace");
197+ .setRoutingKey(routingKey)
198+ .setKeyspace("keyspace");
214199
215200 queryTracker.query(session, 10, statement);
216201
@@ -230,18 +215,18 @@
230215 *
231216 * @test_category load_balancing:token_aware
232217 */
233- @Test(groups="short")
218+ @Test(groups = "short")
234219 public void should_use_other_nodes_when_replicas_having_token_are_down() {
235220 // given: A 4 node cluster using TokenAwarePolicy with a replication factor of 2.
236221 ScassandraCluster sCluster = ScassandraCluster.builder()
237- .withNodes(4)
238- .withSimpleKeyspace("keyspace", 2)
239- .build();
222+ .withNodes(4)
223+ .withSimpleKeyspace("keyspace", 2)
224+ .build();
240225 Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2))
241- .withNettyOptions(nonQuietClusterCloseOptions)
242- // Don't shuffle replicas just to keep test deterministic.
243- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
244- .build();
226+ .withNettyOptions(nonQuietClusterCloseOptions)
227+ // Don't shuffle replicas just to keep test deterministic.
228+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
229+ .build();
245230
246231 try {
247232 sCluster.init();
@@ -252,8 +237,8 @@
252237 // Encodes into murmur hash '6444339665561646341' which should belong to node 4.
253238 ByteBuffer routingKey = DataType.text().serialize("should_use_other_nodes_when_replicas_having_token_are_down");
254239 SimpleStatement statement = new SimpleStatement("select * from table where k=5")
255- .setRoutingKey(routingKey)
256- .setKeyspace("keyspace");
240+ .setRoutingKey(routingKey)
241+ .setKeyspace("keyspace");
257242
258243 queryTracker.query(session, 10, statement);
259244
@@ -326,9 +311,9 @@
326311 CCMBridge ccm = CCMBridge.builder("TokenAwarePolicyTest").withNodes(3).notStarted().build();
327312
328313 Cluster cluster = Cluster.builder()
329- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
330- .addContactPoint(CCMBridge.ipOfNode(1))
331- .build();
314+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
315+ .addContactPoint(CCMBridge.ipOfNode(1))
316+ .build();
332317
333318 try {
334319 ccm.start();
@@ -344,11 +329,11 @@
344329 BoundStatement insertBs = insertPs.bind(1, 2, 3);
345330
346331 PreparedStatement selectPs = session.prepare("SELECT * FROM " + table + " WHERE k1=? and k2=?");
347- BoundStatement selectBs = selectPs.bind(1,2);
332+ BoundStatement selectBs = selectPs.bind(1, 2);
348333
349334 // when: executing a prepared statement with a composite partition key.
350335 // then: should query the correct node (1) in for both insert and select queries.
351- for(int i = 0; i < 10; i++) {
336+ for (int i = 0; i < 10; i++) {
352337 ResultSet rs = session.execute(insertBs);
353338 assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
354339
modified driver-core/src/test/java/com/datastax/driver/core/policies/WhiteListPolicyTest.java +20 −25
@@ -15,20 +15,15 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.net.InetAddress;
19-import java.net.InetSocketAddress;
20-import java.util.List;
21-
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.NoHostAvailableException;
2220 import com.google.common.collect.Lists;
2321 import org.testng.annotations.BeforeMethod;
2422 import org.testng.annotations.Test;
2523
26-import com.datastax.driver.core.Cluster;
27-import com.datastax.driver.core.ConsistencyLevel;
28-import com.datastax.driver.core.QueryTracker;
29-import com.datastax.driver.core.ScassandraCluster;
30-import com.datastax.driver.core.Session;
31-import com.datastax.driver.core.exceptions.NoHostAvailableException;
24+import java.net.InetAddress;
25+import java.net.InetSocketAddress;
26+import java.util.List;
3227
3328 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
3429
@@ -46,25 +41,25 @@
4641 * <p/>
4742 * Ensures that:
4843 * <ol>
49- * <li>Only addresses provided in the whitelist are every used for querying.</li>
50- * <li>If no nodes present in the whitelist are available, queries fail with a {@link NoHostAvailableException}</li>
44+ * <li>Only addresses provided in the whitelist are every used for querying.</li>
45+ * <li>If no nodes present in the whitelist are available, queries fail with a {@link NoHostAvailableException}</li>
5146 * </ol>
5247 *
5348 * @test_category load_balancing:white_list
5449 */
55- @Test(groups="short")
50+ @Test(groups = "short")
5651 public void should_only_query_hosts_in_white_list() throws Exception {
5752 // given: a 5 node cluster with a WhiteListPolicy targeting nodes 3 and 5.
5853 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build();
5954 List<InetSocketAddress> whiteList = Lists.newArrayList(
60- new InetSocketAddress(InetAddress.getByName(sCluster.address(3)), 9042),
61- new InetSocketAddress(InetAddress.getByName(sCluster.address(5)), 9042));
55+ new InetSocketAddress(InetAddress.getByName(sCluster.address(3)), 9042),
56+ new InetSocketAddress(InetAddress.getByName(sCluster.address(5)), 9042));
6257
6358 Cluster cluster = Cluster.builder()
64- .addContactPoint(sCluster.address(5))
65- .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
66- .withNettyOptions(nonQuietClusterCloseOptions)
67- .build();
59+ .addContactPoint(sCluster.address(5))
60+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
61+ .withNettyOptions(nonQuietClusterCloseOptions)
62+ .build();
6863
6964 try {
7065 sCluster.init();
@@ -106,7 +101,7 @@
106101 *
107102 * @test_category load_balancing:white_list
108103 */
109- @Test(groups="short", expectedExceptions = {IllegalArgumentException.class})
104+ @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
110105 public void should_require_contact_point_in_white_list() throws Exception {
111106 // given: a 5 node cluster with a WhiteListPolicy targeting node2.
112107 ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build();
@@ -114,12 +109,12 @@
114109 // when: using a Cluster instance with none of the contact points in the declared
115110 // WhiteListPolicy.
116111 List<InetSocketAddress> whiteList = Lists.newArrayList(
117- new InetSocketAddress(InetAddress.getByName(sCluster.address(2)), 9042));
112+ new InetSocketAddress(InetAddress.getByName(sCluster.address(2)), 9042));
118113 Cluster cluster = Cluster.builder()
119- .addContactPoint(sCluster.address(3))
120- .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
121- .withNettyOptions(nonQuietClusterCloseOptions)
122- .build();
114+ .addContactPoint(sCluster.address(3))
115+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
116+ .withNettyOptions(nonQuietClusterCloseOptions)
117+ .build();
123118
124119 try {
125120 sCluster.init();
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +8 −12
@@ -15,19 +15,15 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.*;
2019 import org.testng.annotations.Test;
2120
22-import static org.assertj.core.api.Assertions.assertThat;
23-import static org.assertj.core.data.MapEntry.entry;
24-import static org.testng.Assert.assertEquals;
25-import static org.testng.Assert.assertFalse;
26-import static org.testng.Assert.assertTrue;
27-
28-import com.datastax.driver.core.*;
21+import java.util.*;
2922
3023 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
24+import static org.assertj.core.api.Assertions.assertThat;
25+import static org.assertj.core.data.MapEntry.entry;
26+import static org.testng.Assert.*;
3127
3228 public class QueryBuilderExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
3329
@@ -36,9 +32,9 @@
3632 @Override
3733 protected Collection<String> getTableDefinitions() {
3834 return Arrays.asList(
39- String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1),
40- "CREATE TABLE dateTest (t timestamp PRIMARY KEY)",
41- "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)");
35+ String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1),
36+ "CREATE TABLE dateTest (t timestamp PRIMARY KEY)",
37+ "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)");
4238 }
4339
4440 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +19 −17
@@ -15,19 +15,17 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.Arrays;
19-import java.util.Collection;
20-import java.util.TreeSet;
21-
22-import org.testng.annotations.Test;
23-
24-import static org.testng.Assert.*;
25-
2618 import com.datastax.driver.core.*;
2719 import com.datastax.driver.core.exceptions.SyntaxError;
2820 import com.datastax.driver.core.utils.CassandraVersion;
21+import org.testng.annotations.Test;
22+
23+import java.util.Arrays;
24+import java.util.Collection;
25+import java.util.TreeSet;
2926
3027 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
28+import static org.testng.Assert.*;
3129
3230 public class QueryBuilderITest extends CCMBridge.PerClassSingleNodeCluster {
3331
@@ -37,15 +35,15 @@
3735 @Override
3836 protected Collection<String> getTableDefinitions() {
3937 return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
40- String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
38+ String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
4139 }
4240
4341 @Override
4442 protected Cluster.Builder configure(Cluster.Builder builder) {
4543 return builder.withQueryOptions(new QueryOptions()
46- .setRefreshNodeIntervalMillis(0)
47- .setRefreshNodeListIntervalMillis(0)
48- .setRefreshSchemaIntervalMillis(0)
44+ .setRefreshNodeIntervalMillis(0)
45+ .setRefreshNodeListIntervalMillis(0)
46+ .setRefreshSchemaIntervalMillis(0)
4947 );
5048 }
5149
@@ -147,7 +145,11 @@
147145 assertEquals(insert.toString(), query);
148146
149147 query = "INSERT INTO foo(a,b) VALUES ({'2''} space','3','4'},3.4) USING TTL 24 AND TIMESTAMP 42;";
150- insert = insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<String>(){{ add("2'} space"); add("3"); add("4"); }}, 3.4 }).using(ttl(24)).and(timestamp(42));
148+ insert = insertInto("foo").values(new String[]{"a", "b"}, new Object[]{new TreeSet<String>() {{
149+ add("2'} space");
150+ add("3");
151+ add("4");
152+ }}, 3.4}).using(ttl(24)).and(timestamp(42));
151153 assertEquals(insert.toString(), query);
152154 }
153155
@@ -215,9 +217,9 @@
215217 }
216218
217219 @Test(groups = "short")
218- @CassandraVersion(major=2.0, minor=7, description="DELETE..IF EXISTS only supported in 2.0.7+ (CASSANDRA-5708)")
220+ @CassandraVersion(major = 2.0, minor = 7, description = "DELETE..IF EXISTS only supported in 2.0.7+ (CASSANDRA-5708)")
219221 public void conditionalDeletesTest() throws Exception {
220- session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)",keyspace));
222+ session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
221223
222224 Statement delete;
223225 Row row;
@@ -241,9 +243,9 @@
241243 }
242244
243245 @Test(groups = "short")
244- @CassandraVersion(major=2.0, minor=13, description="Allow IF EXISTS for UPDATE statements (CASSANDRA-8610)")
246+ @CassandraVersion(major = 2.0, minor = 13, description = "Allow IF EXISTS for UPDATE statements (CASSANDRA-8610)")
245247 public void conditionalUpdatesTest() throws Exception {
246- session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)",keyspace));
248+ session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
247249
248250 Statement update;
249251 Row row;
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +8 −10
@@ -15,19 +15,17 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.*;
19+import org.testng.annotations.Test;
20+
1821 import java.nio.ByteBuffer;
1922 import java.util.Arrays;
2023 import java.util.Collection;
2124
22-import org.testng.annotations.Test;
23-
25+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2426 import static org.testng.Assert.assertEquals;
2527 import static org.testng.Assert.assertNotNull;
2628
27-import com.datastax.driver.core.*;
28-
29-import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
30-
3129 public class QueryBuilderRoutingKeyTest extends CCMBridge.PerClassSingleNodeCluster {
3230
3331 private static final String TABLE_TEXT = "test_text";
@@ -36,15 +34,15 @@
3634 @Override
3735 protected Collection<String> getTableDefinitions() {
3836 return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
39- String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
37+ String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
4038 }
4139
4240 @Override
4341 protected Cluster.Builder configure(Cluster.Builder builder) {
4442 return builder.withQueryOptions(new QueryOptions()
45- .setRefreshNodeIntervalMillis(0)
46- .setRefreshNodeListIntervalMillis(0)
47- .setRefreshSchemaIntervalMillis(0)
43+ .setRefreshNodeIntervalMillis(0)
44+ .setRefreshNodeListIntervalMillis(0)
45+ .setRefreshSchemaIntervalMillis(0)
4846 );
4947 }
5048
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +116 −97
@@ -15,24 +15,20 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.math.BigDecimal;
19-import java.math.BigInteger;
20-import java.net.InetAddress;
21-import java.util.*;
22-
23-import org.testng.annotations.Test;
24-
25-import static org.assertj.core.api.Assertions.assertThat;
26-import static org.testng.Assert.assertEquals;
27-import static org.testng.Assert.assertTrue;
28-import static org.testng.Assert.fail;
29-
3018 import com.datastax.driver.core.ConsistencyLevel;
3119 import com.datastax.driver.core.RegularStatement;
3220 import com.datastax.driver.core.Statement;
3321 import com.datastax.driver.core.exceptions.InvalidQueryException;
22+import org.testng.annotations.Test;
23+
24+import java.math.BigDecimal;
25+import java.math.BigInteger;
26+import java.net.InetAddress;
27+import java.util.*;
3428
3529 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
30+import static org.assertj.core.api.Assertions.assertThat;
31+import static org.testng.Assert.*;
3632
3733 public class QueryBuilderTest {
3834
@@ -52,10 +48,10 @@
5248
5349 query = "SELECT a,b,\"C\" FROM foo WHERE a IN ('127.0.0.1','127.0.0.3') AND \"C\"='foo' ORDER BY a ASC,b DESC LIMIT 42;";
5450 select = select("a", "b", quote("C")).from("foo")
55- .where(in("a", InetAddress.getByName("127.0.0.1"), InetAddress.getByName("127.0.0.3")))
56- .and(eq(quote("C"), "foo"))
57- .orderBy(asc("a"), desc("b"))
58- .limit(42);
51+ .where(in("a", InetAddress.getByName("127.0.0.1"), InetAddress.getByName("127.0.0.3")))
52+ .and(eq(quote("C"), "foo"))
53+ .orderBy(asc("a"), desc("b"))
54+ .limit(42);
5955 assertEquals(select.toString(), query);
6056
6157 query = "SELECT writetime(a),ttl(a) FROM foo ALLOW FILTERING;";
@@ -163,63 +159,67 @@
163159
164160 query = "INSERT INTO foo(a,b,\"C\",d) VALUES (123,'127.0.0.1','foo''bar',{'x':3,'y':2}) USING TIMESTAMP 42 AND TTL 24;";
165161 insert = insertInto("foo")
166- .value("a", 123)
167- .value("b", InetAddress.getByName("127.0.0.1"))
168- .value(quote("C"), "foo'bar")
169- .value("d", new TreeMap<String, Integer>() {{
170- put("x", 3);
171- put("y", 2);
172- }})
173- .using(timestamp(42)).and(ttl(24));
162+ .value("a", 123)
163+ .value("b", InetAddress.getByName("127.0.0.1"))
164+ .value(quote("C"), "foo'bar")
165+ .value("d", new TreeMap<String, Integer>() {{
166+ put("x", 3);
167+ put("y", 2);
168+ }})
169+ .using(timestamp(42)).and(ttl(24));
174170 assertEquals(insert.toString(), query);
175171
176172 query = "INSERT INTO foo(a,b) VALUES (2,null);";
177173 insert = insertInto("foo")
178- .value("a", 2)
179- .value("b", null);
174+ .value("a", 2)
175+ .value("b", null);
180176 assertEquals(insert.toString(), query);
181177
182178 query = "INSERT INTO foo(a,b) VALUES ({2,3,4},3.4) USING TTL 24 AND TIMESTAMP 42;";
183- insert = insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
179+ insert = insertInto("foo").values(new String[]{"a", "b"}, new Object[]{new TreeSet<Integer>() {{
184180 add(2);
185181 add(3);
186182 add(4);
187- }}, 3.4 }).using(ttl(24)).and(timestamp(42));
183+ }}, 3.4}).using(ttl(24)).and(timestamp(42));
188184 assertEquals(insert.toString(), query);
189185
190186 query = "INSERT INTO foo.bar(a,b) VALUES ({2,3,4},3.4) USING TTL ? AND TIMESTAMP ?;";
191187 insert = insertInto("foo", "bar")
192- .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
193- add(2);
194- add(3);
195- add(4);
196- }}, 3.4 })
197- .using(ttl(bindMarker()))
198- .and(timestamp(bindMarker()));
188+ .values(new String[]{"a", "b"}, new Object[]{new TreeSet<Integer>() {{
189+ add(2);
190+ add(3);
191+ add(4);
192+ }}, 3.4})
193+ .using(ttl(bindMarker()))
194+ .and(timestamp(bindMarker()));
199195 assertEquals(insert.toString(), query);
200196
201197 // commutative result of TIMESTAMP
202198 query = "INSERT INTO foo.bar(a,b,c) VALUES ({2,3,4},3.4,123) USING TIMESTAMP 42;";
203199 insert = insertInto("foo", "bar")
204- .using(timestamp(42))
205- .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
206- add(2);
207- add(3);
208- add(4);
209- }}, 3.4 })
210- .value("c", 123);
200+ .using(timestamp(42))
201+ .values(new String[]{"a", "b"}, new Object[]{new TreeSet<Integer>() {{
202+ add(2);
203+ add(3);
204+ add(4);
205+ }}, 3.4})
206+ .value("c", 123);
211207 assertEquals(insert.toString(), query);
212208
213209 // commutative result of value() and values()
214210 query = "INSERT INTO foo(c,a,b) VALUES (123,{2,3,4},3.4) USING TIMESTAMP 42;";
215211 insert = insertInto("foo")
216- .using(timestamp(42))
217- .value("c", 123)
218- .values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<Integer>(){{ add(2); add(3); add(4); }}, 3.4 });
212+ .using(timestamp(42))
213+ .value("c", 123)
214+ .values(new String[]{"a", "b"}, new Object[]{new TreeSet<Integer>() {{
215+ add(2);
216+ add(3);
217+ add(4);
218+ }}, 3.4});
219219 assertEquals(insert.toString(), query);
220220
221221 try {
222- insert = insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ 1, 2, 3 });
222+ insert = insertInto("foo").values(new String[]{"a", "b"}, new Object[]{1, 2, 3});
223223 fail();
224224 } catch (IllegalArgumentException e) {
225225 assertEquals(e.getMessage(), "Got 2 names but 3 values");
@@ -255,20 +255,31 @@
255255 assertEquals(update.toString(), query);
256256
257257 query = "UPDATE foo SET b=b-[1,2,3],c=c+{1},d=d+{2,3,4};";
258- update = update("foo").with(discardAll("b", Arrays.asList(1, 2, 3))).and(add("c", 1)).and(addAll("d", new TreeSet<Integer>(){{ add(2); add(3); add(4); }}));
258+ update = update("foo").with(discardAll("b", Arrays.asList(1, 2, 3))).and(add("c", 1)).and(addAll("d", new TreeSet<Integer>() {{
259+ add(2);
260+ add(3);
261+ add(4);
262+ }}));
259263 assertEquals(update.toString(), query);
260264
261265 query = "UPDATE foo SET b=b-{2,3,4},c['k']='v',d=d+{'x':3,'y':2};";
262- update = update("foo").with(removeAll("b", new TreeSet<Integer>(){{ add(2); add(3); add(4); }}))
263- .and(put("c", "k", "v"))
264- .and(putAll("d", new TreeMap<String, Integer>(){{ put("x", 3); put("y", 2); }}));
266+ update = update("foo").with(removeAll("b", new TreeSet<Integer>() {{
267+ add(2);
268+ add(3);
269+ add(4);
270+ }}))
271+ .and(put("c", "k", "v"))
272+ .and(putAll("d", new TreeMap<String, Integer>() {{
273+ put("x", 3);
274+ put("y", 2);
275+ }}));
265276 assertEquals(update.toString(), query);
266277
267278 query = "UPDATE foo USING TTL 400;";
268279 update = update("foo").using(ttl(400));
269280 assertEquals(update.toString(), query);
270281
271- query = "UPDATE foo SET a="+new BigDecimal(3.2)+",b=42 WHERE k=2;";
282+ query = "UPDATE foo SET a=" + new BigDecimal(3.2) + ",b=42 WHERE k=2;";
272283 update = update("foo").with(set("a", new BigDecimal(3.2))).and(set("b", new BigInteger("42"))).where(eq("k", 2));
273284 assertEquals(update.toString(), query);
274285
@@ -300,7 +311,7 @@
300311 update = update("foo").with(set("x", 3)).where(eq("k", 2)).ifExists();
301312 assertThat(update.toString()).isEqualTo("UPDATE foo SET x=3 WHERE k=2 IF EXISTS;");
302313 }
303-
314+
304315 @Test(groups = "unit")
305316 public void deleteTest() throws Exception {
306317
@@ -373,10 +384,14 @@
373384 query += "DELETE a[3],b['foo'],c FROM foo WHERE k=1;";
374385 query += "APPLY BATCH;";
375386 batch = batch()
376- .add(insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<Integer>(){{ add(2); add(3); add(4); }}, 3.4 }))
377- .add(update("foo").with(setIdx("a", 2, "foo")).and(prependAll("b", Arrays.asList(3, 2, 1))).and(remove("c", "a")).where(eq("k", 2)))
378- .add(delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1)))
379- .using(timestamp(42));
387+ .add(insertInto("foo").values(new String[]{"a", "b"}, new Object[]{new TreeSet<Integer>() {{
388+ add(2);
389+ add(3);
390+ add(4);
391+ }}, 3.4}))
392+ .add(update("foo").with(setIdx("a", 2, "foo")).and(prependAll("b", Arrays.asList(3, 2, 1))).and(remove("c", "a")).where(eq("k", 2)))
393+ .add(delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1)))
394+ .using(timestamp(42));
380395 assertEquals(batch.toString(), query);
381396
382397 // Test passing batch(statement)
@@ -401,10 +416,10 @@
401416 query += "UPDATE foo SET c=c+3;";
402417 query += "APPLY BATCH;";
403418 batch = batch()
404- .add(update("foo").with(incr("a", 1)))
405- .add(update("foo").with(incr("b", 2)))
406- .add(update("foo").with(incr("c", 3)))
407- .using(timestamp(42));
419+ .add(update("foo").with(incr("a", 1)))
420+ .add(update("foo").with(incr("b", 2)))
421+ .add(update("foo").with(incr("c", 3)))
422+ .using(timestamp(42));
408423 assertEquals(batch.toString(), query);
409424
410425 // Test single increments
@@ -414,10 +429,10 @@
414429 query += "UPDATE foo SET c=c+1;";
415430 query += "APPLY BATCH;";
416431 batch = batch()
417- .add(update("foo").with(incr("a")))
418- .add(update("foo").with(incr("b")))
419- .add(update("foo").with(incr("c")))
420- .using(timestamp(42));
432+ .add(update("foo").with(incr("a")))
433+ .add(update("foo").with(incr("b")))
434+ .add(update("foo").with(incr("c")))
435+ .using(timestamp(42));
421436 assertEquals(batch.toString(), query);
422437
423438 // Test value decrements
@@ -427,10 +442,10 @@
427442 query += "UPDATE foo SET c=c-3;";
428443 query += "APPLY BATCH;";
429444 batch = batch()
430- .add(update("foo").with(decr("a", 1)))
431- .add(update("foo").with(decr("b", 2)))
432- .add(update("foo").with(decr("c", 3)))
433- .using(timestamp(42));
445+ .add(update("foo").with(decr("a", 1)))
446+ .add(update("foo").with(decr("b", 2)))
447+ .add(update("foo").with(decr("c", 3)))
448+ .using(timestamp(42));
434449 assertEquals(batch.toString(), query);
435450
436451 // Test single decrements
@@ -440,10 +455,10 @@
440455 query += "UPDATE foo SET c=c-1;";
441456 query += "APPLY BATCH;";
442457 batch = batch()
443- .add(update("foo").with(decr("a")))
444- .add(update("foo").with(decr("b")))
445- .add(update("foo").with(decr("c")))
446- .using(timestamp(42));
458+ .add(update("foo").with(decr("a")))
459+ .add(update("foo").with(decr("b")))
460+ .add(update("foo").with(decr("c")))
461+ .using(timestamp(42));
447462 assertEquals(batch.toString(), query);
448463
449464 // Test negative decrements and negative increments
@@ -453,23 +468,23 @@
453468 query += "UPDATE foo SET c=c-3;";
454469 query += "APPLY BATCH;";
455470 batch = batch()
456- .add(update("foo").with(decr("a", -1)))
457- .add(update("foo").with(incr("b", -2)))
458- .add(update("foo").with(decr("c", 3)))
459- .using(timestamp(42));
471+ .add(update("foo").with(decr("a", -1)))
472+ .add(update("foo").with(incr("b", -2)))
473+ .add(update("foo").with(decr("c", 3)))
474+ .using(timestamp(42));
460475 assertEquals(batch.toString(), query);
461476 }
462477
463- @Test(groups = "unit", expectedExceptions={IllegalArgumentException.class})
478+ @Test(groups = "unit", expectedExceptions = {IllegalArgumentException.class})
464479 public void batchMixedCounterTest() throws Exception {
465480 String query;
466481 Statement batch;
467482
468483 batch = batch()
469- .add(update("foo").with(incr("a", 1)))
470- .add(update("foo").with(set("b", 2)))
471- .add(update("foo").with(incr("c", 3)))
472- .using(timestamp(42));
484+ .add(update("foo").with(incr("a", 1)))
485+ .add(update("foo").with(set("b", 2)))
486+ .add(update("foo").with(incr("c", 3)))
487+ .using(timestamp(42));
473488 }
474489
475490 @Test(groups = "unit")
@@ -479,8 +494,8 @@
479494
480495 query = "INSERT INTO test(k,c) VALUES (0,?);";
481496 insert = insertInto("test")
482- .value("k", 0)
483- .value("c", bindMarker());
497+ .value("k", 0)
498+ .value("c", bindMarker());
484499 assertEquals(insert.toString(), query);
485500 }
486501
@@ -580,7 +595,11 @@
580595 assertEquals(insert.toString(), query);
581596
582597 query = "INSERT INTO foo(a,b) VALUES ({'2''} space','3','4'},3.4) USING TTL 24 AND TIMESTAMP 42;";
583- insert = insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<String>(){{ add("2'} space"); add("3"); add("4"); }}, 3.4 }).using(ttl(24)).and(timestamp(42));
598+ insert = insertInto("foo").values(new String[]{"a", "b"}, new Object[]{new TreeSet<String>() {{
599+ add("2'} space");
600+ add("3");
601+ add("4");
602+ }}, 3.4}).using(ttl(24)).and(timestamp(42));
584603 assertEquals(insert.toString(), query);
585604 }
586605
@@ -680,22 +699,22 @@
680699 @Test(groups = "unit")
681700 public void quotingTest() {
682701 assertEquals(QueryBuilder.select().from("Metrics", "epochs").getQueryString(),
683- "SELECT * FROM Metrics.epochs;");
702+ "SELECT * FROM Metrics.epochs;");
684703 assertEquals(QueryBuilder.select().from("Metrics", quote("epochs")).getQueryString(),
685- "SELECT * FROM Metrics.\"epochs\";");
704+ "SELECT * FROM Metrics.\"epochs\";");
686705 assertEquals(QueryBuilder.select().from(quote("Metrics"), "epochs").getQueryString(),
687- "SELECT * FROM \"Metrics\".epochs;");
706+ "SELECT * FROM \"Metrics\".epochs;");
688707 assertEquals(QueryBuilder.select().from(quote("Metrics"), quote("epochs")).getQueryString(),
689- "SELECT * FROM \"Metrics\".\"epochs\";");
708+ "SELECT * FROM \"Metrics\".\"epochs\";");
690709
691710 assertEquals(QueryBuilder.insertInto("Metrics", "epochs").getQueryString(),
692- "INSERT INTO Metrics.epochs() VALUES ();");
711+ "INSERT INTO Metrics.epochs() VALUES ();");
693712 assertEquals(QueryBuilder.insertInto("Metrics", quote("epochs")).getQueryString(),
694- "INSERT INTO Metrics.\"epochs\"() VALUES ();");
713+ "INSERT INTO Metrics.\"epochs\"() VALUES ();");
695714 assertEquals(QueryBuilder.insertInto(quote("Metrics"), "epochs").getQueryString(),
696- "INSERT INTO \"Metrics\".epochs() VALUES ();");
715+ "INSERT INTO \"Metrics\".epochs() VALUES ();");
697716 assertEquals(QueryBuilder.insertInto(quote("Metrics"), quote("epochs")).getQueryString(),
698- "INSERT INTO \"Metrics\".\"epochs\"() VALUES ();");
717+ "INSERT INTO \"Metrics\".\"epochs\"() VALUES ();");
699718 }
700719
701720 @Test(groups = "unit")
@@ -709,7 +728,7 @@
709728
710729 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)>=('a',2) AND (c1,c2)<('b',0);";
711730 select = select().all().from("foo").where(eq("k", 4)).and(gte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)))
712- .and(lt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("b", 0)));
731+ .and(lt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("b", 0)));
713732 assertEquals(select.toString(), query);
714733
715734 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)<=('a',2);";
@@ -729,8 +748,8 @@
729748
730749 // If the excessive count results from successive DSL calls, we don't check it on the fly so this statement works:
731750 BuiltStatement statement = select().all().from("foo")
732- .where(eq("bar", "a"))
733- .and(in("baz", values.toArray()));
751+ .where(eq("bar", "a"))
752+ .and(in("baz", values.toArray()));
734753
735754 // But we still want to check it client-side, to fail fast instead of sending a bad query to Cassandra.
736755 // getValues() is called on any RegularStatement before we send it (see SessionManager.makeRequestMessage).
@@ -779,12 +798,12 @@
779798 assertThat(select.getValues()).isNull();
780799 }
781800
782- @Test(groups = "unit", expectedExceptions = { IllegalStateException.class })
801+ @Test(groups = "unit", expectedExceptions = {IllegalStateException.class})
783802 public void should_throw_ISE_if_getObject_called_on_statement_without_values() {
784803 select().from("test").where(eq("foo", 42)).getObject(0); // integers are appended to the CQL string
785804 }
786805
787- @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class })
806+ @Test(groups = "unit", expectedExceptions = {IndexOutOfBoundsException.class})
788807 public void should_throw_IOOBE_if_getObject_called_with_wrong_index() {
789808 select().from("test").where(eq("foo", new Object())).getObject(1);
790809 }
modified driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +14 −11
@@ -28,9 +28,10 @@
2828 import org.slf4j.LoggerFactory;
2929
3030 import java.net.InetSocketAddress;
31-import java.net.Socket;
32-import java.net.SocketAddress;
33-import java.util.*;
31+import java.util.Collection;
32+import java.util.Collections;
33+import java.util.Comparator;
34+import java.util.List;
3435 import java.util.concurrent.Executors;
3536 import java.util.concurrent.ScheduledExecutorService;
3637 import java.util.concurrent.TimeUnit;
@@ -70,7 +71,7 @@
7071 public void run() {
7172 try {
7273 report();
73- } catch(Exception e) {
74+ } catch (Exception e) {
7475 logger.error("Error countered.", e);
7576 }
7677 }
@@ -85,7 +86,7 @@
8586
8687 /**
8788 * @return A custom {@link NettyOptions} instance that hooks into afterChannelInitialized added channels may be
88- * monitored.
89+ * monitored.
8990 */
9091 public NettyOptions nettyOptions() {
9192 return nettyOptions;
@@ -100,6 +101,7 @@
100101
101102 /**
102103 * Schedules a {@link #report()} to be called every configured interval.
104+ *
103105 * @param interval how often to report.
104106 * @param timeUnit at what time precision to report at.
105107 */
@@ -115,17 +117,17 @@
115117 }
116118
117119 /**
118- * <p>
120+ * <p/>
119121 * Report for all sockets matching the given predicate. The report format reflects the number of open, closed,
120122 * live and total sockets created. This is logged at DEBUG if enabled.
121- *
122- * <p>
123+ * <p/>
124+ * <p/>
123125 * If TRACE is enabled, each individual socket will be logged as well.
124126 *
125127 * @param channelFilter used to determine which sockets to report on.
126128 */
127129 public void report(Predicate<SocketChannel> channelFilter) {
128- if(logger.isDebugEnabled()) {
130+ if (logger.isDebugEnabled()) {
129131 Iterable<SocketChannel> channels = matchingChannels(channelFilter);
130132 Iterable<SocketChannel> open = Iterables.filter(channels, openChannels);
131133 Iterable<SocketChannel> closed = Iterables.filter(channels, Predicates.not(openChannels));
@@ -137,7 +139,7 @@
137139 Iterables.size(channels),
138140 channelsCreated.get());
139141
140- if(logger.isTraceEnabled()) {
142+ if (logger.isTraceEnabled()) {
141143 logger.trace("Open channels {}.", open);
142144 logger.trace("Closed channels {}.", closed);
143145 }
@@ -149,7 +151,8 @@
149151 public int compare(SocketChannel t0, SocketChannel t1) {
150152 // Should not be null as these are filtered previously in matchingChannels.
151153 assert t0 != null && t0.remoteAddress() != null;
152- assert t1 != null && t1.remoteAddress() != null;;
154+ assert t1 != null && t1.remoteAddress() != null;
155+ ;
153156 return t0.remoteAddress().toString().compareTo(t1.remoteAddress().toString());
154157 }
155158 };
modified driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsTest.java +4 −4
@@ -15,6 +15,9 @@
1515 */
1616 package com.datastax.driver.core.utils;
1717
18+import com.datastax.driver.core.DataType;
19+import org.testng.annotations.Test;
20+
1821 import java.nio.ByteBuffer;
1922 import java.util.HashSet;
2023 import java.util.Random;
@@ -22,12 +25,9 @@
2225 import java.util.UUID;
2326 import java.util.concurrent.ConcurrentSkipListSet;
2427
25-import org.testng.annotations.Test;
2628 import static org.testng.Assert.assertEquals;
2729 import static org.testng.Assert.assertTrue;
2830
29-import com.datastax.driver.core.DataType;
30-
3131 public class UUIDsTest {
3232
3333 @Test(groups = "unit")
@@ -103,7 +103,7 @@
103103 int nbPerTstamp = 10;
104104
105105 for (int i = 0; i < nbTstamp; i++) {
106- long tstamp = (long)random.nextInt();
106+ long tstamp = (long) random.nextInt();
107107 for (int j = 0; j < nbPerTstamp; j++) {
108108 assertWithin(new UUID(UUIDs.makeMSB(UUIDs.fromUnixTimestamp(tstamp)), random.nextLong()), UUIDs.startOf(tstamp), UUIDs.endOf(tstamp));
109109 }
modified driver-dse/src/main/java/com/datastax/driver/auth/DseAuthProvider.java +15 −18
@@ -22,28 +22,28 @@
2222 import java.net.InetSocketAddress;
2323
2424 /**
25- * AuthProvider which supplies authenticator instances for clients to connect t
26- * DSE clusters secured with Kerberos
27- *
25+ * AuthProvider which supplies authenticator instances for clients to connect t
26+ * DSE clusters secured with Kerberos
27+ * <p/>
2828 * The SASL protocol name defaults to "dse"; should you need to change that
2929 * it can be overridden using the <code>dse.sasl.protocol</code> system property.
30- * <p>
30+ * <p/>
3131 * Keytab and ticket cache settings are specified using a standard JAAS
3232 * configuration file. The location of the file can be set using the
3333 * <code>java.security.auth.login.config</code> system property or by adding a
3434 * <code>login.config.url.n</code> entry in the <code>java.security</code> properties
3535 * file.
36- * <p>
37- *
36+ * <p/>
37+ * <p/>
3838 * See the following documents for further details on the
3939 * <a href="https://docs.oracle.com/javase/6/docs/technotes/guides/security/jgss/tutorials/LoginConfigFile.html">JAAS Login Configuration File</a> and the
4040 * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jaas/tutorials/GeneralAcnOnly.html">JAAS Authentication Tutorial</a>
4141 * for more on JAAS in general.
42- *
42+ * <p/>
4343 * <h1>Authentication using ticket cache</h1>
4444 * Run <code>kinit</code> to obtain a ticket and populate the cache before
4545 * connecting. JAAS config:
46-
46+ * <p/>
4747 * <pre>
4848 * DseClient {
4949 * com.sun.security.auth.module.Krb5LoginModule required
@@ -51,13 +51,13 @@
5151 * renewTGT=true;
5252 * };
5353 * </pre>
54- *
55- *
54+ * <p/>
55+ * <p/>
5656 * <h1>Authentication using a keytab file</h1>
5757 * To enable authentication using a keytab file, specify its location on disk.
5858 * If your keytab contains more than one principal key, you should also specify
5959 * which one to select.
60- *
60+ * <p/>
6161 * <pre>
6262 * DseClient {
6363 * com.sun.security.auth.module.Krb5LoginModule required
@@ -66,23 +66,20 @@
6666 * principal="user@MYDOMAIN.COM";
6767 * };
6868 * </pre>
69- *
69+ * <p/>
7070 * To connect to clusters using internal authentication, use the standard method for
7171 * setting credentials. eg:
72- *
72+ * <p/>
7373 * <pre>
7474 * Cluster cluster = Cluster.builder()
7575 * .addContactPoint(hostname)
7676 * .withCredentials("username", "password")
7777 * .build();
7878 * </pre>
79- *
8079 */
81-public class DseAuthProvider implements AuthProvider
82-{
80+public class DseAuthProvider implements AuthProvider {
8381 @Override
84- public Authenticator newAuthenticator(InetSocketAddress host) throws AuthenticationException
85- {
82+ public Authenticator newAuthenticator(InetSocketAddress host) throws AuthenticationException {
8683 return new KerberosAuthenticator(host);
8784 }
8885 }
modified driver-dse/src/main/java/com/datastax/driver/auth/KerberosAuthenticator.java +9 −18
@@ -30,8 +30,7 @@
3030 * PrivilegedSaslClient which performs the priviledged actions on behalf
3131 * of the logged in user.
3232 */
33-public class KerberosAuthenticator implements Authenticator
34-{
33+public class KerberosAuthenticator implements Authenticator {
3534 private static final Logger logger = LoggerFactory.getLogger(KerberosAuthenticator.class);
3635
3736 public static final String JAAS_CONFIG_ENTRY = "DseClient";
@@ -41,8 +40,7 @@
4140
4241 private final PrivilegedSaslClient saslClient;
4342
44- public KerberosAuthenticator(InetSocketAddress host)
45- {
43+ public KerberosAuthenticator(InetSocketAddress host) {
4644 saslClient = new PrivilegedSaslClient(loginSubject(),
4745 SUPPORTED_MECHANISMS,
4846 null,
@@ -52,32 +50,26 @@
5250 null);
5351 }
5452
55- private Subject loginSubject()
56- {
53+ private Subject loginSubject() {
5754 Subject subject = new Subject();
58- try
59- {
55+ try {
6056 LoginContext login = new LoginContext(JAAS_CONFIG_ENTRY, subject);
6157 login.login();
6258 return subject;
63- } catch (LoginException e)
64- {
59+ } catch (LoginException e) {
6560 throw new RuntimeException(e);
6661 }
6762 }
6863
6964 @Override
70- public byte[] initialResponse()
71- {
65+ public byte[] initialResponse() {
7266 return saslClient.getInitialResponse();
7367 }
7468
7569 @Override
76- public byte[] evaluateChallenge(byte[] challenge)
77- {
70+ public byte[] evaluateChallenge(byte[] challenge) {
7871 byte[] response = saslClient.evaluateChallenge(challenge);
79- if (response == null)
80- {
72+ if (response == null) {
8173 // If we generate a null response, then authentication has completed (if
8274 // not, warn), and return without sending a response back to the server.
8375 logger.trace("Response to server is null: authentication should now be complete.");
@@ -91,8 +83,7 @@
9183 }
9284
9385 @Override
94- public void onAuthenticationSuccess(byte[] token)
95- {
86+ public void onAuthenticationSuccess(byte[] token) {
9687 // no-op
9788 }
9889 }
modified driver-dse/src/main/java/com/datastax/driver/auth/PrivilegedSaslClient.java +25 −43
@@ -32,14 +32,12 @@
3232 * the authentication protocol as {@code PrivilegedAction}s with the
3333 * assumed identity of the {@code Subject} supplied in the constructor.
3434 */
35-public class PrivilegedSaslClient
36-{
35+public class PrivilegedSaslClient {
3736 private static final Logger logger = LoggerFactory.getLogger(PrivilegedSaslClient.class);
3837
39- public static final Map<String, String> DEFAULT_PROPERTIES = new HashMap<String, String>()
40- {{
41- put(Sasl.SERVER_AUTH, "true");
42- put(Sasl.QOP, "auth");
38+ public static final Map<String, String> DEFAULT_PROPERTIES = new HashMap<String, String>() {{
39+ put(Sasl.SERVER_AUTH, "true");
40+ put(Sasl.QOP, "auth");
4341 }};
4442 private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
4543
@@ -60,17 +58,13 @@
6058 final String protocol,
6159 final String hostname,
6260 final Map<String, String> properties,
63- final CallbackHandler callbackHandler)
64- {
61+ final CallbackHandler callbackHandler) {
6562 logger.trace("Initalising SASL client");
6663 this.clientIdentity = clientIdentity;
67- saslClient = Subject.doAs(this.clientIdentity, new PrivilegedAction<SaslClient>()
68- {
64+ saslClient = Subject.doAs(this.clientIdentity, new PrivilegedAction<SaslClient>() {
6965 @Override
70- public javax.security.sasl.SaslClient run()
71- {
72- try
73- {
66+ public javax.security.sasl.SaslClient run() {
67+ try {
7468 return Sasl.createSaslClient(
7569 mechanisms,
7670 authzId,
@@ -78,8 +72,7 @@
7872 hostname,
7973 properties,
8074 callbackHandler);
81- } catch (Exception e)
82- {
75+ } catch (Exception e) {
8376 logger.error("Error initialising SASL client", e);
8477 throw new RuntimeException(e);
8578 }
@@ -91,24 +84,19 @@
9184
9285 /**
9386 * Generate an initial token to start the SASL handshake with server.
87+ *
9488 * @return SaslTokenRequestMessage message to be sent to server.
9589 */
96- public byte[] getInitialResponse()
97- {
90+ public byte[] getInitialResponse() {
9891 logger.trace("Initialising SASL handshake from client");
9992 byte[] initialResponse = null;
100- if (saslClient.hasInitialResponse())
101- {
102- initialResponse = Subject.doAs(clientIdentity, new PrivilegedAction<byte[]>()
103- {
93+ if (saslClient.hasInitialResponse()) {
94+ initialResponse = Subject.doAs(clientIdentity, new PrivilegedAction<byte[]>() {
10495 @Override
105- public byte[] run()
106- {
107- try
108- {
96+ public byte[] run() {
97+ try {
10998 return saslClient.evaluateChallenge(EMPTY_BYTE_ARRAY);
110- } catch (Exception e)
111- {
99+ } catch (Exception e) {
112100 throw new RuntimeException(e);
113101 }
114102 }
@@ -119,30 +107,24 @@
119107
120108 /**
121109 * Respond to server's SASL token
110+ *
122111 * @param challenge contains server's SASL token
123112 * @return client's response SASL token, which will be null if authentication is complete
124113 */
125- public byte[] evaluateChallenge(final byte[] challenge)
126- {
114+ public byte[] evaluateChallenge(final byte[] challenge) {
127115 logger.trace("Evaluating SASL server token");
128- if (saslClient.isComplete())
129- {
116+ if (saslClient.isComplete()) {
130117 return null;
131118 }
132- byte[] retval = Subject.doAs(clientIdentity, new PrivilegedAction<byte[]>()
133- {
119+ byte[] retval = Subject.doAs(clientIdentity, new PrivilegedAction<byte[]>() {
134120 @Override
135- public byte[] run()
136- {
137- try
138- {
121+ public byte[] run() {
122+ try {
139123 logger.trace("SASL client evaluating challenge");
140124 byte[] retval = saslClient.evaluateChallenge(challenge);
141125 logger.trace("SASL client is complete = " + saslClient.isComplete());
142126 return retval;
143- }
144- catch (SaslException e)
145- {
127+ } catch (SaslException e) {
146128 logger.error("Failed to generate response to SASL server's token:", e);
147129 throw new RuntimeException(e);
148130 }
@@ -153,10 +135,10 @@
153135
154136 /**
155137 * Is the SASL negotiation with the server complete
138+ *
156139 * @return true iff SASL authentication has successfully completed
157140 */
158- public boolean isComplete()
159- {
141+ public boolean isComplete() {
160142 return saslClient.isComplete();
161143 }
162144 }
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java +7 −6
@@ -46,13 +46,14 @@
4646 return body;
4747 }
4848
49- @Override public boolean equals(Object that) {
50- if(that instanceof MailboxMessage) {
51- MailboxMessage thatM = (MailboxMessage)that;
49+ @Override
50+ public boolean equals(Object that) {
51+ if (that instanceof MailboxMessage) {
52+ MailboxMessage thatM = (MailboxMessage) that;
5253 return recipient.equals(thatM.getRecipient()) &&
53- date.equals(thatM.getDate()) &&
54- sender.equals(thatM.getSender()) &&
55- body.equals(thatM.getBody());
54+ date.equals(thatM.getDate()) &&
55+ sender.equals(thatM.getSender()) &&
56+ body.equals(thatM.getBody());
5657 } else {
5758 return false;
5859 }
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxService.java +3 −0
@@ -22,6 +22,7 @@
2222
2323 /**
2424 * Retrieve all messages for a given recipient.
25+ *
2526 * @param recipient User whose mailbox is being read.
2627 * @return All messages in the mailbox.
2728 */
@@ -29,6 +30,7 @@
2930
3031 /**
3132 * Stores the given message in the appropriate mailbox.
33+ *
3234 * @param message Message to send.
3335 * @return UUID generated for the message.
3436 */
@@ -36,6 +38,7 @@
3638
3739 /**
3840 * Deletes all mail for the given recipient.
41+ *
3942 * @param recipient User whose mailbox will be cleared.
4043 */
4144 public void clearMailbox(String recipient) throws MailboxException;
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/Activator.java +11 −10
@@ -15,28 +15,28 @@
1515 */
1616 package com.datastax.driver.osgi.impl;
1717
18-import java.util.Hashtable;
19-
20-import org.osgi.framework.BundleActivator;
21-import org.osgi.framework.BundleContext;
22-
2318 import com.datastax.driver.core.Cluster;
2419 import com.datastax.driver.core.Session;
2520 import com.datastax.driver.osgi.api.MailboxService;
21+import org.osgi.framework.BundleActivator;
22+import org.osgi.framework.BundleContext;
23+
24+import java.util.Hashtable;
2625
2726 public class Activator implements BundleActivator {
2827
2928 private Cluster cluster;
3029
31- @Override public void start(BundleContext context) throws Exception {
30+ @Override
31+ public void start(BundleContext context) throws Exception {
3232 String contactPointsStr = context.getProperty("cassandra.contactpoints");
33- if(contactPointsStr == null) {
33+ if (contactPointsStr == null) {
3434 contactPointsStr = "127.0.0.1";
3535 }
3636 String[] contactPoints = contactPointsStr.split(",");
3737
3838 String keyspace = context.getProperty("cassandra.keyspace");
39- if(keyspace == null) {
39+ if (keyspace == null) {
4040 keyspace = "mailbox";
4141 }
4242
@@ -49,8 +49,9 @@
4949 context.registerService(MailboxService.class.getName(), mailbox, new Hashtable<String, String>());
5050 }
5151
52- @Override public void stop(BundleContext context) throws Exception {
53- if(cluster != null) {
52+ @Override
53+ public void stop(BundleContext context) throws Exception {
54+ if (cluster != null) {
5455 cluster.close();
5556 }
5657 }
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java +33 −34
@@ -15,11 +15,6 @@
1515 */
1616 package com.datastax.driver.osgi.impl;
1717
18-import java.util.ArrayList;
19-import java.util.Collection;
20-import java.util.Date;
21-import java.util.UUID;
22-
2318 import com.datastax.driver.core.*;
2419 import com.datastax.driver.core.exceptions.InvalidQueryException;
2520 import com.datastax.driver.core.utils.UUIDs;
@@ -27,11 +22,12 @@
2722 import com.datastax.driver.osgi.api.MailboxMessage;
2823 import com.datastax.driver.osgi.api.MailboxService;
2924
30-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.delete;
32-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
33-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
34-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
25+import java.util.ArrayList;
26+import java.util.Collection;
27+import java.util.Date;
28+import java.util.UUID;
29+
30+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3531
3632 public class MailboxImpl implements MailboxService {
3733
@@ -55,7 +51,7 @@
5551 }
5652
5753 public synchronized void init() {
58- if(initialized)
54+ if (initialized)
5955 return;
6056
6157 // Create the schema if it does not exist.
@@ -63,53 +59,55 @@
6359 session.execute("USE " + keyspace);
6460 } catch (InvalidQueryException e) {
6561 session.execute("CREATE KEYSPACE " + keyspace +
66- " with replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}");
62+ " with replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}");
6763
6864 session.execute("CREATE TABLE " + keyspace + "." + TABLE + " (" +
69- "recipient text," +
70- "time timeuuid," +
71- "sender text," +
72- "body text," +
73- "PRIMARY KEY (recipient, time))");
65+ "recipient text," +
66+ "time timeuuid," +
67+ "sender text," +
68+ "body text," +
69+ "PRIMARY KEY (recipient, time))");
7470 }
7571
7672 retrieveStatement = session.prepare(select()
77- .from(keyspace, TABLE)
78- .where(eq("recipient", bindMarker())));
73+ .from(keyspace, TABLE)
74+ .where(eq("recipient", bindMarker())));
7975
8076 insertStatement = session.prepare(insertInto(keyspace, TABLE)
81- .value("recipient", bindMarker())
82- .value("time", bindMarker())
83- .value("sender", bindMarker())
84- .value("body", bindMarker()));
77+ .value("recipient", bindMarker())
78+ .value("time", bindMarker())
79+ .value("sender", bindMarker())
80+ .value("body", bindMarker()));
8581
8682 deleteStatement = session.prepare(delete().from(keyspace, TABLE)
87- .where(eq("recipient", bindMarker())));
83+ .where(eq("recipient", bindMarker())));
8884
8985 initialized = true;
9086 }
9187
92- @Override public Collection<MailboxMessage> getMessages(String recipient) throws MailboxException {
88+ @Override
89+ public Collection<MailboxMessage> getMessages(String recipient) throws MailboxException {
9390 try {
9491 BoundStatement statement = new BoundStatement(retrieveStatement);
9592 statement.setString(0, recipient);
9693 ResultSet result = session.execute(statement);
9794
9895 Collection<MailboxMessage> messages = new ArrayList<MailboxMessage>();
99- for(Row input : result) {
96+ for (Row input : result) {
10097 Date date = new Date(UUIDs.unixTimestamp(input.getUUID("time")));
10198 messages.add(new MailboxMessage(input.getString("recipient"),
102- date,
103- input.getString("sender"),
104- input.getString("body")));
99+ date,
100+ input.getString("sender"),
101+ input.getString("body")));
105102 }
106103 return messages;
107- } catch(Exception e) {
104+ } catch (Exception e) {
108105 throw new MailboxException(e);
109106 }
110107 }
111108
112- @Override public UUID sendMessage(MailboxMessage message) throws MailboxException {
109+ @Override
110+ public UUID sendMessage(MailboxMessage message) throws MailboxException {
113111 try {
114112 UUID time = UUIDs.startOf(message.getDate().getTime());
115113
@@ -121,17 +119,18 @@
121119
122120 session.execute(statement);
123121 return time;
124- } catch(Exception e) {
122+ } catch (Exception e) {
125123 throw new MailboxException(e);
126124 }
127125 }
128126
129- @Override public void clearMailbox(String recipient) throws MailboxException {
127+ @Override
128+ public void clearMailbox(String recipient) throws MailboxException {
130129 try {
131130 BoundStatement statement = new BoundStatement(deleteStatement);
132131 statement.setString(0, recipient);
133132 session.execute(statement);
134- } catch(Exception e) {
133+ } catch (Exception e) {
135134 throw new MailboxException(e);
136135 }
137136 }
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java +22 −11
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.osgi;
1717
18+import com.datastax.driver.core.CCMBridge;
1819 import org.testng.ITestContext;
1920 import org.testng.ITestListener;
2021 import org.testng.ITestResult;
2122
22-import com.datastax.driver.core.CCMBridge;
23-
2423 /**
2524 * A listener that fires up a single node CCM instance on test class start and tears it
2625 * down on test class end.
27- *
26+ * <p/>
2827 * This is needed for tests that use Pax-Exam since it runs some methods in the OSGi container
2928 * which we do not want.
3029 */
@@ -32,23 +31,35 @@
3231
3332 private CCMBridge ccm;
3433
35- @Override public void onStart(ITestContext context) {
34+ @Override
35+ public void onStart(ITestContext context) {
3636 ccm = CCMBridge.builder("test").withNodes(1).build();
3737 }
3838
39- @Override public void onFinish(ITestContext context) {
40- if(ccm != null) {
39+ @Override
40+ public void onFinish(ITestContext context) {
41+ if (ccm != null) {
4142 ccm.remove();
4243 }
4344 }
4445
45- @Override public void onTestStart(ITestResult result) {}
46+ @Override
47+ public void onTestStart(ITestResult result) {
48+ }
4649
47- @Override public void onTestSuccess(ITestResult result) {}
50+ @Override
51+ public void onTestSuccess(ITestResult result) {
52+ }
4853
49- @Override public void onTestFailure(ITestResult result) {}
54+ @Override
55+ public void onTestFailure(ITestResult result) {
56+ }
5057
51- @Override public void onTestSkipped(ITestResult result) {}
58+ @Override
59+ public void onTestSkipped(ITestResult result) {
60+ }
5261
53- @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {}
62+ @Override
63+ public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
64+ }
5465 }
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceIT.java +59 −58
@@ -15,11 +15,10 @@
1515 */
1616 package com.datastax.driver.osgi;
1717
18-import java.util.ArrayList;
19-import java.util.Collection;
20-import java.util.GregorianCalendar;
21-
22-import javax.inject.Inject;
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.osgi.api.MailboxException;
20+import com.datastax.driver.osgi.api.MailboxMessage;
21+import com.datastax.driver.osgi.api.MailboxService;
2322 import org.ops4j.pax.exam.Configuration;
2423 import org.ops4j.pax.exam.Option;
2524 import org.ops4j.pax.exam.options.CompositeOption;
@@ -29,20 +28,20 @@
2928 import org.testng.annotations.Listeners;
3029 import org.testng.annotations.Test;
3130
32-import static org.ops4j.pax.exam.CoreOptions.*;
33-import static org.testng.Assert.assertEquals;
34-
35-import com.datastax.driver.core.CCMBridge;
36-import com.datastax.driver.osgi.api.MailboxException;
37-import com.datastax.driver.osgi.api.MailboxMessage;
38-import com.datastax.driver.osgi.api.MailboxService;
31+import javax.inject.Inject;
32+import java.util.ArrayList;
33+import java.util.Collection;
34+import java.util.GregorianCalendar;
3935
4036 import static com.datastax.driver.osgi.VersionProvider.projectVersion;
37+import static org.ops4j.pax.exam.CoreOptions.*;
38+import static org.testng.Assert.assertEquals;
4139
4240 @Listeners({CCMBridgeListener.class, PaxExam.class})
43-@Test(groups="short")
41+@Test(groups = "short")
4442 public class MailboxServiceIT {
45- @Inject MailboxService service;
43+ @Inject
44+ MailboxService service;
4645
4746 private UrlProvisionOption driverBundle() {
4847 return driverBundle(false);
@@ -61,13 +60,14 @@
6160 final String nettyVersion = "4.0.27.Final";
6261 return new CompositeOption() {
6362
64- @Override public Option[] getOptions() {
63+ @Override
64+ public Option[] getOptions() {
6565 return options(
66- mavenBundle("io.netty", "netty-buffer", nettyVersion),
67- mavenBundle("io.netty", "netty-codec", nettyVersion),
68- mavenBundle("io.netty", "netty-common", nettyVersion),
69- mavenBundle("io.netty", "netty-handler", nettyVersion),
70- mavenBundle("io.netty", "netty-transport", nettyVersion)
66+ mavenBundle("io.netty", "netty-buffer", nettyVersion),
67+ mavenBundle("io.netty", "netty-codec", nettyVersion),
68+ mavenBundle("io.netty", "netty-common", nettyVersion),
69+ mavenBundle("io.netty", "netty-handler", nettyVersion),
70+ mavenBundle("io.netty", "netty-transport", nettyVersion)
7171 );
7272 }
7373 };
@@ -76,15 +76,16 @@
7676 private CompositeOption defaultOptions() {
7777 return new CompositeOption() {
7878
79- @Override public Option[] getOptions() {
79+ @Override
80+ public Option[] getOptions() {
8081 return options(
81- systemProperty("cassandra.contactpoints").value(CCMBridge.IP_PREFIX + 1),
82- bundle("reference:file:target/classes"),
83- mavenBundle("com.codahale.metrics", "metrics-core", "3.0.2"),
84- mavenBundle("org.slf4j", "slf4j-api", "1.7.5"),
85- mavenBundle("org.slf4j", "slf4j-simple", "1.7.5").noStart(),
86- systemPackages("org.testng", "org.junit", "org.junit.runner", "org.junit.runner.manipulation",
87- "org.junit.runner.notification", "com.jcabi.manifests")
82+ systemProperty("cassandra.contactpoints").value(CCMBridge.IP_PREFIX + 1),
83+ bundle("reference:file:target/classes"),
84+ mavenBundle("com.codahale.metrics", "metrics-core", "3.0.2"),
85+ mavenBundle("org.slf4j", "slf4j-api", "1.7.5"),
86+ mavenBundle("org.slf4j", "slf4j-simple", "1.7.5").noStart(),
87+ systemPackages("org.testng", "org.junit", "org.junit.runner", "org.junit.runner.manipulation",
88+ "org.junit.runner.notification", "com.jcabi.manifests")
8889 );
8990 }
9091 };
@@ -93,59 +94,59 @@
9394 @Configuration
9495 public Option[] shadedConfig() {
9596 return options(
96- driverBundle(true),
97- guavaBundle(),
98- defaultOptions()
97+ driverBundle(true),
98+ guavaBundle(),
99+ defaultOptions()
99100 );
100101 }
101102
102103 @Configuration
103104 public Option[] defaultConfig() {
104105 return options(
105- driverBundle(),
106- guavaBundle(),
107- nettyBundles(),
108- defaultOptions()
106+ driverBundle(),
107+ guavaBundle(),
108+ nettyBundles(),
109+ defaultOptions()
109110 );
110111 }
111112
112113 @Configuration
113114 public Option[] guava15Config() {
114115 return options(
115- driverBundle(),
116- nettyBundles(),
117- guavaBundle().version("15.0"),
118- defaultOptions()
116+ driverBundle(),
117+ nettyBundles(),
118+ guavaBundle().version("15.0"),
119+ defaultOptions()
119120 );
120121 }
121122
122123 @Configuration
123124 public Option[] guava16Config() {
124125 return options(
125- driverBundle(),
126- nettyBundles(),
127- guavaBundle().version("16.0.1"),
128- defaultOptions()
126+ driverBundle(),
127+ nettyBundles(),
128+ guavaBundle().version("16.0.1"),
129+ defaultOptions()
129130 );
130131 }
131132
132133 @Configuration
133134 public Option[] guava17Config() {
134135 return options(
135- driverBundle(),
136- nettyBundles(),
137- guavaBundle().version("17.0"),
138- defaultOptions()
136+ driverBundle(),
137+ nettyBundles(),
138+ guavaBundle().version("17.0"),
139+ defaultOptions()
139140 );
140141 }
141142
142143 @Configuration
143144 public Option[] guava18Config() {
144145 return options(
145- driverBundle(),
146- nettyBundles(),
147- guavaBundle().version("18.0"),
148- defaultOptions()
146+ driverBundle(),
147+ nettyBundles(),
148+ guavaBundle().version("18.0"),
149+ defaultOptions()
149150 );
150151 }
151152
@@ -154,15 +155,15 @@
154155 * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver. Ensures that
155156 * queries can be made through the service with the current given configuration.
156157 * </p>
157- *
158+ * <p/>
158159 * The following configurations are tried (defined via methods with the @Configuration annotation):
159160 * <ol>
160- * <li>Default bundle (Driver with all of it's dependencies)</li>
161- * <li>Shaded bundle (Driver with netty shaded)</li>
162- * <li>With Guava 15</li>
163- * <li>With Guava 16</li>
164- * <li>With Guava 17</li>
165- * <li>With Guava 18</li>
161+ * <li>Default bundle (Driver with all of it's dependencies)</li>
162+ * <li>Shaded bundle (Driver with netty shaded)</li>
163+ * <li>With Guava 15</li>
164+ * <li>With Guava 16</li>
165+ * <li>With Guava 17</li>
166+ * <li>With Guava 18</li>
166167 * </ol>
167168 *
168169 * @test_category packaging
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/VersionProvider.java +2 −1
@@ -20,12 +20,13 @@
2020 /**
2121 * Attempts to resolve the project version from the Bundle manifest. If not present, will throw RuntimeException
2222 * on initialization. If this happens, try building with 'mvn compile' to generate the Bundle manifest.
23- *
23+ * <p/>
2424 * In IntelliJ you can have compile run after make by right clicking on 'compile' in the 'Maven Projects' tool window.
2525 */
2626 public class VersionProvider {
2727
2828 private static String PROJECT_VERSION;
29+
2930 static {
3031 String bundleName = Manifests.read("Bundle-SymbolicName");
3132 if (bundleName.equals("com.datastax.driver.osgi")) {
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/AsynchronousConsumer.java +6 −8
@@ -15,17 +15,15 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.util.Iterator;
19-import java.util.concurrent.CountDownLatch;
20-import java.util.concurrent.ExecutorService;
21-import java.util.concurrent.Executors;
22-
23-import com.google.common.util.concurrent.FutureCallback;
24-import com.google.common.util.concurrent.Futures;
25-
2618 import com.datastax.driver.core.ResultSet;
2719 import com.datastax.driver.core.ResultSetFuture;
2820 import com.datastax.driver.core.Session;
21+import com.google.common.util.concurrent.FutureCallback;
22+import com.google.common.util.concurrent.Futures;
23+
24+import java.util.concurrent.CountDownLatch;
25+import java.util.concurrent.ExecutorService;
26+import java.util.concurrent.Executors;
2927
3028 import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly;
3129
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/BlockingConsumer.java +1 −4
@@ -15,12 +15,9 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.util.Iterator;
19-
20-import com.google.common.util.concurrent.Uninterruptibles;
21-
2218 import com.datastax.driver.core.Session;
2319 import com.datastax.driver.core.exceptions.DriverException;
20+import com.google.common.util.concurrent.Uninterruptibles;
2421
2522 public class BlockingConsumer implements Consumer {
2623
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Consumer.java +1 −0
@@ -18,5 +18,6 @@
1818 public interface Consumer {
1919
2020 public void start();
21+
2122 public void join();
2223 }
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Generators.java +14 −15
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Random;
20-
2118 import com.datastax.driver.core.*;
22-import com.datastax.driver.core.exceptions.*;
19+import com.datastax.driver.core.exceptions.QueryValidationException;
2320 import com.datastax.driver.core.utils.Bytes;
24-
2521 import joptsimple.OptionParser;
2622 import joptsimple.OptionSet;
2723
24+import java.nio.ByteBuffer;
25+import java.util.Random;
26+
2827 public class Generators {
2928 private static ThreadLocal<Random> random = new ThreadLocal<Random>() {
3029 protected Random initialValue() {
@@ -69,7 +68,7 @@
6968
7069 public OptionParser addOptions(OptionParser parser) {
7170 String msg = "Simple insertion of CQL3 rows (using prepared statements unless the --no-prepare option is used). "
72- + "The inserted rows have a fixed set of columns but no clustering columns.";
71+ + "The inserted rows have a fixed set of columns but no clustering columns.";
7372 parser.formatHelpWith(Stress.Help.formatFor(name(), msg));
7473
7574 parser.accepts("no-prepare", "Do no use prepared statement");
@@ -91,7 +90,7 @@
9190
9291 StringBuilder sb = new StringBuilder();
9392 sb.append("CREATE TABLE standard1 (key bigint PRIMARY KEY");
94- for (int i = 0; i < (Integer)options.valueOf("columns-per-row"); ++i)
93+ for (int i = 0; i < (Integer) options.valueOf("columns-per-row"); ++i)
9594 sb.append(", C").append(i).append(" blob");
9695 sb.append(')');
9796
@@ -104,13 +103,13 @@
104103 public QueryGenerator create(int id, int iterations, OptionSet options, Session session) {
105104
106105 return options.has("no-prepare")
107- ? createRegular(id, iterations, options)
108- : createPrepared(id, iterations, options, session);
106+ ? createRegular(id, iterations, options)
107+ : createPrepared(id, iterations, options, session);
109108 }
110109
111110 public QueryGenerator createRegular(int id, int iterations, OptionSet options) {
112- final int valueSize = (Integer)options.valueOf("value-size");
113- final int columnsPerRow = (Integer)options.valueOf("columns-per-row");
111+ final int valueSize = (Integer) options.valueOf("value-size");
112+ final int columnsPerRow = (Integer) options.valueOf("columns-per-row");
114113 final long prefix = (long) id << 32;
115114
116115 return new AbstractGenerator(iterations) {
@@ -130,8 +129,8 @@
130129 }
131130
132131 public QueryGenerator createPrepared(int id, int iterations, OptionSet options, Session session) {
133- final int valueSize = (Integer)options.valueOf("value-size");
134- final int columnsPerRow = (Integer)options.valueOf("columns-per-row");
132+ final int valueSize = (Integer) options.valueOf("value-size");
133+ final int columnsPerRow = (Integer) options.valueOf("columns-per-row");
135134 final long prefix = (long) id << 32;
136135
137136 StringBuilder sb = new StringBuilder();
@@ -184,8 +183,8 @@
184183
185184 public QueryGenerator create(int id, int iterations, OptionSet options, Session session) {
186185 return options.has("no-prepare")
187- ? createRegular(id, iterations)
188- : createPrepared(id, iterations, session);
186+ ? createRegular(id, iterations)
187+ : createPrepared(id, iterations, session);
189188 }
190189
191190 public QueryGenerator createRegular(long id, int iterations) {
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/QueryGenerator.java +5 −3
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.util.Iterator;
19-
2018 import com.datastax.driver.core.*;
21-
2219 import joptsimple.OptionParser;
2320 import joptsimple.OptionSet;
2421
22+import java.util.Iterator;
23+
2524 public abstract class QueryGenerator implements Iterator<QueryGenerator.Request> {
2625
2726 protected final int iterations;
@@ -38,8 +37,11 @@
3837
3938 public interface Builder {
4039 public String name();
40+
4141 public OptionParser addOptions(OptionParser parser);
42+
4243 public void prepare(OptionSet options, Session session);
44+
4345 public QueryGenerator create(int id, int iterations, OptionSet options, Session session);
4446 }
4547
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Reporter.java +23 −17
@@ -15,15 +15,21 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.io.*;
19-import java.util.concurrent.*;
20-import java.util.concurrent.atomic.AtomicInteger;
21-
2218 import com.yammer.metrics.Metrics;
23-import com.yammer.metrics.core.*;
24-import com.yammer.metrics.reporting.*;
19+import com.yammer.metrics.core.Meter;
20+import com.yammer.metrics.core.Timer;
21+import com.yammer.metrics.core.TimerContext;
2522 import com.yammer.metrics.stats.Snapshot;
2623
24+import java.io.File;
25+import java.io.FileOutputStream;
26+import java.io.IOException;
27+import java.io.PrintStream;
28+import java.util.concurrent.Executors;
29+import java.util.concurrent.ScheduledExecutorService;
30+import java.util.concurrent.TimeUnit;
31+import java.util.concurrent.atomic.AtomicInteger;
32+
2733 public class Reporter implements Runnable {
2834
2935 private Meter requests;
@@ -67,8 +73,8 @@
6773 this.iterations = iterations;
6874
6975 // Middle = exclude first and last 10% (note: if requests is -1, we'll end up with negative bounds, which will always exclude. It's fine if we never stop anyway)
70- this.middleLowBound = (int)(0.1 * iterations);
71- this.middleHighBound = (int)(0.9 * iterations);
76+ this.middleLowBound = (int) (0.1 * iterations);
77+ this.middleHighBound = (int) (0.9 * iterations);
7278 }
7379
7480 private static String formatHeader(String[] args) {
@@ -162,14 +168,14 @@
162168
163169 private void reportToCSV(Report report) {
164170 csv.println(new StringBuilder()
165- .append(report.elapsed).append(',')
166- .append(report.totalOps).append(',')
167- .append(report.intervalRate).append(',')
168- .append(report.meanRate).append(',')
169- .append(report.meanLatency).append(',')
170- .append(report.latency95th).append(',')
171- .append(report.latency99th).append(',')
172- .append(report.stdDev));
171+ .append(report.elapsed).append(',')
172+ .append(report.totalOps).append(',')
173+ .append(report.intervalRate).append(',')
174+ .append(report.meanRate).append(',')
175+ .append(report.meanLatency).append(',')
176+ .append(report.latency95th).append(',')
177+ .append(report.latency99th).append(',')
178+ .append(report.stdDev));
173179 }
174180
175181 private void stopCSV(Report lastReport) {
@@ -197,7 +203,7 @@
197203
198204 private void printReportToConsole(Report report) {
199205 long delay = report.timestamp - lastConsoleTimestamp;
200- double intervalRate = (((double)(report.totalOps - lastConsoleOpCount)) / delay) * 1000;
206+ double intervalRate = (((double) (report.totalOps - lastConsoleOpCount)) / delay) * 1000;
201207
202208 String msg = String.format(" %8d | %12d | %13.2f | %12.2f | %17.3f | %17.3f | %17.3f | %9.3f",
203209 report.elapsed, report.totalOps, intervalRate, report.meanRate, report.meanLatency, report.latency95th, report.latency99th, report.stdDev);
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Stress.java +27 −26
@@ -15,32 +15,33 @@
1515 */
1616 package com.datastax.driver.stress;
1717
18-import java.io.IOException;
19-import java.util.*;
20-
2118 import com.datastax.driver.core.*;
22-import com.datastax.driver.core.exceptions.*;
23-
19+import com.datastax.driver.core.exceptions.NoHostAvailableException;
20+import joptsimple.*;
2421 import org.apache.log4j.PropertyConfigurator;
2522
26-import joptsimple.*;
23+import java.io.IOException;
24+import java.util.HashMap;
25+import java.util.List;
26+import java.util.Map;
2727
2828 /**
2929 * A simple stress tool to demonstrate the use of the driver.
30- *
30+ * <p/>
3131 * Sample usage:
32- * stress insert -n 100000
33- * stress read -n 10000
32+ * stress insert -n 100000
33+ * stress read -n 10000
3434 */
3535 public class Stress {
3636
3737 private static final Map<String, QueryGenerator.Builder> generators = new HashMap<String, QueryGenerator.Builder>();
38+
3839 static {
3940 PropertyConfigurator.configure(System.getProperty("log4j.configuration", "./conf/log4j.properties"));
4041
41- QueryGenerator.Builder[] gs = new QueryGenerator.Builder[] {
42- Generators.INSERTER,
43- Generators.READER
42+ QueryGenerator.Builder[] gs = new QueryGenerator.Builder[]{
43+ Generators.INSERTER,
44+ Generators.READER
4445 };
4546
4647 for (QueryGenerator.Builder b : gs)
@@ -60,7 +61,7 @@
6061 accepts("connections-per-host", "The number of connections per hosts (default: based on the number of threads)").withRequiredArg().ofType(Integer.class);
6162 }};
6263 String msg = "Where <generator> can be one of " + generators.keySet() + '\n'
63- + "You can get more help on a particular generator with: stress <generator> -h";
64+ + "You can get more help on a particular generator with: stress <generator> -h";
6465 parser.formatHelpWith(Help.formatFor("<generator>", msg));
6566 return parser;
6667 }
@@ -175,7 +176,7 @@
175176 public static Help formatFor(String generator, String header) {
176177 // It's a pain in the ass to get the real console width in JAVA so hardcode it. But it's the 21th
177178 // century, we're not stuck at 80 characters anymore.
178- int width = 120;
179+ int width = 120;
179180 return new Help(new BuiltinHelpFormatter(width, 4), generator, header);
180181 }
181182
@@ -195,19 +196,19 @@
195196 Stresser stresser = Stresser.forCommandLineArguments(args);
196197 OptionSet options = stresser.getOptions();
197198
198- int requests = options.has("n") ? (Integer)options.valueOf("n") : -1;
199- int concurrency = (Integer)options.valueOf("t");
199+ int requests = options.has("n") ? (Integer) options.valueOf("n") : -1;
200+ int concurrency = (Integer) options.valueOf("t");
200201
201- String reportFileName = (String)options.valueOf("report-file");
202+ String reportFileName = (String) options.valueOf("report-file");
202203
203204 boolean async = options.has("async");
204205
205- int iterations = (requests == -1 ? -1 : requests / concurrency);
206+ int iterations = (requests == -1 ? -1 : requests / concurrency);
206207
207208 final int maxRequestsPerConnection = 128;
208209 int maxConnections = options.has("connections-per-host")
209- ? (Integer)options.valueOf("connections-per-host")
210- : concurrency / maxRequestsPerConnection + 1;
210+ ? (Integer) options.valueOf("connections-per-host")
211+ : concurrency / maxRequestsPerConnection + 1;
211212
212213 PoolingOptions pools = new PoolingOptions();
213214 pools.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, concurrency);
@@ -226,10 +227,10 @@
226227 try {
227228 // Create session to hosts
228229 Cluster cluster = new Cluster.Builder()
229- .addContactPoints(String.valueOf(options.valueOf("ip")))
230- .withPoolingOptions(pools)
231- .withSocketOptions(new SocketOptions().setTcpNoDelay(true))
232- .build();
230+ .addContactPoints(String.valueOf(options.valueOf("ip")))
231+ .withPoolingOptions(pools)
232+ .withSocketOptions(new SocketOptions().setTcpNoDelay(true))
233+ .build();
233234
234235 if (options.has("compression"))
235236 cluster.getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.SNAPPY);
@@ -242,13 +243,13 @@
242243 System.out.println("Preparing test...");
243244 stresser.prepare(session);
244245
245- Reporter reporter = new Reporter((Integer)options.valueOf("print-delay"), reportFileName, args, requests);
246+ Reporter reporter = new Reporter((Integer) options.valueOf("print-delay"), reportFileName, args, requests);
246247
247248 Consumer[] consumers = new Consumer[concurrency];
248249 for (int i = 0; i < concurrency; i++) {
249250 QueryGenerator generator = stresser.newGenerator(i, session, iterations);
250251 consumers[i] = async ? new AsynchronousConsumer(session, generator, reporter) :
251- new BlockingConsumer(session, generator, reporter);
252+ new BlockingConsumer(session, generator, reporter);
252253 }
253254
254255 System.out.println("Starting to stress test...");